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