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