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