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