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