xref: /btstack/src/ble/gatt_client.c (revision 7e4c9b5dd1d710d44c3e167b1542e913a43014c9)
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     // write without response callback
1157     btstack_context_callback_registration_t * callback =
1158             (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->write_without_response_requests);
1159     if (callback != NULL){
1160         (*callback->callback)(callback->context);
1161         return true;
1162     }
1163 
1164     // requested can send now old
1165     if (gatt_client->write_without_response_callback){
1166         btstack_packet_handler_t packet_handler = gatt_client->write_without_response_callback;
1167         gatt_client->write_without_response_callback = NULL;
1168         uint8_t event[4];
1169         event[0] = GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE;
1170         event[1] = sizeof(event) - 2u;
1171         little_endian_store_16(event, 2, gatt_client->con_handle);
1172         packet_handler(HCI_EVENT_PACKET, gatt_client->con_handle, event, sizeof(event));
1173         return true; // to trigger requeueing (even if higher layer didn't sent)
1174     }
1175 
1176     return false;
1177 }
1178 
1179 static void gatt_client_run(void){
1180     btstack_linked_item_t *it;
1181     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
1182         gatt_client_t * gatt_client = (gatt_client_t *) it;
1183         if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) {
1184             att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1185             return;
1186         }
1187         bool packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1188         if (packet_sent){
1189             // request new permission
1190             att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1191             // requeue client for fairness and exit
1192             // note: iterator has become invalid
1193             btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1194             btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1195             return;
1196         }
1197     }
1198 }
1199 
1200 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code) {
1201     if (is_ready(gatt_client) == 1) return;
1202     gatt_client_handle_transaction_complete(gatt_client);
1203     emit_gatt_complete_event(gatt_client, att_error_code);
1204 }
1205 
1206 static void gatt_client_handle_reencryption_complete(const uint8_t * packet){
1207     hci_con_handle_t con_handle = sm_event_reencryption_complete_get_handle(packet);
1208     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1209     if (gatt_client == NULL) return;
1210 
1211     // update security level
1212     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1213 
1214     gatt_client->reencryption_result = sm_event_reencryption_complete_get_status(packet);
1215     gatt_client->reencryption_active = false;
1216     gatt_client->wait_for_authentication_complete = 0;
1217 
1218     if (gatt_client->gatt_client_state == P_READY) return;
1219 
1220     switch (sm_event_reencryption_complete_get_status(packet)){
1221         case ERROR_CODE_SUCCESS:
1222             log_info("re-encryption success, retry operation");
1223             break;
1224         case ERROR_CODE_AUTHENTICATION_FAILURE:
1225         case ERROR_CODE_PIN_OR_KEY_MISSING:
1226 #if defined(ENABLE_GATT_CLIENT_PAIRING) && !defined(ENABLE_LE_PROACTIVE_AUTHENTICATION)
1227             if (gatt_client_required_security_level == LEVEL_0) {
1228                 // re-encryption failed for reactive authentication with pairing and we have a pending client request
1229                 // => try to resolve it by deleting bonding information if we started pairing before
1230                 // delete bonding information
1231                 int le_device_db_index = sm_le_device_index(gatt_client->con_handle);
1232                 btstack_assert(le_device_db_index >= 0);
1233                 log_info("reactive auth with pairing: delete bonding and start pairing");
1234 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1235                 hci_remove_le_device_db_entry_from_resolving_list((uint16_t) le_device_db_index);
1236 #endif
1237                 le_device_db_remove(le_device_db_index);
1238                 // trigger pairing again
1239                 sm_request_pairing(gatt_client->con_handle);
1240                 break;
1241             }
1242 #endif
1243             // report bonding information missing
1244             gatt_client_handle_transaction_complete(gatt_client);
1245             emit_gatt_complete_event(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1246             break;
1247         default:
1248             // report bonding information missing
1249             gatt_client_handle_transaction_complete(gatt_client);
1250             emit_gatt_complete_event(gatt_client, gatt_client->pending_error_code);
1251             break;
1252     }
1253 }
1254 
1255 static void gatt_client_handle_disconnection_complete(const uint8_t * packet){
1256     log_info("GATT Client: HCI_EVENT_DISCONNECTION_COMPLETE");
1257     hci_con_handle_t con_handle = little_endian_read_16(packet,3);
1258     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1259     if (gatt_client == NULL) return;
1260 
1261     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1262     gatt_client_timeout_stop(gatt_client);
1263     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1264     btstack_memory_gatt_client_free(gatt_client);
1265 }
1266 
1267 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1268     UNUSED(channel);    // ok: handling own l2cap events
1269     UNUSED(size);       // ok: there is no channel
1270 
1271     if (packet_type != HCI_EVENT_PACKET) return;
1272 
1273     hci_con_handle_t con_handle;
1274     gatt_client_t * gatt_client;
1275     switch (hci_event_packet_get_type(packet)) {
1276         case HCI_EVENT_DISCONNECTION_COMPLETE:
1277             gatt_client_handle_disconnection_complete(packet);
1278             break;
1279 
1280         // Pairing complete (with/without bonding=storing of pairing information)
1281         case SM_EVENT_PAIRING_COMPLETE:
1282             con_handle = sm_event_pairing_complete_get_handle(packet);
1283             gatt_client = gatt_client_get_context_for_handle(con_handle);
1284             if (gatt_client == NULL) break;
1285 
1286             // update security level
1287             gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1288 
1289             if (gatt_client->wait_for_authentication_complete){
1290                 gatt_client->wait_for_authentication_complete = 0;
1291                 if (sm_event_pairing_complete_get_status(packet)){
1292                     log_info("pairing failed, report previous error 0x%x", gatt_client->pending_error_code);
1293                     gatt_client_report_error_if_pending(gatt_client, gatt_client->pending_error_code);
1294                 } else {
1295                     log_info("pairing success, retry operation");
1296                 }
1297             }
1298             break;
1299 
1300 #ifdef ENABLE_LE_SIGNED_WRITE
1301         // Identity Resolving completed (no code, gatt_client_run will continue)
1302         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
1303         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
1304             break;
1305 #endif
1306 
1307         // re-encryption started
1308         case SM_EVENT_REENCRYPTION_STARTED:
1309             con_handle = sm_event_reencryption_complete_get_handle(packet);
1310             gatt_client = gatt_client_get_context_for_handle(con_handle);
1311             if (gatt_client == NULL) break;
1312 
1313             gatt_client->reencryption_active = true;
1314             gatt_client->reencryption_result = ERROR_CODE_SUCCESS;
1315             break;
1316 
1317         // re-encryption complete
1318         case SM_EVENT_REENCRYPTION_COMPLETE:
1319             gatt_client_handle_reencryption_complete(packet);
1320             break;
1321         default:
1322             break;
1323     }
1324 
1325     gatt_client_run();
1326 }
1327 
1328 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
1329     gatt_client_t * gatt_client;
1330     if (size < 1u) return;
1331 
1332     if (packet_type == HCI_EVENT_PACKET) {
1333         switch (packet[0]){
1334             case L2CAP_EVENT_CAN_SEND_NOW:
1335                 gatt_client_run();
1336                 break;
1337             // att_server has negotiated the mtu for this connection, cache if context exists
1338             case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
1339                 if (size < 6u) break;
1340                 gatt_client = gatt_client_get_context_for_handle(handle);
1341                 if (gatt_client == NULL) break;
1342                 gatt_client->mtu = little_endian_read_16(packet, 4);
1343                 break;
1344             default:
1345                 break;
1346         }
1347         return;
1348     }
1349 
1350     if (packet_type != ATT_DATA_PACKET) return;
1351 
1352     // special cases: notifications don't need a context while indications motivate creating one
1353     switch (packet[0]){
1354         case ATT_HANDLE_VALUE_NOTIFICATION:
1355             if (size < 3u) return;
1356             report_gatt_notification(handle, little_endian_read_16(packet,1u), &packet[3], size-3u);
1357             return;
1358         case ATT_HANDLE_VALUE_INDICATION:
1359             gatt_client_provide_context_for_handle(handle, &gatt_client);
1360             break;
1361         default:
1362             gatt_client = gatt_client_get_context_for_handle(handle);
1363             break;
1364     }
1365 
1366     if (gatt_client == NULL) return;
1367 
1368     uint8_t error_code;
1369     switch (packet[0]){
1370         case ATT_EXCHANGE_MTU_RESPONSE:
1371         {
1372             if (size < 3u) break;
1373             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1374             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1375             uint16_t mtu = (remote_rx_mtu < local_rx_mtu) ? remote_rx_mtu : local_rx_mtu;
1376 
1377             // set gatt client mtu
1378             gatt_client->mtu = mtu;
1379             gatt_client->mtu_state = MTU_EXCHANGED;
1380 
1381             // set per connection mtu state
1382             hci_connection_t * hci_connection = hci_connection_for_handle(handle);
1383             hci_connection->att_connection.mtu = gatt_client->mtu;
1384             hci_connection->att_connection.mtu_exchanged = true;
1385 
1386             emit_gatt_mtu_exchanged_result_event(gatt_client, gatt_client->mtu);
1387             break;
1388         }
1389         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
1390             switch(gatt_client->gatt_client_state){
1391                 case P_W4_SERVICE_QUERY_RESULT:
1392                     report_gatt_services(gatt_client, packet, size);
1393                     trigger_next_service_query(gatt_client, get_last_result_handle_from_service_list(packet, size));
1394                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1395                     break;
1396                 default:
1397                     break;
1398             }
1399             break;
1400         case ATT_HANDLE_VALUE_INDICATION:
1401             if (size < 3u) break;
1402             report_gatt_indication(handle, little_endian_read_16(packet,1u), &packet[3], size-3u);
1403             gatt_client->send_confirmation = 1;
1404             break;
1405 
1406         case ATT_READ_BY_TYPE_RESPONSE:
1407             switch (gatt_client->gatt_client_state){
1408                 case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1409                     report_gatt_characteristics(gatt_client, packet, size);
1410                     trigger_next_characteristic_query(gatt_client, get_last_result_handle_from_characteristics_list(packet, size));
1411                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1412                     break;
1413                 case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1414                     report_gatt_characteristics(gatt_client, packet, size);
1415                     trigger_next_characteristic_query(gatt_client, get_last_result_handle_from_characteristics_list(packet, size));
1416                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1417                     break;
1418                 case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1419                 {
1420                     if (size < 2u) break;
1421                     uint16_t uuid16 = 0;
1422                     uint16_t pair_size = packet[1];
1423 
1424                     if (pair_size == 6u){
1425                         if (size < 8u) break;
1426                         // UUIDs not available, query first included service
1427                         gatt_client->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1428                         gatt_client->query_start_handle = little_endian_read_16(packet, 4);
1429                         gatt_client->query_end_handle = little_endian_read_16(packet, 6);
1430                         gatt_client->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1431                         break;
1432                     }
1433 
1434                     if (pair_size != 8u) break;
1435 
1436                     // UUIDs included, report all of them
1437                     uint16_t offset;
1438                     for (offset = 2u; (offset + 8u) <= size; offset += pair_size){
1439                         uint16_t include_handle = little_endian_read_16(packet, offset);
1440                         gatt_client->query_start_handle = little_endian_read_16(packet, offset + 2u);
1441                         gatt_client->query_end_handle = little_endian_read_16(packet, offset + 4u);
1442                         uuid16 = little_endian_read_16(packet, offset+6u);
1443                         report_gatt_included_service_uuid16(gatt_client, include_handle, uuid16);
1444                     }
1445 
1446                     trigger_next_included_service_query(gatt_client, get_last_result_handle_from_included_services_list(packet, size));
1447                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1448                     break;
1449                 }
1450 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1451                 case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1452                     gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1453                     gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1454                     break;
1455 #endif
1456                 case P_W4_READ_BY_TYPE_RESPONSE: {
1457                     uint16_t pair_size = packet[1];
1458                     // set last result handle to last valid handle, only used if pair_size invalid
1459                     uint16_t last_result_handle = 0xffff;
1460                     if (pair_size > 2){
1461                         uint16_t offset;
1462                         for (offset = 2; offset < size ; offset += pair_size){
1463                             uint16_t value_handle = little_endian_read_16(packet, offset);
1464                             report_gatt_characteristic_value(gatt_client, value_handle, &packet[offset + 2u], pair_size - 2u);
1465                             last_result_handle = value_handle;
1466                         }
1467                     }
1468                     trigger_next_read_by_type_query(gatt_client, last_result_handle);
1469                     break;
1470                 }
1471                 default:
1472                     break;
1473             }
1474             break;
1475         case ATT_READ_RESPONSE:
1476             switch (gatt_client->gatt_client_state){
1477                 case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT:
1478                     if (size >= 17){
1479                         uint8_t uuid128[16];
1480                         reverse_128(&packet[1], uuid128);
1481                         report_gatt_included_service_uuid128(gatt_client, gatt_client->start_group_handle, uuid128);
1482                     }
1483                     trigger_next_included_service_query(gatt_client, gatt_client->start_group_handle);
1484                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1485                     break;
1486 
1487                 case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1488                     gatt_client_handle_transaction_complete(gatt_client);
1489                     report_gatt_characteristic_value(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u);
1490                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1491                     break;
1492 
1493                 case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1494                     gatt_client_handle_transaction_complete(gatt_client);
1495                     report_gatt_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u, 0u);
1496                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1497                     break;
1498 
1499                 // Use ATT_READ_REQUEST for first blob of Read Long Characteristic
1500                 case P_W4_READ_BLOB_RESULT:
1501                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u, gatt_client->attribute_offset);
1502                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, size - 1u);
1503                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1504                     break;
1505 
1506                 // Use ATT_READ_REQUEST for first blob of Read Long Characteristic Descriptor
1507                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1508                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1], size-1u, gatt_client->attribute_offset);
1509                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY, size-1u);
1510                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1511                     break;
1512 
1513                 default:
1514                     break;
1515             }
1516             break;
1517 
1518         case ATT_FIND_BY_TYPE_VALUE_RESPONSE:
1519         {
1520             uint8_t pair_size = 4;
1521             int i;
1522             uint16_t start_group_handle;
1523             uint16_t   end_group_handle= 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
1524             for (i = 1u; (i + pair_size) <= size; i += pair_size){
1525                 start_group_handle = little_endian_read_16(packet,i);
1526                 end_group_handle = little_endian_read_16(packet,i+2);
1527                 emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle, gatt_client->uuid128);
1528             }
1529             trigger_next_service_by_uuid_query(gatt_client, end_group_handle);
1530             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1531             break;
1532         }
1533         case ATT_FIND_INFORMATION_REPLY:
1534         {
1535             if (size < 2u) break;
1536 
1537             uint8_t pair_size = 4;
1538             if (packet[1u] == 2u){
1539                 pair_size = 18;
1540             }
1541             uint16_t offset = 2;
1542 
1543             if (size < (pair_size + offset)) break;
1544             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
1545 
1546 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1547             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", gatt_client->gatt_client_state);
1548             if (gatt_client->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
1549                 // iterate over descriptors looking for CCC
1550                 if (pair_size == 4){
1551                     while ((offset + 4) <= size){
1552                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
1553                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
1554                             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
1555                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1556                             log_info("CCC found %x", gatt_client->client_characteristic_configuration_handle);
1557                             break;
1558                         }
1559                         offset += pair_size;
1560                     }
1561                 }
1562                 if (is_query_done(gatt_client, last_descriptor_handle)){
1563 
1564                 } else {
1565                     // next
1566                     gatt_client->start_group_handle = last_descriptor_handle + 1;
1567                     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1568                 }
1569                 break;
1570             }
1571 #endif
1572             report_gatt_all_characteristic_descriptors(gatt_client, &packet[2], size - 2u, pair_size);
1573             trigger_next_characteristic_descriptor_query(gatt_client, last_descriptor_handle);
1574             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1575             break;
1576         }
1577 
1578         case ATT_WRITE_RESPONSE:
1579             switch (gatt_client->gatt_client_state){
1580                 case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1581                     gatt_client_handle_transaction_complete(gatt_client);
1582                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1583                     break;
1584                 case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1585                     gatt_client_handle_transaction_complete(gatt_client);
1586                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1587                     break;
1588                 case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1589                     gatt_client_handle_transaction_complete(gatt_client);
1590                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1591                     break;
1592                 default:
1593                     break;
1594             }
1595             break;
1596 
1597         case ATT_READ_BLOB_RESPONSE:{
1598             uint16_t received_blob_length = size-1u;
1599             switch(gatt_client->gatt_client_state){
1600                 case P_W4_READ_BLOB_RESULT:
1601                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1], received_blob_length, gatt_client->attribute_offset);
1602                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
1603                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1604                     break;
1605                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1606                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle,
1607                                                                &packet[1], received_blob_length,
1608                                                                gatt_client->attribute_offset);
1609                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY, received_blob_length);
1610                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1611                     break;
1612                 default:
1613                     break;
1614             }
1615             break;
1616         }
1617         case ATT_PREPARE_WRITE_RESPONSE:
1618             switch (gatt_client->gatt_client_state){
1619                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1620                     gatt_client_handle_transaction_complete(gatt_client);
1621                     if (is_value_valid(gatt_client, packet, size)){
1622                         emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1623                     } else {
1624                         emit_gatt_complete_event(gatt_client, ATT_ERROR_DATA_MISMATCH);
1625                     }
1626                     break;
1627 
1628                 case P_W4_PREPARE_WRITE_RESULT:{
1629                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1630                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1631                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1632                     break;
1633                 }
1634                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1635                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1636                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR, P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1637                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1638                     break;
1639                 }
1640                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT:{
1641                     if (is_value_valid(gatt_client, packet, size)){
1642                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1643                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1644                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1645                         break;
1646                     }
1647                     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1648                     break;
1649                 }
1650                 default:
1651                     break;
1652             }
1653             break;
1654 
1655         case ATT_EXECUTE_WRITE_RESPONSE:
1656             switch (gatt_client->gatt_client_state){
1657                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1658                     gatt_client_handle_transaction_complete(gatt_client);
1659                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1660                     break;
1661                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1662                     gatt_client_handle_transaction_complete(gatt_client);
1663                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1664                     break;
1665                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1666                     gatt_client_handle_transaction_complete(gatt_client);
1667                     emit_gatt_complete_event(gatt_client, ATT_ERROR_DATA_MISMATCH);
1668                     break;
1669                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1670                     gatt_client_handle_transaction_complete(gatt_client);
1671                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1672                     break;
1673                 default:
1674                     break;
1675 
1676             }
1677             break;
1678 
1679         case ATT_READ_MULTIPLE_RESPONSE:
1680             switch(gatt_client->gatt_client_state){
1681                 case P_W4_READ_MULTIPLE_RESPONSE:
1682                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
1683                     gatt_client_handle_transaction_complete(gatt_client);
1684                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1685                     break;
1686                 default:
1687                     break;
1688             }
1689             break;
1690 
1691         case ATT_ERROR_RESPONSE:
1692             if (size < 5u) return;
1693             error_code = packet[4];
1694             switch (error_code){
1695                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1696                     switch(gatt_client->gatt_client_state){
1697                         case P_W4_SERVICE_QUERY_RESULT:
1698                         case P_W4_SERVICE_WITH_UUID_RESULT:
1699                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1700                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1701                             gatt_client_handle_transaction_complete(gatt_client);
1702                             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1703                             break;
1704                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1705                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1706                             characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1707                             gatt_client_handle_transaction_complete(gatt_client);
1708                             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1709                             break;
1710                         case P_W4_READ_BY_TYPE_RESPONSE:
1711                             gatt_client_handle_transaction_complete(gatt_client);
1712                             if (gatt_client->start_group_handle == gatt_client->query_start_handle){
1713                                 emit_gatt_complete_event(gatt_client, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
1714                             } else {
1715                                 emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1716                             }
1717                             break;
1718                         default:
1719                             gatt_client_report_error_if_pending(gatt_client, error_code);
1720                             break;
1721                     }
1722                     break;
1723                 }
1724 
1725 #ifdef ENABLE_GATT_CLIENT_PAIRING
1726 
1727                 case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
1728                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
1729                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
1730 
1731                     // security too low
1732                     if (gatt_client->security_counter > 0) {
1733                         gatt_client_report_error_if_pending(gatt_client, error_code);
1734                         break;
1735                     }
1736                     // start security
1737                     gatt_client->security_counter++;
1738 
1739                     // setup action
1740                     int retry = 1;
1741                     switch (gatt_client->gatt_client_state){
1742                         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1743                             gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
1744                             break;
1745                         case P_W4_READ_BLOB_RESULT:
1746                             gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1747                             break;
1748                         case P_W4_READ_BY_TYPE_RESPONSE:
1749                             gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1750                             break;
1751                         case P_W4_READ_MULTIPLE_RESPONSE:
1752                             gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1753                             break;
1754                         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1755                             gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1756                             break;
1757                         case P_W4_PREPARE_WRITE_RESULT:
1758                             gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
1759                             break;
1760                         case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1761                             gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
1762                             break;
1763                         case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
1764                             gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1765                             break;
1766                         case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1767                             gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
1768                             break;
1769                         case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1770                             gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
1771                             break;
1772                         case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1773                             gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1774                             break;
1775                         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1776                             gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1777                             break;
1778                         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1779                             gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1780                             break;
1781                         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1782                             gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
1783                             break;
1784                         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1785                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1786                             break;
1787                         case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1788                             gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
1789                             break;
1790                         case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1791                             gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
1792                             break;
1793 #ifdef ENABLE_LE_SIGNED_WRITE
1794                         case P_W4_SEND_SINGED_WRITE_DONE:
1795                             gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1796                             break;
1797 #endif
1798                         default:
1799                             log_info("retry not supported for state %x", gatt_client->gatt_client_state);
1800                             retry = 0;
1801                             break;
1802                     }
1803 
1804                     if (!retry) {
1805                         gatt_client_report_error_if_pending(gatt_client, error_code);
1806                         break;
1807                     }
1808 
1809                     log_info("security error, start pairing");
1810 
1811                     // start pairing for higher security level
1812                     gatt_client->wait_for_authentication_complete = 1;
1813                     gatt_client->pending_error_code = error_code;
1814                     sm_request_pairing(gatt_client->con_handle);
1815                     break;
1816                 }
1817 #endif
1818 
1819                 // nothing we can do about that
1820                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
1821                 default:
1822                     gatt_client_report_error_if_pending(gatt_client, error_code);
1823                     break;
1824             }
1825             break;
1826 
1827         default:
1828             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
1829             break;
1830     }
1831     gatt_client_run();
1832 }
1833 
1834 #ifdef ENABLE_LE_SIGNED_WRITE
1835 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
1836     btstack_linked_list_iterator_t it;
1837     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
1838     while (btstack_linked_list_iterator_has_next(&it)){
1839         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
1840         if (gatt_client->gatt_client_state == P_W4_CMAC_RESULT){
1841             // store result
1842             (void)memcpy(gatt_client->cmac, hash, 8);
1843             // reverse_64(hash, gatt_client->cmac);
1844             gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1845             gatt_client_run();
1846             return;
1847         }
1848     }
1849 }
1850 
1851 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){
1852     gatt_client_t * gatt_client;
1853     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
1854     if (status != ERROR_CODE_SUCCESS){
1855         return status;
1856     }
1857     if (is_ready(gatt_client) == 0){
1858         return GATT_CLIENT_IN_WRONG_STATE;
1859     }
1860 
1861     gatt_client->callback = callback;
1862     gatt_client->attribute_handle = value_handle;
1863     gatt_client->attribute_length = message_len;
1864     gatt_client->attribute_value = message;
1865     gatt_client->gatt_client_state = P_W4_IDENTITY_RESOLVING;
1866     gatt_client_run();
1867     return ERROR_CODE_SUCCESS;
1868 }
1869 #endif
1870 
1871 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1872     gatt_client_t * gatt_client;
1873     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
1874     if (status != ERROR_CODE_SUCCESS){
1875         return status;
1876     }
1877     if (is_ready(gatt_client) == 0){
1878         return GATT_CLIENT_IN_WRONG_STATE;
1879     }
1880 
1881     gatt_client->callback = callback;
1882     gatt_client->start_group_handle = 0x0001;
1883     gatt_client->end_group_handle   = 0xffff;
1884     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
1885     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
1886     gatt_client_run();
1887     return ERROR_CODE_SUCCESS;
1888 }
1889 
1890 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1891     gatt_client_t * gatt_client;
1892     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
1893     if (status != ERROR_CODE_SUCCESS){
1894         return status;
1895     }
1896     if (is_ready(gatt_client) == 0){
1897         return GATT_CLIENT_IN_WRONG_STATE;
1898     }
1899 
1900     gatt_client->callback = callback;
1901     gatt_client->start_group_handle = 0x0001;
1902     gatt_client->end_group_handle   = 0xffff;
1903     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
1904     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
1905     gatt_client_run();
1906     return ERROR_CODE_SUCCESS;
1907 }
1908 
1909 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
1910     gatt_client_t * gatt_client;
1911     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
1912     if (status != ERROR_CODE_SUCCESS){
1913         return status;
1914     }
1915     if (is_ready(gatt_client) == 0){
1916         return GATT_CLIENT_IN_WRONG_STATE;
1917     }
1918 
1919     gatt_client->callback = callback;
1920     gatt_client->start_group_handle = 0x0001;
1921     gatt_client->end_group_handle   = 0xffff;
1922     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1923     gatt_client->uuid16 = uuid16;
1924     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
1925     gatt_client_run();
1926     return ERROR_CODE_SUCCESS;
1927 }
1928 
1929 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
1930     gatt_client_t * gatt_client;
1931     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
1932     if (status != ERROR_CODE_SUCCESS){
1933         return status;
1934     }
1935     if (is_ready(gatt_client) == 0){
1936         return GATT_CLIENT_IN_WRONG_STATE;
1937     }
1938 
1939     gatt_client->callback = callback;
1940     gatt_client->start_group_handle = 0x0001;
1941     gatt_client->end_group_handle   = 0xffff;
1942     gatt_client->uuid16 = 0;
1943     (void)memcpy(gatt_client->uuid128, uuid128, 16);
1944     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1945     gatt_client_run();
1946     return ERROR_CODE_SUCCESS;
1947 }
1948 
1949 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
1950     gatt_client_t * gatt_client;
1951     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
1952     if (status != ERROR_CODE_SUCCESS){
1953         return status;
1954     }
1955     if (is_ready(gatt_client) == 0){
1956         return GATT_CLIENT_IN_WRONG_STATE;
1957     }
1958 
1959     gatt_client->callback = callback;
1960     gatt_client->start_group_handle = service->start_group_handle;
1961     gatt_client->end_group_handle   = service->end_group_handle;
1962     gatt_client->filter_with_uuid = 0;
1963     gatt_client->characteristic_start_handle = 0;
1964     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
1965     gatt_client_run();
1966     return ERROR_CODE_SUCCESS;
1967 }
1968 
1969 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){
1970     gatt_client_t * gatt_client;
1971     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
1972     if (status != ERROR_CODE_SUCCESS){
1973         return status;
1974     }
1975     if (is_ready(gatt_client) == 0){
1976         return GATT_CLIENT_IN_WRONG_STATE;
1977     }
1978     gatt_client->callback = callback;
1979     gatt_client->start_group_handle = service->start_group_handle;
1980     gatt_client->end_group_handle   = service->end_group_handle;
1981     gatt_client->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
1982 
1983     gatt_client_run();
1984     return ERROR_CODE_SUCCESS;
1985 }
1986 
1987 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){
1988     gatt_client_t * gatt_client;
1989     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
1990     if (status != ERROR_CODE_SUCCESS){
1991         return status;
1992     }
1993     if (is_ready(gatt_client) == 0){
1994         return GATT_CLIENT_IN_WRONG_STATE;
1995     }
1996 
1997     gatt_client->callback = callback;
1998     gatt_client->start_group_handle = start_handle;
1999     gatt_client->end_group_handle   = end_handle;
2000     gatt_client->filter_with_uuid = 1;
2001     gatt_client->uuid16 = uuid16;
2002     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2003     gatt_client->characteristic_start_handle = 0;
2004     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2005     gatt_client_run();
2006     return ERROR_CODE_SUCCESS;
2007 }
2008 
2009 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){
2010     gatt_client_t * gatt_client;
2011     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2012     if (status != ERROR_CODE_SUCCESS){
2013         return status;
2014     }
2015     if (is_ready(gatt_client) == 0){
2016         return GATT_CLIENT_IN_WRONG_STATE;
2017     }
2018 
2019     gatt_client->callback = callback;
2020     gatt_client->start_group_handle = start_handle;
2021     gatt_client->end_group_handle   = end_handle;
2022     gatt_client->filter_with_uuid = 1;
2023     gatt_client->uuid16 = 0;
2024     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2025     gatt_client->characteristic_start_handle = 0;
2026     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2027     gatt_client_run();
2028     return ERROR_CODE_SUCCESS;
2029 }
2030 
2031 
2032 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){
2033     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2034 }
2035 
2036 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){
2037     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2038 }
2039 
2040 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2041     gatt_client_t * gatt_client;
2042     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2043     if (status != ERROR_CODE_SUCCESS){
2044         return status;
2045     }
2046     if (is_ready(gatt_client) == 0){
2047         return GATT_CLIENT_IN_WRONG_STATE;
2048     }
2049 
2050     if (characteristic->value_handle == characteristic->end_handle){
2051         emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
2052         return ERROR_CODE_SUCCESS;
2053     }
2054     gatt_client->callback = callback;
2055     gatt_client->start_group_handle = characteristic->value_handle + 1u;
2056     gatt_client->end_group_handle   = characteristic->end_handle;
2057     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2058     gatt_client_run();
2059     return ERROR_CODE_SUCCESS;
2060 }
2061 
2062 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){
2063     gatt_client_t * gatt_client;
2064     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2065     if (status != ERROR_CODE_SUCCESS){
2066         return status;
2067     }
2068     if (is_ready(gatt_client) == 0){
2069         return GATT_CLIENT_IN_WRONG_STATE;
2070     }
2071 
2072     gatt_client->callback = callback;
2073     gatt_client->attribute_handle = value_handle;
2074     gatt_client->attribute_offset = 0;
2075     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2076     gatt_client_run();
2077     return ERROR_CODE_SUCCESS;
2078 }
2079 
2080 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){
2081     gatt_client_t * gatt_client;
2082     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2083     if (status != ERROR_CODE_SUCCESS){
2084         return status;
2085     }
2086     if (is_ready(gatt_client) == 0){
2087         return GATT_CLIENT_IN_WRONG_STATE;
2088     }
2089 
2090     gatt_client->callback = callback;
2091     gatt_client->start_group_handle = start_handle;
2092     gatt_client->end_group_handle = end_handle;
2093     gatt_client->query_start_handle = start_handle;
2094     gatt_client->query_end_handle = end_handle;
2095     gatt_client->uuid16 = uuid16;
2096     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2097     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2098     gatt_client_run();
2099     return ERROR_CODE_SUCCESS;
2100 }
2101 
2102 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){
2103     gatt_client_t * gatt_client;
2104     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2105     if (status != ERROR_CODE_SUCCESS){
2106         return status;
2107     }
2108     if (is_ready(gatt_client) == 0){
2109         return GATT_CLIENT_IN_WRONG_STATE;
2110     }
2111 
2112     gatt_client->callback = callback;
2113     gatt_client->start_group_handle = start_handle;
2114     gatt_client->end_group_handle = end_handle;
2115     gatt_client->query_start_handle = start_handle;
2116     gatt_client->query_end_handle = end_handle;
2117     gatt_client->uuid16 = 0;
2118     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2119     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2120     gatt_client_run();
2121     return ERROR_CODE_SUCCESS;
2122 }
2123 
2124 
2125 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2126     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2127 }
2128 
2129 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){
2130     gatt_client_t * gatt_client;
2131     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2132     if (status != ERROR_CODE_SUCCESS){
2133         return status;
2134     }
2135     if (is_ready(gatt_client) == 0){
2136         return GATT_CLIENT_IN_WRONG_STATE;
2137     }
2138 
2139     gatt_client->callback = callback;
2140     gatt_client->attribute_handle = value_handle;
2141     gatt_client->attribute_offset = offset;
2142     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
2143     gatt_client_run();
2144     return ERROR_CODE_SUCCESS;
2145 }
2146 
2147 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){
2148     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2149 }
2150 
2151 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){
2152     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2153 }
2154 
2155 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){
2156     gatt_client_t * gatt_client;
2157     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2158     if (status != ERROR_CODE_SUCCESS){
2159         return status;
2160     }
2161     if (is_ready(gatt_client) == 0){
2162         return GATT_CLIENT_IN_WRONG_STATE;
2163     }
2164 
2165     gatt_client->callback = callback;
2166     gatt_client->read_multiple_handle_count = num_value_handles;
2167     gatt_client->read_multiple_handles = value_handles;
2168     gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2169     gatt_client_run();
2170     return ERROR_CODE_SUCCESS;
2171 }
2172 
2173 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){
2174     gatt_client_t * gatt_client;
2175     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2176     if (status != ERROR_CODE_SUCCESS){
2177         return status;
2178     }
2179 
2180     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2181     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2182 
2183     return att_write_request(ATT_WRITE_COMMAND, gatt_client->con_handle, value_handle, value_length, value);
2184 }
2185 
2186 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){
2187     gatt_client_t * gatt_client;
2188     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2189     if (status != ERROR_CODE_SUCCESS){
2190         return status;
2191     }
2192     if (is_ready(gatt_client) == 0){
2193         return GATT_CLIENT_IN_WRONG_STATE;
2194     }
2195 
2196     gatt_client->callback = callback;
2197     gatt_client->attribute_handle = value_handle;
2198     gatt_client->attribute_length = value_length;
2199     gatt_client->attribute_value = value;
2200     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2201     gatt_client_run();
2202     return ERROR_CODE_SUCCESS;
2203 }
2204 
2205 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){
2206     gatt_client_t * gatt_client;
2207     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2208     if (status != ERROR_CODE_SUCCESS){
2209         return status;
2210     }
2211     if (is_ready(gatt_client) == 0){
2212         return GATT_CLIENT_IN_WRONG_STATE;
2213     }
2214 
2215     gatt_client->callback = callback;
2216     gatt_client->attribute_handle = value_handle;
2217     gatt_client->attribute_length = value_length;
2218     gatt_client->attribute_offset = offset;
2219     gatt_client->attribute_value = value;
2220     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
2221     gatt_client_run();
2222     return ERROR_CODE_SUCCESS;
2223 }
2224 
2225 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){
2226     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2227 }
2228 
2229 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){
2230     gatt_client_t * gatt_client;
2231     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2232     if (status != ERROR_CODE_SUCCESS){
2233         return status;
2234     }
2235     if (is_ready(gatt_client) == 0){
2236         return GATT_CLIENT_IN_WRONG_STATE;
2237     }
2238 
2239     gatt_client->callback = callback;
2240     gatt_client->attribute_handle = value_handle;
2241     gatt_client->attribute_length = value_length;
2242     gatt_client->attribute_offset = 0;
2243     gatt_client->attribute_value = value;
2244     gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
2245     gatt_client_run();
2246     return ERROR_CODE_SUCCESS;
2247 }
2248 
2249 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){
2250     gatt_client_t * gatt_client;
2251     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2252     if (status != ERROR_CODE_SUCCESS){
2253         return status;
2254     }
2255     if (is_ready(gatt_client) == 0){
2256         return GATT_CLIENT_IN_WRONG_STATE;
2257     }
2258 
2259     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2260         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2261         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2262         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2263     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2264                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2265         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2266         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2267     }
2268 
2269     gatt_client->callback = callback;
2270     gatt_client->start_group_handle = characteristic->value_handle;
2271     gatt_client->end_group_handle = characteristic->end_handle;
2272     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2273 
2274 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2275     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2276 #else
2277     gatt_client->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2278 #endif
2279     gatt_client_run();
2280     return ERROR_CODE_SUCCESS;
2281 }
2282 
2283 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){
2284     gatt_client_t * gatt_client;
2285     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2286     if (status != ERROR_CODE_SUCCESS){
2287         return status;
2288     }
2289     if (is_ready(gatt_client) == 0){
2290         return GATT_CLIENT_IN_WRONG_STATE;
2291     }
2292 
2293     gatt_client->callback = callback;
2294     gatt_client->attribute_handle = descriptor_handle;
2295 
2296     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2297     gatt_client_run();
2298     return ERROR_CODE_SUCCESS;
2299 }
2300 
2301 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2302     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2303 }
2304 
2305 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){
2306     gatt_client_t * gatt_client;
2307     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2308     if (status != ERROR_CODE_SUCCESS){
2309         return status;
2310     }
2311     if (is_ready(gatt_client) == 0){
2312         return GATT_CLIENT_IN_WRONG_STATE;
2313     }
2314 
2315     gatt_client->callback = callback;
2316     gatt_client->attribute_handle = descriptor_handle;
2317     gatt_client->attribute_offset = offset;
2318     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2319     gatt_client_run();
2320     return ERROR_CODE_SUCCESS;
2321 }
2322 
2323 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){
2324     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2325 }
2326 
2327 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){
2328     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2329 }
2330 
2331 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){
2332     gatt_client_t * gatt_client;
2333     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2334     if (status != ERROR_CODE_SUCCESS){
2335         return status;
2336     }
2337     if (is_ready(gatt_client) == 0){
2338         return GATT_CLIENT_IN_WRONG_STATE;
2339     }
2340 
2341     gatt_client->callback = callback;
2342     gatt_client->attribute_handle = descriptor_handle;
2343     gatt_client->attribute_length = value_length;
2344     gatt_client->attribute_offset = 0;
2345     gatt_client->attribute_value = value;
2346     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2347     gatt_client_run();
2348     return ERROR_CODE_SUCCESS;
2349 }
2350 
2351 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){
2352     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2353 }
2354 
2355 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){
2356     gatt_client_t * gatt_client;
2357     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2358     if (status != ERROR_CODE_SUCCESS){
2359         return status;
2360     }
2361     if (is_ready(gatt_client) == 0){
2362         return GATT_CLIENT_IN_WRONG_STATE;
2363     }
2364 
2365     gatt_client->callback = callback;
2366     gatt_client->attribute_handle = descriptor_handle;
2367     gatt_client->attribute_length = value_length;
2368     gatt_client->attribute_offset = offset;
2369     gatt_client->attribute_value = value;
2370     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2371     gatt_client_run();
2372     return ERROR_CODE_SUCCESS;
2373 }
2374 
2375 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){
2376     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2377 }
2378 
2379 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){
2380     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2381 }
2382 
2383 /**
2384  * @brief -> gatt complete event
2385  */
2386 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){
2387     gatt_client_t * gatt_client;
2388     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2389     if (status != ERROR_CODE_SUCCESS){
2390         return status;
2391     }
2392     if (is_ready(gatt_client) == 0){
2393         return GATT_CLIENT_IN_WRONG_STATE;
2394     }
2395 
2396     gatt_client->callback = callback;
2397     gatt_client->attribute_handle = attribute_handle;
2398     gatt_client->attribute_length = value_length;
2399     gatt_client->attribute_offset = offset;
2400     gatt_client->attribute_value = value;
2401     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
2402     gatt_client_run();
2403     return ERROR_CODE_SUCCESS;
2404 }
2405 
2406 /**
2407  * @brief -> gatt complete event
2408  */
2409 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2410     gatt_client_t * gatt_client;
2411     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2412     if (status != ERROR_CODE_SUCCESS){
2413         return status;
2414     }
2415     if (is_ready(gatt_client) == 0){
2416         return GATT_CLIENT_IN_WRONG_STATE;
2417     }
2418 
2419     gatt_client->callback = callback;
2420     gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
2421     gatt_client_run();
2422     return ERROR_CODE_SUCCESS;
2423 }
2424 
2425 /**
2426  * @brief -> gatt complete event
2427  */
2428 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2429     gatt_client_t * gatt_client;
2430     uint8_t status = gatt_client_provide_context_for_handle_and_start_timer(con_handle, &gatt_client);
2431     if (status != ERROR_CODE_SUCCESS){
2432         return status;
2433     }
2434     if (is_ready(gatt_client) == 0){
2435         return GATT_CLIENT_IN_WRONG_STATE;
2436     }
2437 
2438     gatt_client->callback = callback;
2439     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
2440     gatt_client_run();
2441     return ERROR_CODE_SUCCESS;
2442 }
2443 
2444 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
2445     service->start_group_handle = little_endian_read_16(packet, offset);
2446     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2447     reverse_128(&packet[offset + 4], service->uuid128);
2448     if (uuid_has_bluetooth_prefix(service->uuid128)){
2449         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2450     } else {
2451         service->uuid16 = 0;
2452     }
2453 }
2454 
2455 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2456     characteristic->start_handle = little_endian_read_16(packet, offset);
2457     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2458     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2459     characteristic->properties = little_endian_read_16(packet, offset + 6);
2460     reverse_128(&packet[offset+8], characteristic->uuid128);
2461     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2462         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2463     } else {
2464         characteristic->uuid16 = 0;
2465     }
2466 }
2467 
2468 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2469     descriptor->handle = little_endian_read_16(packet, offset);
2470     reverse_128(&packet[offset+2], descriptor->uuid128);
2471     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2472         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2473     } else {
2474         descriptor->uuid16 = 0;
2475     }
2476 }
2477 
2478 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2479     gatt_client_t * gatt_client;
2480     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2481     if (status != ERROR_CODE_SUCCESS){
2482         return;
2483     }
2484     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2485         gatt_client->callback = callback;
2486         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
2487         gatt_client_run();
2488     }
2489 }
2490 
2491 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2492     gatt_client_t * gatt_client;
2493     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2494     if (status != ERROR_CODE_SUCCESS){
2495         return status;
2496     }
2497     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
2498     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2499     if (added){
2500         return ERROR_CODE_SUCCESS;
2501     } else {
2502         return ERROR_CODE_COMMAND_DISALLOWED;
2503     }
2504 }
2505 
2506 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2507     gatt_client_t * gatt_client;
2508     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2509     if (status != ERROR_CODE_SUCCESS){
2510         return status;
2511     }
2512     if (gatt_client->write_without_response_callback != NULL){
2513         return GATT_CLIENT_IN_WRONG_STATE;
2514     }
2515     gatt_client->write_without_response_callback = callback;
2516     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2517     return ERROR_CODE_SUCCESS;
2518 }
2519 
2520 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2521 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2522     gatt_client_att_packet_handler(packet_type, handle, packet, size);
2523 }
2524 
2525 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
2526     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
2527     return status;
2528 }
2529 #endif
2530