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