xref: /btstack/src/ble/gatt_client.c (revision 3a19f7e295cb91ddc14d9634b76a83dbe469d59f)
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             break;
1232         }
1233 #endif
1234         default:
1235             done = 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 #endif
1293         // handle GATT over LE
1294         if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) {
1295             att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1296             return;
1297         }
1298         bool packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1299         if (packet_sent){
1300             // request new permission
1301             att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1302             // requeue client for fairness and exit
1303             // note: iterator has become invalid
1304             btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1305             btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1306             return;
1307         }
1308     }
1309 }
1310 
1311 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code) {
1312     if (is_ready(gatt_client) == 1) return;
1313     gatt_client_handle_transaction_complete(gatt_client);
1314     emit_gatt_complete_event(gatt_client, att_error_code);
1315 }
1316 
1317 static void gatt_client_handle_reencryption_complete(const uint8_t * packet){
1318     hci_con_handle_t con_handle = sm_event_reencryption_complete_get_handle(packet);
1319     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1320     if (gatt_client == NULL) return;
1321 
1322     // update security level
1323     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1324 
1325     gatt_client->reencryption_result = sm_event_reencryption_complete_get_status(packet);
1326     gatt_client->reencryption_active = false;
1327     gatt_client->wait_for_authentication_complete = 0;
1328 
1329     if (gatt_client->gatt_client_state == P_READY) return;
1330 
1331     switch (sm_event_reencryption_complete_get_status(packet)){
1332         case ERROR_CODE_SUCCESS:
1333             log_info("re-encryption success, retry operation");
1334             break;
1335         case ERROR_CODE_AUTHENTICATION_FAILURE:
1336         case ERROR_CODE_PIN_OR_KEY_MISSING:
1337 #if defined(ENABLE_GATT_CLIENT_PAIRING) && !defined(ENABLE_LE_PROACTIVE_AUTHENTICATION)
1338             if (gatt_client_required_security_level == LEVEL_0) {
1339                 // re-encryption failed for reactive authentication with pairing and we have a pending client request
1340                 // => try to resolve it by deleting bonding information if we started pairing before
1341                 // delete bonding information
1342                 int le_device_db_index = sm_le_device_index(gatt_client->con_handle);
1343                 btstack_assert(le_device_db_index >= 0);
1344                 log_info("reactive auth with pairing: delete bonding and start pairing");
1345 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1346                 hci_remove_le_device_db_entry_from_resolving_list((uint16_t) le_device_db_index);
1347 #endif
1348                 le_device_db_remove(le_device_db_index);
1349                 // trigger pairing again
1350                 sm_request_pairing(gatt_client->con_handle);
1351                 break;
1352             }
1353 #endif
1354             // report bonding information missing
1355             gatt_client_handle_transaction_complete(gatt_client);
1356             emit_gatt_complete_event(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1357             break;
1358         default:
1359             // report bonding information missing
1360             gatt_client_handle_transaction_complete(gatt_client);
1361             emit_gatt_complete_event(gatt_client, gatt_client->pending_error_code);
1362             break;
1363     }
1364 }
1365 
1366 static void gatt_client_handle_disconnection_complete(const uint8_t * packet){
1367     log_info("GATT Client: HCI_EVENT_DISCONNECTION_COMPLETE");
1368     hci_con_handle_t con_handle = little_endian_read_16(packet,3);
1369     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1370     if (gatt_client == NULL) return;
1371 
1372     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1373     gatt_client_timeout_stop(gatt_client);
1374     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1375     btstack_memory_gatt_client_free(gatt_client);
1376 }
1377 
1378 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1379     UNUSED(channel);    // ok: handling own l2cap events
1380     UNUSED(size);       // ok: there is no channel
1381 
1382     if (packet_type != HCI_EVENT_PACKET) return;
1383 
1384     hci_con_handle_t con_handle;
1385     gatt_client_t * gatt_client;
1386     switch (hci_event_packet_get_type(packet)) {
1387         case HCI_EVENT_DISCONNECTION_COMPLETE:
1388             gatt_client_handle_disconnection_complete(packet);
1389             break;
1390 
1391         // Pairing complete (with/without bonding=storing of pairing information)
1392         case SM_EVENT_PAIRING_COMPLETE:
1393             con_handle = sm_event_pairing_complete_get_handle(packet);
1394             gatt_client = gatt_client_get_context_for_handle(con_handle);
1395             if (gatt_client == NULL) break;
1396 
1397             // update security level
1398             gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1399 
1400             if (gatt_client->wait_for_authentication_complete){
1401                 gatt_client->wait_for_authentication_complete = 0;
1402                 if (sm_event_pairing_complete_get_status(packet)){
1403                     log_info("pairing failed, report previous error 0x%x", gatt_client->pending_error_code);
1404                     gatt_client_report_error_if_pending(gatt_client, gatt_client->pending_error_code);
1405                 } else {
1406                     log_info("pairing success, retry operation");
1407                 }
1408             }
1409             break;
1410 
1411 #ifdef ENABLE_LE_SIGNED_WRITE
1412         // Identity Resolving completed (no code, gatt_client_run will continue)
1413         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
1414         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
1415             break;
1416 #endif
1417 
1418         // re-encryption started
1419         case SM_EVENT_REENCRYPTION_STARTED:
1420             con_handle = sm_event_reencryption_complete_get_handle(packet);
1421             gatt_client = gatt_client_get_context_for_handle(con_handle);
1422             if (gatt_client == NULL) break;
1423 
1424             gatt_client->reencryption_active = true;
1425             gatt_client->reencryption_result = ERROR_CODE_SUCCESS;
1426             break;
1427 
1428         // re-encryption complete
1429         case SM_EVENT_REENCRYPTION_COMPLETE:
1430             gatt_client_handle_reencryption_complete(packet);
1431             break;
1432         default:
1433             break;
1434     }
1435 
1436     gatt_client_run();
1437 }
1438 
1439 static void gatt_client_handle_att_read_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1440     switch (gatt_client->gatt_client_state) {
1441         case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT:
1442             if (size >= 17) {
1443                 uint8_t uuid128[16];
1444                 reverse_128(&packet[1], uuid128);
1445                 report_gatt_included_service_uuid128(gatt_client, gatt_client->start_group_handle, uuid128);
1446             }
1447             trigger_next_included_service_query(gatt_client, gatt_client->start_group_handle);
1448             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1449             break;
1450 
1451         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1452             gatt_client_handle_transaction_complete(gatt_client);
1453             report_gatt_characteristic_value(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u);
1454             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1455             break;
1456 
1457         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1458             gatt_client_handle_transaction_complete(gatt_client);
1459             report_gatt_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1460                                                   size - 1u, 0u);
1461             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1462             break;
1463 
1464             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic
1465         case P_W4_READ_BLOB_RESULT:
1466             report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1467                                                        size - 1u, gatt_client->attribute_offset);
1468             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, size - 1u);
1469             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1470             break;
1471 
1472             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic Descriptor
1473         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1474             report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1475                                                        size - 1u, gatt_client->attribute_offset);
1476             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
1477                                     size - 1u);
1478             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1479             break;
1480 
1481         default:
1482             break;
1483     }
1484 }
1485 
1486 static void gatt_client_handle_att_read_by_type_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1487     switch (gatt_client->gatt_client_state) {
1488         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1489             report_gatt_characteristics(gatt_client, packet, size);
1490             trigger_next_characteristic_query(gatt_client,
1491                                               get_last_result_handle_from_characteristics_list(packet, size));
1492             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1493             break;
1494         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1495             report_gatt_characteristics(gatt_client, packet, size);
1496             trigger_next_characteristic_query(gatt_client,
1497                                               get_last_result_handle_from_characteristics_list(packet, size));
1498             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1499             break;
1500         case P_W4_INCLUDED_SERVICE_QUERY_RESULT: {
1501             if (size < 2u) break;
1502             uint16_t uuid16 = 0;
1503             uint16_t pair_size = packet[1];
1504 
1505             if (pair_size == 6u) {
1506                 if (size < 8u) break;
1507                 // UUIDs not available, query first included service
1508                 gatt_client->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1509                 gatt_client->query_start_handle = little_endian_read_16(packet, 4);
1510                 gatt_client->query_end_handle = little_endian_read_16(packet, 6);
1511                 gatt_client->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1512                 break;
1513             }
1514 
1515             if (pair_size != 8u) break;
1516 
1517             // UUIDs included, report all of them
1518             uint16_t offset;
1519             for (offset = 2u; (offset + 8u) <= size; offset += pair_size) {
1520                 uint16_t include_handle = little_endian_read_16(packet, offset);
1521                 gatt_client->query_start_handle = little_endian_read_16(packet, offset + 2u);
1522                 gatt_client->query_end_handle = little_endian_read_16(packet, offset + 4u);
1523                 uuid16 = little_endian_read_16(packet, offset + 6u);
1524                 report_gatt_included_service_uuid16(gatt_client, include_handle, uuid16);
1525             }
1526 
1527             trigger_next_included_service_query(gatt_client,
1528                                                 get_last_result_handle_from_included_services_list(packet,
1529                                                                                                    size));
1530             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1531             break;
1532         }
1533 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1534         case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1535             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1536             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1537             break;
1538 #endif
1539         case P_W4_READ_BY_TYPE_RESPONSE: {
1540             uint16_t pair_size = packet[1];
1541             // set last result handle to last valid handle, only used if pair_size invalid
1542             uint16_t last_result_handle = 0xffff;
1543             if (pair_size > 2) {
1544                 uint16_t offset;
1545                 for (offset = 2; offset < size; offset += pair_size) {
1546                     uint16_t value_handle = little_endian_read_16(packet, offset);
1547                     report_gatt_characteristic_value(gatt_client, value_handle, &packet[offset + 2u],
1548                                                      pair_size - 2u);
1549                     last_result_handle = value_handle;
1550                 }
1551             }
1552             trigger_next_read_by_type_query(gatt_client, last_result_handle);
1553             break;
1554         }
1555         default:
1556             break;
1557     }
1558 }
1559 
1560 static void gatt_client_handle_att_write_response(gatt_client_t *gatt_client) {
1561     switch (gatt_client->gatt_client_state) {
1562         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1563             gatt_client_handle_transaction_complete(gatt_client);
1564             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1565             break;
1566         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1567             gatt_client_handle_transaction_complete(gatt_client);
1568             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1569             break;
1570         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1571             gatt_client_handle_transaction_complete(gatt_client);
1572             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1573             break;
1574         default:
1575             break;
1576     }
1577 }
1578 
1579 static void gatt_client_handle_att_response(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size) {
1580     uint8_t error_code;
1581     switch (packet[0]) {
1582         case ATT_EXCHANGE_MTU_RESPONSE: {
1583             if (size < 3u) break;
1584             bool update_att_mtu = true;
1585             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1586             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1587 #ifdef ENABLE_GATT_OVER_CLASSIC
1588             if (gatt_client->l2cap_psm != 0){
1589                 local_rx_mtu = gatt_client->mtu;
1590             } else {
1591                 update_att_mtu = false;
1592             }
1593 #endif
1594             uint16_t mtu = (remote_rx_mtu < local_rx_mtu) ? remote_rx_mtu : local_rx_mtu;
1595 
1596             // set gatt client mtu
1597             gatt_client->mtu = mtu;
1598             gatt_client->mtu_state = MTU_EXCHANGED;
1599 
1600             if (update_att_mtu){
1601                 // set per connection mtu state - for fixed channel
1602                 hci_connection_t *hci_connection = hci_connection_for_handle(gatt_client->con_handle);
1603                 hci_connection->att_connection.mtu = gatt_client->mtu;
1604                 hci_connection->att_connection.mtu_exchanged = true;
1605             }
1606             emit_gatt_mtu_exchanged_result_event(gatt_client, gatt_client->mtu);
1607             break;
1608         }
1609         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
1610             switch (gatt_client->gatt_client_state) {
1611                 case P_W4_SERVICE_QUERY_RESULT:
1612                     report_gatt_services(gatt_client, packet, size);
1613                     trigger_next_service_query(gatt_client, get_last_result_handle_from_service_list(packet, size));
1614                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1615                     break;
1616                 default:
1617                     break;
1618             }
1619             break;
1620         case ATT_HANDLE_VALUE_NOTIFICATION:
1621             if (size < 3u) return;
1622             report_gatt_notification(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
1623             return;
1624         case ATT_HANDLE_VALUE_INDICATION:
1625             if (size < 3u) break;
1626             report_gatt_indication(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
1627             gatt_client->send_confirmation = 1;
1628             break;
1629         case ATT_READ_BY_TYPE_RESPONSE:
1630             gatt_client_handle_att_read_by_type_response(gatt_client, packet, size);
1631             break;
1632         case ATT_READ_RESPONSE:
1633             gatt_client_handle_att_read_response(gatt_client, packet, size);
1634             break;
1635         case ATT_FIND_BY_TYPE_VALUE_RESPONSE: {
1636             uint8_t pair_size = 4;
1637             int i;
1638             uint16_t start_group_handle;
1639             uint16_t end_group_handle = 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
1640             for (i = 1u; (i + pair_size) <= size; i += pair_size) {
1641                 start_group_handle = little_endian_read_16(packet, i);
1642                 end_group_handle = little_endian_read_16(packet, i + 2);
1643                 emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle,
1644                                                      gatt_client->uuid128);
1645             }
1646             trigger_next_service_by_uuid_query(gatt_client, end_group_handle);
1647             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1648             break;
1649         }
1650         case ATT_FIND_INFORMATION_REPLY: {
1651             if (size < 2u) break;
1652 
1653             uint8_t pair_size = 4;
1654             if (packet[1u] == 2u) {
1655                 pair_size = 18;
1656             }
1657             uint16_t offset = 2;
1658 
1659             if (size < (pair_size + offset)) break;
1660             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
1661 
1662 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1663             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", gatt_client->gatt_client_state);
1664             if (gatt_client->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
1665                 // iterate over descriptors looking for CCC
1666                 if (pair_size == 4){
1667                     while ((offset + 4) <= size){
1668                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
1669                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
1670                             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
1671                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1672                             log_info("CCC found %x", gatt_client->client_characteristic_configuration_handle);
1673                             break;
1674                         }
1675                         offset += pair_size;
1676                     }
1677                 }
1678                 if (is_query_done(gatt_client, last_descriptor_handle)){
1679 
1680                 } else {
1681                     // next
1682                     gatt_client->start_group_handle = last_descriptor_handle + 1;
1683                     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1684                 }
1685                 break;
1686             }
1687 #endif
1688             report_gatt_all_characteristic_descriptors(gatt_client, &packet[2], size - 2u, pair_size);
1689             trigger_next_characteristic_descriptor_query(gatt_client, last_descriptor_handle);
1690             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1691             break;
1692         }
1693 
1694         case ATT_WRITE_RESPONSE:
1695             gatt_client_handle_att_write_response(gatt_client);
1696             break;
1697 
1698         case ATT_READ_BLOB_RESPONSE: {
1699             uint16_t received_blob_length = size - 1u;
1700             switch (gatt_client->gatt_client_state) {
1701                 case P_W4_READ_BLOB_RESULT:
1702                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1703                                                                received_blob_length, gatt_client->attribute_offset);
1704                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
1705                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1706                     break;
1707                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1708                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle,
1709                                                                &packet[1], received_blob_length,
1710                                                                gatt_client->attribute_offset);
1711                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
1712                                             received_blob_length);
1713                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1714                     break;
1715                 default:
1716                     break;
1717             }
1718             break;
1719         }
1720         case ATT_PREPARE_WRITE_RESPONSE:
1721             switch (gatt_client->gatt_client_state) {
1722                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1723                     gatt_client_handle_transaction_complete(gatt_client);
1724                     if (is_value_valid(gatt_client, packet, size)) {
1725                         emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1726                     } else {
1727                         emit_gatt_complete_event(gatt_client, ATT_ERROR_DATA_MISMATCH);
1728                     }
1729                     break;
1730 
1731                 case P_W4_PREPARE_WRITE_RESULT: {
1732                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1733                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1734                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1735                     break;
1736                 }
1737                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT: {
1738                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1739                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR,
1740                                                      P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1741                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1742                     break;
1743                 }
1744                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT: {
1745                     if (is_value_valid(gatt_client, packet, size)) {
1746                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1747                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE,
1748                                                          P_W2_EXECUTE_PREPARED_WRITE);
1749                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1750                         break;
1751                     }
1752                     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1753                     break;
1754                 }
1755                 default:
1756                     break;
1757             }
1758             break;
1759 
1760         case ATT_EXECUTE_WRITE_RESPONSE:
1761             switch (gatt_client->gatt_client_state) {
1762                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1763                     gatt_client_handle_transaction_complete(gatt_client);
1764                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1765                     break;
1766                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1767                     gatt_client_handle_transaction_complete(gatt_client);
1768                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1769                     break;
1770                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1771                     gatt_client_handle_transaction_complete(gatt_client);
1772                     emit_gatt_complete_event(gatt_client, ATT_ERROR_DATA_MISMATCH);
1773                     break;
1774                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1775                     gatt_client_handle_transaction_complete(gatt_client);
1776                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1777                     break;
1778                 default:
1779                     break;
1780 
1781             }
1782             break;
1783 
1784         case ATT_READ_MULTIPLE_RESPONSE:
1785             switch (gatt_client->gatt_client_state) {
1786                 case P_W4_READ_MULTIPLE_RESPONSE:
1787                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
1788                     gatt_client_handle_transaction_complete(gatt_client);
1789                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1790                     break;
1791                 default:
1792                     break;
1793             }
1794             break;
1795 
1796         case ATT_ERROR_RESPONSE:
1797             if (size < 5u) return;
1798             error_code = packet[4];
1799             switch (error_code) {
1800                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1801                     switch (gatt_client->gatt_client_state) {
1802                         case P_W4_SERVICE_QUERY_RESULT:
1803                         case P_W4_SERVICE_WITH_UUID_RESULT:
1804                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1805                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1806                             gatt_client_handle_transaction_complete(gatt_client);
1807                             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1808                             break;
1809                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1810                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1811                             characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1812                             gatt_client_handle_transaction_complete(gatt_client);
1813                             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1814                             break;
1815                         case P_W4_READ_BY_TYPE_RESPONSE:
1816                             gatt_client_handle_transaction_complete(gatt_client);
1817                             if (gatt_client->start_group_handle == gatt_client->query_start_handle) {
1818                                 emit_gatt_complete_event(gatt_client, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
1819                             } else {
1820                                 emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1821                             }
1822                             break;
1823                         default:
1824                             gatt_client_report_error_if_pending(gatt_client, error_code);
1825                             break;
1826                     }
1827                     break;
1828                 }
1829 
1830 #ifdef ENABLE_GATT_CLIENT_PAIRING
1831 
1832                     case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
1833                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
1834                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
1835 
1836                         // security too low
1837                         if (gatt_client->security_counter > 0) {
1838                             gatt_client_report_error_if_pending(gatt_client, error_code);
1839                             break;
1840                         }
1841                         // start security
1842                         gatt_client->security_counter++;
1843 
1844                         // setup action
1845                         int retry = 1;
1846                         switch (gatt_client->gatt_client_state){
1847                             case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1848                                 gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
1849                                 break;
1850                             case P_W4_READ_BLOB_RESULT:
1851                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1852                                 break;
1853                             case P_W4_READ_BY_TYPE_RESPONSE:
1854                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1855                                 break;
1856                             case P_W4_READ_MULTIPLE_RESPONSE:
1857                                 gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1858                                 break;
1859                             case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1860                                 gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1861                                 break;
1862                             case P_W4_PREPARE_WRITE_RESULT:
1863                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
1864                                 break;
1865                             case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1866                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
1867                                 break;
1868                             case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
1869                                 gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1870                                 break;
1871                             case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1872                                 gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
1873                                 break;
1874                             case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1875                                 gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
1876                                 break;
1877                             case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1878                                 gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1879                                 break;
1880                             case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1881                                 gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1882                                 break;
1883                             case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1884                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1885                                 break;
1886                             case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1887                                 gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
1888                                 break;
1889                             case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1890                                 gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1891                                 break;
1892                             case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1893                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
1894                                 break;
1895                             case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1896                                 gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
1897                                 break;
1898 #ifdef ENABLE_LE_SIGNED_WRITE
1899                             case P_W4_SEND_SINGED_WRITE_DONE:
1900                                 gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1901                                 break;
1902 #endif
1903                             default:
1904                                 log_info("retry not supported for state %x", gatt_client->gatt_client_state);
1905                                 retry = 0;
1906                                 break;
1907                         }
1908 
1909                         if (!retry) {
1910                             gatt_client_report_error_if_pending(gatt_client, error_code);
1911                             break;
1912                         }
1913 
1914                         log_info("security error, start pairing");
1915 
1916                         // start pairing for higher security level
1917                         gatt_client->wait_for_authentication_complete = 1;
1918                         gatt_client->pending_error_code = error_code;
1919                         sm_request_pairing(gatt_client->con_handle);
1920                         break;
1921                     }
1922 #endif
1923 
1924                     // nothing we can do about that
1925                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
1926                 default:
1927                     gatt_client_report_error_if_pending(gatt_client, error_code);
1928                     break;
1929             }
1930             break;
1931 
1932         default:
1933             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
1934             break;
1935     }
1936 }
1937 
1938 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size) {
1939     gatt_client_t *gatt_client;
1940     if (size < 1u) return;
1941 
1942     if (packet_type == HCI_EVENT_PACKET) {
1943         switch (packet[0]) {
1944             case L2CAP_EVENT_CAN_SEND_NOW:
1945                 gatt_client_run();
1946                 break;
1947                 // att_server has negotiated the mtu for this connection, cache if context exists
1948             case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
1949                 if (size < 6u) break;
1950                 gatt_client = gatt_client_get_context_for_handle(handle);
1951                 if (gatt_client == NULL) break;
1952                 gatt_client->mtu = little_endian_read_16(packet, 4);
1953                 break;
1954             default:
1955                 break;
1956         }
1957         return;
1958     }
1959 
1960     if (packet_type != ATT_DATA_PACKET) return;
1961 
1962     // special cases: notifications & indications motivate creating context
1963     switch (packet[0]) {
1964         case ATT_HANDLE_VALUE_NOTIFICATION:
1965         case ATT_HANDLE_VALUE_INDICATION:
1966             gatt_client_provide_context_for_handle(handle, &gatt_client);
1967             break;
1968         default:
1969             gatt_client = gatt_client_get_context_for_handle(handle);
1970             break;
1971     }
1972 
1973     if (gatt_client != NULL) {
1974         gatt_client_handle_att_response(gatt_client, packet, size);
1975         gatt_client_run();
1976     }
1977 }
1978 
1979 #ifdef ENABLE_LE_SIGNED_WRITE
1980 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
1981     btstack_linked_list_iterator_t it;
1982     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
1983     while (btstack_linked_list_iterator_has_next(&it)){
1984         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
1985         if (gatt_client->gatt_client_state == P_W4_CMAC_RESULT){
1986             // store result
1987             (void)memcpy(gatt_client->cmac, hash, 8);
1988             // reverse_64(hash, gatt_client->cmac);
1989             gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1990             gatt_client_run();
1991             return;
1992         }
1993     }
1994 }
1995 
1996 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){
1997     gatt_client_t * gatt_client;
1998     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
1999     if (status != ERROR_CODE_SUCCESS){
2000         return status;
2001     }
2002     if (is_ready(gatt_client) == 0){
2003         return GATT_CLIENT_IN_WRONG_STATE;
2004     }
2005 
2006     gatt_client->callback = callback;
2007     gatt_client->attribute_handle = value_handle;
2008     gatt_client->attribute_length = message_len;
2009     gatt_client->attribute_value = message;
2010     gatt_client->gatt_client_state = P_W4_IDENTITY_RESOLVING;
2011     gatt_client_run();
2012     return ERROR_CODE_SUCCESS;
2013 }
2014 #endif
2015 
2016 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2017     gatt_client_t * gatt_client;
2018     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2019     if (status != ERROR_CODE_SUCCESS){
2020         return status;
2021     }
2022     if (is_ready(gatt_client) == 0){
2023         return GATT_CLIENT_IN_WRONG_STATE;
2024     }
2025 
2026     gatt_client->callback = callback;
2027     gatt_client->start_group_handle = 0x0001;
2028     gatt_client->end_group_handle   = 0xffff;
2029     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
2030     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2031     gatt_client_run();
2032     return ERROR_CODE_SUCCESS;
2033 }
2034 
2035 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2036     gatt_client_t * gatt_client;
2037     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2038     if (status != ERROR_CODE_SUCCESS){
2039         return status;
2040     }
2041     if (is_ready(gatt_client) == 0){
2042         return GATT_CLIENT_IN_WRONG_STATE;
2043     }
2044 
2045     gatt_client->callback = callback;
2046     gatt_client->start_group_handle = 0x0001;
2047     gatt_client->end_group_handle   = 0xffff;
2048     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
2049     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2050     gatt_client_run();
2051     return ERROR_CODE_SUCCESS;
2052 }
2053 
2054 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2055     gatt_client_t * gatt_client;
2056     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2057     if (status != ERROR_CODE_SUCCESS){
2058         return status;
2059     }
2060     if (is_ready(gatt_client) == 0){
2061         return GATT_CLIENT_IN_WRONG_STATE;
2062     }
2063 
2064     gatt_client->callback = callback;
2065     gatt_client->start_group_handle = 0x0001;
2066     gatt_client->end_group_handle   = 0xffff;
2067     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2068     gatt_client->uuid16 = uuid16;
2069     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2070     gatt_client_run();
2071     return ERROR_CODE_SUCCESS;
2072 }
2073 
2074 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2075     gatt_client_t * gatt_client;
2076     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2077     if (status != ERROR_CODE_SUCCESS){
2078         return status;
2079     }
2080     if (is_ready(gatt_client) == 0){
2081         return GATT_CLIENT_IN_WRONG_STATE;
2082     }
2083 
2084     gatt_client->callback = callback;
2085     gatt_client->start_group_handle = 0x0001;
2086     gatt_client->end_group_handle   = 0xffff;
2087     gatt_client->uuid16 = 0;
2088     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2089     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2090     gatt_client_run();
2091     return ERROR_CODE_SUCCESS;
2092 }
2093 
2094 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2095     gatt_client_t * gatt_client;
2096     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2097     if (status != ERROR_CODE_SUCCESS){
2098         return status;
2099     }
2100     if (is_ready(gatt_client) == 0){
2101         return GATT_CLIENT_IN_WRONG_STATE;
2102     }
2103 
2104     gatt_client->callback = callback;
2105     gatt_client->start_group_handle = service->start_group_handle;
2106     gatt_client->end_group_handle   = service->end_group_handle;
2107     gatt_client->filter_with_uuid = 0;
2108     gatt_client->characteristic_start_handle = 0;
2109     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2110     gatt_client_run();
2111     return ERROR_CODE_SUCCESS;
2112 }
2113 
2114 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){
2115     gatt_client_t * gatt_client;
2116     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2117     if (status != ERROR_CODE_SUCCESS){
2118         return status;
2119     }
2120     if (is_ready(gatt_client) == 0){
2121         return GATT_CLIENT_IN_WRONG_STATE;
2122     }
2123     gatt_client->callback = callback;
2124     gatt_client->start_group_handle = service->start_group_handle;
2125     gatt_client->end_group_handle   = service->end_group_handle;
2126     gatt_client->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2127 
2128     gatt_client_run();
2129     return ERROR_CODE_SUCCESS;
2130 }
2131 
2132 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){
2133     gatt_client_t * gatt_client;
2134     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2135     if (status != ERROR_CODE_SUCCESS){
2136         return status;
2137     }
2138     if (is_ready(gatt_client) == 0){
2139         return GATT_CLIENT_IN_WRONG_STATE;
2140     }
2141 
2142     gatt_client->callback = callback;
2143     gatt_client->start_group_handle = start_handle;
2144     gatt_client->end_group_handle   = end_handle;
2145     gatt_client->filter_with_uuid = 1;
2146     gatt_client->uuid16 = uuid16;
2147     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2148     gatt_client->characteristic_start_handle = 0;
2149     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2150     gatt_client_run();
2151     return ERROR_CODE_SUCCESS;
2152 }
2153 
2154 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){
2155     gatt_client_t * gatt_client;
2156     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2157     if (status != ERROR_CODE_SUCCESS){
2158         return status;
2159     }
2160     if (is_ready(gatt_client) == 0){
2161         return GATT_CLIENT_IN_WRONG_STATE;
2162     }
2163 
2164     gatt_client->callback = callback;
2165     gatt_client->start_group_handle = start_handle;
2166     gatt_client->end_group_handle   = end_handle;
2167     gatt_client->filter_with_uuid = 1;
2168     gatt_client->uuid16 = 0;
2169     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2170     gatt_client->characteristic_start_handle = 0;
2171     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2172     gatt_client_run();
2173     return ERROR_CODE_SUCCESS;
2174 }
2175 
2176 
2177 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){
2178     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2179 }
2180 
2181 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){
2182     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2183 }
2184 
2185 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2186     gatt_client_t * gatt_client;
2187     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2188     if (status != ERROR_CODE_SUCCESS){
2189         return status;
2190     }
2191     if (is_ready(gatt_client) == 0){
2192         return GATT_CLIENT_IN_WRONG_STATE;
2193     }
2194 
2195     if (characteristic->value_handle == characteristic->end_handle){
2196         emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
2197         return ERROR_CODE_SUCCESS;
2198     }
2199     gatt_client->callback = callback;
2200     gatt_client->start_group_handle = characteristic->value_handle + 1u;
2201     gatt_client->end_group_handle   = characteristic->end_handle;
2202     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2203     gatt_client_run();
2204     return ERROR_CODE_SUCCESS;
2205 }
2206 
2207 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){
2208     gatt_client_t * gatt_client;
2209     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2210     if (status != ERROR_CODE_SUCCESS){
2211         return status;
2212     }
2213     if (is_ready(gatt_client) == 0){
2214         return GATT_CLIENT_IN_WRONG_STATE;
2215     }
2216 
2217     gatt_client->callback = callback;
2218     gatt_client->attribute_handle = value_handle;
2219     gatt_client->attribute_offset = 0;
2220     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2221     gatt_client_run();
2222     return ERROR_CODE_SUCCESS;
2223 }
2224 
2225 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){
2226     gatt_client_t * gatt_client;
2227     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2228     if (status != ERROR_CODE_SUCCESS){
2229         return status;
2230     }
2231     if (is_ready(gatt_client) == 0){
2232         return GATT_CLIENT_IN_WRONG_STATE;
2233     }
2234 
2235     gatt_client->callback = callback;
2236     gatt_client->start_group_handle = start_handle;
2237     gatt_client->end_group_handle = end_handle;
2238     gatt_client->query_start_handle = start_handle;
2239     gatt_client->query_end_handle = end_handle;
2240     gatt_client->uuid16 = uuid16;
2241     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2242     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2243     gatt_client_run();
2244     return ERROR_CODE_SUCCESS;
2245 }
2246 
2247 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){
2248     gatt_client_t * gatt_client;
2249     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2250     if (status != ERROR_CODE_SUCCESS){
2251         return status;
2252     }
2253     if (is_ready(gatt_client) == 0){
2254         return GATT_CLIENT_IN_WRONG_STATE;
2255     }
2256 
2257     gatt_client->callback = callback;
2258     gatt_client->start_group_handle = start_handle;
2259     gatt_client->end_group_handle = end_handle;
2260     gatt_client->query_start_handle = start_handle;
2261     gatt_client->query_end_handle = end_handle;
2262     gatt_client->uuid16 = 0;
2263     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2264     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2265     gatt_client_run();
2266     return ERROR_CODE_SUCCESS;
2267 }
2268 
2269 
2270 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2271     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2272 }
2273 
2274 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){
2275     gatt_client_t * gatt_client;
2276     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2277     if (status != ERROR_CODE_SUCCESS){
2278         return status;
2279     }
2280     if (is_ready(gatt_client) == 0){
2281         return GATT_CLIENT_IN_WRONG_STATE;
2282     }
2283 
2284     gatt_client->callback = callback;
2285     gatt_client->attribute_handle = value_handle;
2286     gatt_client->attribute_offset = offset;
2287     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
2288     gatt_client_run();
2289     return ERROR_CODE_SUCCESS;
2290 }
2291 
2292 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){
2293     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2294 }
2295 
2296 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){
2297     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2298 }
2299 
2300 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){
2301     gatt_client_t * gatt_client;
2302     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2303     if (status != ERROR_CODE_SUCCESS){
2304         return status;
2305     }
2306     if (is_ready(gatt_client) == 0){
2307         return GATT_CLIENT_IN_WRONG_STATE;
2308     }
2309 
2310     gatt_client->callback = callback;
2311     gatt_client->read_multiple_handle_count = num_value_handles;
2312     gatt_client->read_multiple_handles = value_handles;
2313     gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2314     gatt_client_run();
2315     return ERROR_CODE_SUCCESS;
2316 }
2317 
2318 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){
2319     gatt_client_t * gatt_client;
2320     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2321     if (status != ERROR_CODE_SUCCESS){
2322         return status;
2323     }
2324 
2325     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2326     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2327 
2328     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2329 }
2330 
2331 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){
2332     gatt_client_t * gatt_client;
2333     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2334     if (status != ERROR_CODE_SUCCESS){
2335         return status;
2336     }
2337     if (is_ready(gatt_client) == 0){
2338         return GATT_CLIENT_IN_WRONG_STATE;
2339     }
2340 
2341     gatt_client->callback = callback;
2342     gatt_client->attribute_handle = value_handle;
2343     gatt_client->attribute_length = value_length;
2344     gatt_client->attribute_value = value;
2345     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2346     gatt_client_run();
2347     return ERROR_CODE_SUCCESS;
2348 }
2349 
2350 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){
2351     gatt_client_t * gatt_client;
2352     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2353     if (status != ERROR_CODE_SUCCESS){
2354         return status;
2355     }
2356     if (is_ready(gatt_client) == 0){
2357         return GATT_CLIENT_IN_WRONG_STATE;
2358     }
2359 
2360     gatt_client->callback = callback;
2361     gatt_client->attribute_handle = value_handle;
2362     gatt_client->attribute_length = value_length;
2363     gatt_client->attribute_offset = offset;
2364     gatt_client->attribute_value = value;
2365     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
2366     gatt_client_run();
2367     return ERROR_CODE_SUCCESS;
2368 }
2369 
2370 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){
2371     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2372 }
2373 
2374 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){
2375     gatt_client_t * gatt_client;
2376     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2377     if (status != ERROR_CODE_SUCCESS){
2378         return status;
2379     }
2380     if (is_ready(gatt_client) == 0){
2381         return GATT_CLIENT_IN_WRONG_STATE;
2382     }
2383 
2384     gatt_client->callback = callback;
2385     gatt_client->attribute_handle = value_handle;
2386     gatt_client->attribute_length = value_length;
2387     gatt_client->attribute_offset = 0;
2388     gatt_client->attribute_value = value;
2389     gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
2390     gatt_client_run();
2391     return ERROR_CODE_SUCCESS;
2392 }
2393 
2394 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){
2395     gatt_client_t * gatt_client;
2396     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2397     if (status != ERROR_CODE_SUCCESS){
2398         return status;
2399     }
2400     if (is_ready(gatt_client) == 0){
2401         return GATT_CLIENT_IN_WRONG_STATE;
2402     }
2403 
2404     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2405         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2406         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2407         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2408     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2409                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2410         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2411         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2412     }
2413 
2414     gatt_client->callback = callback;
2415     gatt_client->start_group_handle = characteristic->value_handle;
2416     gatt_client->end_group_handle = characteristic->end_handle;
2417     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2418 
2419 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2420     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2421 #else
2422     gatt_client->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2423 #endif
2424     gatt_client_run();
2425     return ERROR_CODE_SUCCESS;
2426 }
2427 
2428 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){
2429     gatt_client_t * gatt_client;
2430     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2431     if (status != ERROR_CODE_SUCCESS){
2432         return status;
2433     }
2434     if (is_ready(gatt_client) == 0){
2435         return GATT_CLIENT_IN_WRONG_STATE;
2436     }
2437 
2438     gatt_client->callback = callback;
2439     gatt_client->attribute_handle = descriptor_handle;
2440 
2441     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2442     gatt_client_run();
2443     return ERROR_CODE_SUCCESS;
2444 }
2445 
2446 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2447     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2448 }
2449 
2450 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){
2451     gatt_client_t * gatt_client;
2452     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2453     if (status != ERROR_CODE_SUCCESS){
2454         return status;
2455     }
2456     if (is_ready(gatt_client) == 0){
2457         return GATT_CLIENT_IN_WRONG_STATE;
2458     }
2459 
2460     gatt_client->callback = callback;
2461     gatt_client->attribute_handle = descriptor_handle;
2462     gatt_client->attribute_offset = offset;
2463     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2464     gatt_client_run();
2465     return ERROR_CODE_SUCCESS;
2466 }
2467 
2468 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){
2469     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2470 }
2471 
2472 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){
2473     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2474 }
2475 
2476 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){
2477     gatt_client_t * gatt_client;
2478     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2479     if (status != ERROR_CODE_SUCCESS){
2480         return status;
2481     }
2482     if (is_ready(gatt_client) == 0){
2483         return GATT_CLIENT_IN_WRONG_STATE;
2484     }
2485 
2486     gatt_client->callback = callback;
2487     gatt_client->attribute_handle = descriptor_handle;
2488     gatt_client->attribute_length = value_length;
2489     gatt_client->attribute_offset = 0;
2490     gatt_client->attribute_value = value;
2491     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2492     gatt_client_run();
2493     return ERROR_CODE_SUCCESS;
2494 }
2495 
2496 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){
2497     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2498 }
2499 
2500 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){
2501     gatt_client_t * gatt_client;
2502     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2503     if (status != ERROR_CODE_SUCCESS){
2504         return status;
2505     }
2506     if (is_ready(gatt_client) == 0){
2507         return GATT_CLIENT_IN_WRONG_STATE;
2508     }
2509 
2510     gatt_client->callback = callback;
2511     gatt_client->attribute_handle = descriptor_handle;
2512     gatt_client->attribute_length = value_length;
2513     gatt_client->attribute_offset = offset;
2514     gatt_client->attribute_value = value;
2515     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2516     gatt_client_run();
2517     return ERROR_CODE_SUCCESS;
2518 }
2519 
2520 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){
2521     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2522 }
2523 
2524 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){
2525     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2526 }
2527 
2528 /**
2529  * @brief -> gatt complete event
2530  */
2531 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){
2532     gatt_client_t * gatt_client;
2533     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2534     if (status != ERROR_CODE_SUCCESS){
2535         return status;
2536     }
2537     if (is_ready(gatt_client) == 0){
2538         return GATT_CLIENT_IN_WRONG_STATE;
2539     }
2540 
2541     gatt_client->callback = callback;
2542     gatt_client->attribute_handle = attribute_handle;
2543     gatt_client->attribute_length = value_length;
2544     gatt_client->attribute_offset = offset;
2545     gatt_client->attribute_value = value;
2546     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
2547     gatt_client_run();
2548     return ERROR_CODE_SUCCESS;
2549 }
2550 
2551 /**
2552  * @brief -> gatt complete event
2553  */
2554 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2555     gatt_client_t * gatt_client;
2556     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2557     if (status != ERROR_CODE_SUCCESS){
2558         return status;
2559     }
2560     if (is_ready(gatt_client) == 0){
2561         return GATT_CLIENT_IN_WRONG_STATE;
2562     }
2563 
2564     gatt_client->callback = callback;
2565     gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
2566     gatt_client_run();
2567     return ERROR_CODE_SUCCESS;
2568 }
2569 
2570 /**
2571  * @brief -> gatt complete event
2572  */
2573 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2574     gatt_client_t * gatt_client;
2575     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2576     if (status != ERROR_CODE_SUCCESS){
2577         return status;
2578     }
2579     if (is_ready(gatt_client) == 0){
2580         return GATT_CLIENT_IN_WRONG_STATE;
2581     }
2582 
2583     gatt_client->callback = callback;
2584     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
2585     gatt_client_run();
2586     return ERROR_CODE_SUCCESS;
2587 }
2588 
2589 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
2590     service->start_group_handle = little_endian_read_16(packet, offset);
2591     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2592     reverse_128(&packet[offset + 4], service->uuid128);
2593     if (uuid_has_bluetooth_prefix(service->uuid128)){
2594         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2595     } else {
2596         service->uuid16 = 0;
2597     }
2598 }
2599 
2600 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2601     characteristic->start_handle = little_endian_read_16(packet, offset);
2602     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2603     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2604     characteristic->properties = little_endian_read_16(packet, offset + 6);
2605     reverse_128(&packet[offset+8], characteristic->uuid128);
2606     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2607         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2608     } else {
2609         characteristic->uuid16 = 0;
2610     }
2611 }
2612 
2613 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2614     descriptor->handle = little_endian_read_16(packet, offset);
2615     reverse_128(&packet[offset+2], descriptor->uuid128);
2616     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2617         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2618     } else {
2619         descriptor->uuid16 = 0;
2620     }
2621 }
2622 
2623 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2624     gatt_client_t * gatt_client;
2625     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2626     if (status != ERROR_CODE_SUCCESS){
2627         return;
2628     }
2629     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2630         gatt_client->callback = callback;
2631         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
2632         gatt_client_run();
2633     }
2634 }
2635 
2636 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2637     gatt_client_t * gatt_client;
2638     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2639     if (status != ERROR_CODE_SUCCESS){
2640         return status;
2641     }
2642     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
2643     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2644     if (added){
2645         return ERROR_CODE_SUCCESS;
2646     } else {
2647         return ERROR_CODE_COMMAND_DISALLOWED;
2648     }
2649 }
2650 
2651 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2652     gatt_client_t * gatt_client;
2653     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2654     if (status != ERROR_CODE_SUCCESS){
2655         return status;
2656     }
2657     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
2658     gatt_client_notify_can_send_query(gatt_client);
2659     if (added){
2660         return ERROR_CODE_SUCCESS;
2661     } else {
2662         return ERROR_CODE_COMMAND_DISALLOWED;
2663     }
2664 }
2665 
2666 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2667     gatt_client_t * gatt_client;
2668     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2669     if (status != ERROR_CODE_SUCCESS){
2670         return status;
2671     }
2672     if (gatt_client->write_without_response_callback != NULL){
2673         return GATT_CLIENT_IN_WRONG_STATE;
2674     }
2675     gatt_client->write_without_response_callback = callback;
2676     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2677     return ERROR_CODE_SUCCESS;
2678 }
2679 
2680 #ifdef ENABLE_GATT_OVER_CLASSIC
2681 
2682 #include "hci_event.h"
2683 
2684 // single active SDP query
2685 static gatt_client_t * gatt_client_classic_active_sdp_query;
2686 
2687 // macos protocol descriptor list requires 16 bytes
2688 static uint8_t gatt_client_classic_sdp_buffer[32];
2689 
2690 static const hci_event_t gatt_client_connected = {
2691         GATT_EVENT_CONNECTED, 0, "1BH"
2692 };
2693 
2694 static const hci_event_t gatt_client_disconnected = {
2695         GATT_EVENT_DISCONNECTED, 0, "H"
2696 };
2697 
2698 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
2699     btstack_linked_item_t *it;
2700     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2701         gatt_client_t * gatt_client = (gatt_client_t *) it;
2702         if (memcmp(gatt_client->addr, addr, 6) == 0){
2703             return gatt_client;
2704         }
2705     }
2706     return NULL;
2707 }
2708 
2709 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
2710     btstack_linked_item_t *it;
2711     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2712         gatt_client_t * gatt_client = (gatt_client_t *) it;
2713         if (gatt_client->l2cap_cid == l2cap_cid){
2714             return gatt_client;
2715         }
2716     }
2717     return NULL;
2718 }
2719 
2720 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
2721     bd_addr_t addr;
2722     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
2723     memcpy(addr, gatt_client->addr, 6);
2724     hci_con_handle_t con_handle = gatt_client->con_handle;
2725     btstack_packet_handler_t callback = gatt_client->callback;
2726     if (status != ERROR_CODE_SUCCESS){
2727         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2728         btstack_memory_gatt_client_free(gatt_client);
2729     }
2730     uint8_t buffer[20];
2731     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr,
2732                                                                 con_handle);
2733     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2734 }
2735 
2736 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
2737 
2738     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
2739     gatt_client_timeout_stop(gatt_client);
2740 
2741     hci_con_handle_t con_handle = gatt_client->con_handle;
2742     btstack_packet_handler_t callback = gatt_client->callback;
2743     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2744     btstack_memory_gatt_client_free(gatt_client);
2745 
2746     uint8_t buffer[20];
2747     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
2748     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2749 }
2750 
2751 static void gatt_client_l2cap_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2752     gatt_client_t * gatt_client = NULL;
2753     uint8_t status;
2754     switch (packet_type){
2755         case HCI_EVENT_PACKET:
2756             switch (hci_event_packet_get_type(packet)) {
2757                 case L2CAP_EVENT_CHANNEL_OPENED:
2758                     status = l2cap_event_channel_opened_get_status(packet);
2759                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_opened_get_local_cid(packet));
2760                     btstack_assert(gatt_client != NULL);
2761                     // if status != 0, gatt_client will be discarded
2762                     gatt_client->gatt_client_state = P_READY;
2763                     gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2764                     gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2765                     gatt_client_classic_handle_connected(gatt_client, status);
2766                     break;
2767                 case L2CAP_EVENT_CHANNEL_CLOSED:
2768                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2769                     gatt_client_classic_handle_disconnected(gatt_client);
2770                     break;
2771                 default:
2772                     break;
2773             }
2774             break;
2775         case L2CAP_DATA_PACKET:
2776             gatt_client = gatt_client_get_context_for_l2cap_cid(channel);
2777             btstack_assert(gatt_client != NULL);
2778             gatt_client_handle_att_response(gatt_client, packet, size);
2779             gatt_client_run();
2780             break;
2781         default:
2782             break;
2783     }
2784 }
2785 
2786 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
2787     des_iterator_t des_list_it;
2788     des_iterator_t prot_it;
2789 
2790     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
2791         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
2792         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
2793             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
2794                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
2795                     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)) {
2796                         uint8_t       *des_element;
2797                         uint8_t       *element;
2798                         uint32_t       uuid;
2799 
2800                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
2801 
2802                         des_element = des_iterator_get_element(&des_list_it);
2803                         des_iterator_init(&prot_it, des_element);
2804                         element = des_iterator_get_element(&prot_it);
2805 
2806                         if (de_get_element_type(element) != DE_UUID) continue;
2807 
2808                         uuid = de_get_uuid32(element);
2809                         des_iterator_next(&prot_it);
2810                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
2811                         switch (uuid){
2812                             case BLUETOOTH_PROTOCOL_L2CAP:
2813                                 if (!des_iterator_has_more(&prot_it)) continue;
2814                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
2815                                 break;
2816                             default:
2817                                 break;
2818                         }
2819                     }
2820                     break;
2821 
2822                 default:
2823                     break;
2824             }
2825         }
2826     }
2827 }
2828 
2829 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2830     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
2831     btstack_assert(gatt_client != NULL);
2832     uint8_t status;
2833 
2834     // TODO: handle sdp events, get l2cap psm
2835     switch (hci_event_packet_get_type(packet)){
2836         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
2837             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
2838             // TODO:
2839             return;
2840         case SDP_EVENT_QUERY_COMPLETE:
2841             status = sdp_event_query_complete_get_status(packet);
2842             gatt_client_classic_active_sdp_query = NULL;
2843             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
2844             if (status != ERROR_CODE_SUCCESS) break;
2845             if (gatt_client->l2cap_psm == 0) {
2846                 status = SDP_SERVICE_NOT_FOUND;
2847                 break;
2848             }
2849             break;
2850         default:
2851             btstack_assert(false);
2852             return;
2853     }
2854 
2855     // done
2856     if (status == ERROR_CODE_SUCCESS){
2857         gatt_client->gatt_client_state = P_W4_L2CAP_CONNECTION;
2858         status = l2cap_create_channel(gatt_client_l2cap_handler, gatt_client->addr, gatt_client->l2cap_psm, 0xffff,
2859                              &gatt_client->l2cap_cid);
2860     }
2861     if (status != ERROR_CODE_SUCCESS) {
2862         gatt_client_classic_handle_connected(gatt_client, status);
2863     }
2864 }
2865 
2866 static void gatt_client_classic_sdp_start(void * context){
2867     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
2868     gatt_client_classic_active_sdp_query->gatt_client_state = P_W4_SDP_QUERY;
2869     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
2870 }
2871 
2872 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
2873     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
2874     if (gatt_client != NULL){
2875         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
2876     }
2877     gatt_client = btstack_memory_gatt_client_get();
2878     if (gatt_client == NULL){
2879         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
2880     }
2881     // init state
2882     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
2883     memcpy(gatt_client->addr, addr, 6);
2884     gatt_client->mtu = ATT_DEFAULT_MTU;
2885     gatt_client->security_level = LEVEL_0;
2886     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
2887     gatt_client->gatt_client_state = P_W2_SDP_QUERY;
2888     gatt_client->sdp_query_request.callback = &gatt_client_classic_sdp_start;
2889     gatt_client->sdp_query_request.context = gatt_client;
2890     gatt_client->callback = callback;
2891     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
2892     sdp_client_register_query_callback(&gatt_client->sdp_query_request);
2893     return ERROR_CODE_SUCCESS;
2894 }
2895 
2896 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2897     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
2898     if (gatt_client == NULL){
2899         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2900     }
2901     gatt_client->callback = callback;
2902     return l2cap_disconnect(gatt_client->l2cap_cid);
2903 }
2904 #endif
2905 
2906 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2907 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2908     gatt_client_att_packet_handler(packet_type, handle, packet, size);
2909 }
2910 
2911 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
2912     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
2913     return status;
2914 }
2915 #endif
2916