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