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