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