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