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