xref: /btstack/src/ble/gatt_client.c (revision abdc9fb59b2eadafc2464f74b9b2ad9a5ac43b00)
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             gatt_client_report_error_if_pending(peripheral, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1096 
1097             btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) peripheral);
1098             btstack_memory_gatt_client_free(peripheral);
1099             break;
1100 
1101 #ifdef ENABLE_GATT_CLIENT_PAIRING
1102         // Pairing complete (with/without bonding=storing of pairing information)
1103         case SM_EVENT_PAIRING_COMPLETE:
1104             con_handle = sm_event_pairing_complete_get_handle(packet);
1105             peripheral = get_gatt_client_context_for_handle(con_handle);
1106             if (!peripheral) break;
1107 
1108             if (peripheral->wait_for_pairing_complete){
1109                 peripheral->wait_for_pairing_complete = 0;
1110                 if (sm_event_pairing_complete_get_status(packet)){
1111                     log_info("pairing failed, report previous error 0x%x", peripheral->pending_error_code);
1112                     gatt_client_handle_transaction_complete(peripheral);
1113                     emit_gatt_complete_event(peripheral, peripheral->pending_error_code);
1114                 } else {
1115                     log_info("pairing success, retry operation");
1116                 }
1117             }
1118             break;
1119 #endif
1120 
1121         default:
1122             break;
1123     }
1124 
1125     gatt_client_run();
1126 }
1127 
1128 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
1129 
1130     gatt_client_t * peripheral;
1131 
1132     if (packet_type == HCI_EVENT_PACKET) {
1133         switch (packet[0]){
1134             case L2CAP_EVENT_CAN_SEND_NOW:
1135                 gatt_client_run();
1136                 break;
1137             // att_server has negotiated the mtu for this connection, cache if context exists
1138             case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
1139                 peripheral = get_gatt_client_context_for_handle(handle);
1140                 if (!peripheral) break;
1141                 peripheral->mtu = little_endian_read_16(packet, 4);
1142                 break;
1143             default:
1144                 break;
1145         }
1146         return;
1147     }
1148 
1149     if (packet_type != ATT_DATA_PACKET) return;
1150 
1151     // special cases: notifications don't need a context while indications motivate creating one
1152     switch (packet[0]){
1153         case ATT_HANDLE_VALUE_NOTIFICATION:
1154             report_gatt_notification(handle, little_endian_read_16(packet,1), &packet[3], size-3);
1155             return;
1156         case ATT_HANDLE_VALUE_INDICATION:
1157             peripheral = provide_context_for_conn_handle(handle);
1158             break;
1159         default:
1160             peripheral = get_gatt_client_context_for_handle(handle);
1161             break;
1162     }
1163 
1164     if (!peripheral) return;
1165 
1166     switch (packet[0]){
1167         case ATT_EXCHANGE_MTU_RESPONSE:
1168         {
1169             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1170             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1171             peripheral->mtu = remote_rx_mtu < local_rx_mtu ? remote_rx_mtu : local_rx_mtu;
1172             peripheral->mtu_state = MTU_EXCHANGED;
1173             emit_gatt_mtu_exchanged_result_event(peripheral, peripheral->mtu);
1174             break;
1175         }
1176         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
1177             switch(peripheral->gatt_client_state){
1178                 case P_W4_SERVICE_QUERY_RESULT:
1179                     report_gatt_services(peripheral, packet, size);
1180                     trigger_next_service_query(peripheral, get_last_result_handle_from_service_list(packet, size));
1181                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1182                     break;
1183                 default:
1184                     break;
1185             }
1186             break;
1187         case ATT_HANDLE_VALUE_INDICATION:
1188             report_gatt_indication(handle, little_endian_read_16(packet,1), &packet[3], size-3);
1189             peripheral->send_confirmation = 1;
1190             break;
1191 
1192         case ATT_READ_BY_TYPE_RESPONSE:
1193             switch (peripheral->gatt_client_state){
1194                 case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1195                     report_gatt_characteristics(peripheral, packet, size);
1196                     trigger_next_characteristic_query(peripheral, get_last_result_handle_from_characteristics_list(packet, size));
1197                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1198                     break;
1199                 case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1200                     report_gatt_characteristics(peripheral, packet, size);
1201                     trigger_next_characteristic_query(peripheral, get_last_result_handle_from_characteristics_list(packet, size));
1202                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1203                     break;
1204                 case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1205                 {
1206                     uint16_t uuid16 = 0;
1207                     uint16_t pair_size = packet[1];
1208 
1209                     if (pair_size < 7){
1210                         // UUIDs not available, query first included service
1211                         peripheral->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1212                         peripheral->query_start_handle = little_endian_read_16(packet, 4);
1213                         peripheral->query_end_handle = little_endian_read_16(packet,6);
1214                         peripheral->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1215                         break;
1216                     }
1217 
1218                     uint16_t offset;
1219                     for (offset = 2; offset < size; offset += pair_size){
1220                         uint16_t include_handle = little_endian_read_16(packet, offset);
1221                         peripheral->query_start_handle = little_endian_read_16(packet,offset+2);
1222                         peripheral->query_end_handle = little_endian_read_16(packet,offset+4);
1223                         uuid16 = little_endian_read_16(packet, offset+6);
1224                         report_gatt_included_service_uuid16(peripheral, include_handle, uuid16);
1225                     }
1226 
1227                     trigger_next_included_service_query(peripheral, get_last_result_handle_from_included_services_list(packet, size));
1228                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1229                     break;
1230                 }
1231 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1232                 case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1233                     peripheral->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1234                     peripheral->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1235                     break;
1236 #endif
1237                 case P_W4_READ_BY_TYPE_RESPONSE: {
1238                     uint16_t pair_size = packet[1];
1239                     uint16_t offset;
1240                     uint16_t last_result_handle = 0;
1241                     for (offset = 2; offset < size ; offset += pair_size){
1242                         uint16_t value_handle = little_endian_read_16(packet, offset);
1243                         report_gatt_characteristic_value(peripheral, value_handle, &packet[offset+2], pair_size-2);
1244                         last_result_handle = value_handle;
1245                     }
1246                     trigger_next_read_by_type_query(peripheral, last_result_handle);
1247                     break;
1248                 }
1249                 default:
1250                     break;
1251             }
1252             break;
1253         case ATT_READ_RESPONSE:
1254             switch (peripheral->gatt_client_state){
1255                 case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT: {
1256                     uint8_t uuid128[16];
1257                     reverse_128(&packet[1], uuid128);
1258                     report_gatt_included_service_uuid128(peripheral, peripheral->start_group_handle, uuid128);
1259                     trigger_next_included_service_query(peripheral, peripheral->start_group_handle);
1260                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1261                     break;
1262                 }
1263                 case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1264                     gatt_client_handle_transaction_complete(peripheral);
1265                     report_gatt_characteristic_value(peripheral, peripheral->attribute_handle, &packet[1], size-1);
1266                     emit_gatt_complete_event(peripheral, 0);
1267                     break;
1268 
1269                 case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1270                     gatt_client_handle_transaction_complete(peripheral);
1271                     report_gatt_characteristic_descriptor(peripheral, peripheral->attribute_handle, &packet[1], size-1, 0);
1272                     emit_gatt_complete_event(peripheral, 0);
1273                     break;
1274                 }
1275                 default:
1276                     break;
1277             }
1278             break;
1279 
1280         case ATT_FIND_BY_TYPE_VALUE_RESPONSE:
1281         {
1282             uint8_t pair_size = 4;
1283             int i;
1284             uint16_t start_group_handle;
1285             uint16_t   end_group_handle= 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
1286             for (i = 1; i<size; i+=pair_size){
1287                 start_group_handle = little_endian_read_16(packet,i);
1288                 end_group_handle = little_endian_read_16(packet,i+2);
1289                 emit_gatt_service_query_result_event(peripheral, start_group_handle, end_group_handle, peripheral->uuid128);
1290             }
1291             trigger_next_service_by_uuid_query(peripheral, end_group_handle);
1292             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1293             break;
1294         }
1295         case ATT_FIND_INFORMATION_REPLY:
1296         {
1297             uint8_t pair_size = 4;
1298             if (packet[1] == 2){
1299                 pair_size = 18;
1300             }
1301             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
1302 
1303 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1304             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", peripheral->gatt_client_state);
1305             if (peripheral->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
1306                 // iterate over descriptors looking for CCC
1307                 if (pair_size == 4){
1308                     int offset = 2;
1309                     while (offset < size){
1310                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
1311                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
1312                             peripheral->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
1313                             peripheral->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1314                             log_info("CCC found %x", peripheral->client_characteristic_configuration_handle);
1315                             break;
1316                         }
1317                         offset += pair_size;
1318                     }
1319                 }
1320                 if (is_query_done(peripheral, last_descriptor_handle)){
1321 
1322                 } else {
1323                     // next
1324                     peripheral->start_group_handle = last_descriptor_handle + 1;
1325                     peripheral->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1326                 }
1327                 break;
1328             }
1329 #endif
1330             report_gatt_all_characteristic_descriptors(peripheral, &packet[2], size-2, pair_size);
1331             trigger_next_characteristic_descriptor_query(peripheral, last_descriptor_handle);
1332             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1333             break;
1334         }
1335 
1336         case ATT_WRITE_RESPONSE:
1337             switch (peripheral->gatt_client_state){
1338                 case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1339                     gatt_client_handle_transaction_complete(peripheral);
1340                     emit_gatt_complete_event(peripheral, 0);
1341                     break;
1342                 case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1343                     gatt_client_handle_transaction_complete(peripheral);
1344                     emit_gatt_complete_event(peripheral, 0);
1345                     break;
1346                 case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1347                     gatt_client_handle_transaction_complete(peripheral);
1348                     emit_gatt_complete_event(peripheral, 0);
1349                     break;
1350                 default:
1351                     break;
1352             }
1353             break;
1354 
1355         case ATT_READ_BLOB_RESPONSE:{
1356             uint16_t received_blob_length = size-1;
1357             switch(peripheral->gatt_client_state){
1358                 case P_W4_READ_BLOB_RESULT:
1359                     report_gatt_long_characteristic_value_blob(peripheral, peripheral->attribute_handle, &packet[1], received_blob_length, peripheral->attribute_offset);
1360                     trigger_next_blob_query(peripheral, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
1361                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1362                     break;
1363                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1364                     report_gatt_long_characteristic_descriptor(peripheral, peripheral->attribute_handle,
1365                                                           &packet[1], received_blob_length,
1366                                                           peripheral->attribute_offset);
1367                     trigger_next_blob_query(peripheral, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY, received_blob_length);
1368                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1369                     break;
1370                 default:
1371                     break;
1372             }
1373             break;
1374         }
1375         case ATT_PREPARE_WRITE_RESPONSE:
1376             switch (peripheral->gatt_client_state){
1377                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1378                     gatt_client_handle_transaction_complete(peripheral);
1379                     if (is_value_valid(peripheral, packet, size)){
1380                         emit_gatt_complete_event(peripheral, 0);
1381                     } else {
1382                         emit_gatt_complete_event(peripheral, ATT_ERROR_DATA_MISMATCH);
1383                     }
1384                     break;
1385 
1386                 case P_W4_PREPARE_WRITE_RESULT:{
1387                     peripheral->attribute_offset = little_endian_read_16(packet, 3);
1388                     trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1389                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1390                     break;
1391                 }
1392                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1393                     peripheral->attribute_offset = little_endian_read_16(packet, 3);
1394                     trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR, P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1395                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1396                     break;
1397                 }
1398                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT:{
1399                     if (is_value_valid(peripheral, packet, size)){
1400                         peripheral->attribute_offset = little_endian_read_16(packet, 3);
1401                         trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_RELIABLE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1402                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1403                         break;
1404                     }
1405                     peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1406                     break;
1407                 }
1408                 default:
1409                     break;
1410             }
1411             break;
1412 
1413         case ATT_EXECUTE_WRITE_RESPONSE:
1414             switch (peripheral->gatt_client_state){
1415                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1416                     gatt_client_handle_transaction_complete(peripheral);
1417                     emit_gatt_complete_event(peripheral, 0);
1418                     break;
1419                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1420                     gatt_client_handle_transaction_complete(peripheral);
1421                     emit_gatt_complete_event(peripheral, 0);
1422                     break;
1423                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1424                     gatt_client_handle_transaction_complete(peripheral);
1425                     emit_gatt_complete_event(peripheral, ATT_ERROR_DATA_MISMATCH);
1426                     break;
1427                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1428                     gatt_client_handle_transaction_complete(peripheral);
1429                     emit_gatt_complete_event(peripheral, 0);
1430                     break;
1431                 default:
1432                     break;
1433 
1434             }
1435             break;
1436 
1437         case ATT_READ_MULTIPLE_RESPONSE:
1438             switch(peripheral->gatt_client_state){
1439                 case P_W4_READ_MULTIPLE_RESPONSE:
1440                     report_gatt_characteristic_value(peripheral, 0, &packet[1], size-1);
1441                     gatt_client_handle_transaction_complete(peripheral);
1442                     emit_gatt_complete_event(peripheral, 0);
1443                     break;
1444                 default:
1445                     break;
1446             }
1447             break;
1448 
1449         case ATT_ERROR_RESPONSE:
1450 
1451             switch (packet[4]){
1452                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1453                     switch(peripheral->gatt_client_state){
1454                         case P_W4_SERVICE_QUERY_RESULT:
1455                         case P_W4_SERVICE_WITH_UUID_RESULT:
1456                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1457                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1458                             gatt_client_handle_transaction_complete(peripheral);
1459                             emit_gatt_complete_event(peripheral, 0);
1460                             break;
1461                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1462                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1463                             characteristic_end_found(peripheral, peripheral->end_group_handle);
1464                             gatt_client_handle_transaction_complete(peripheral);
1465                             emit_gatt_complete_event(peripheral, 0);
1466                             break;
1467                         case P_W4_READ_BY_TYPE_RESPONSE:
1468                             gatt_client_handle_transaction_complete(peripheral);
1469                             if (peripheral->start_group_handle == peripheral->query_start_handle){
1470                                 emit_gatt_complete_event(peripheral, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
1471                             } else {
1472                                 emit_gatt_complete_event(peripheral, 0);
1473                             }
1474                             break;
1475                         default:
1476                             gatt_client_report_error_if_pending(peripheral, packet[4]);
1477                             break;
1478                     }
1479                     break;
1480                 }
1481 
1482 #ifdef ENABLE_GATT_CLIENT_PAIRING
1483 
1484                 case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
1485                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
1486                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION:
1487                     // security too low
1488                     if (peripheral->security_counter > 0) {
1489                         gatt_client_report_error_if_pending(peripheral, packet[4]);
1490                         break;
1491                     }
1492                     // start security
1493                     peripheral->security_counter++;
1494 
1495                     // setup action
1496                     int retry = 1;
1497                     switch (peripheral->gatt_client_state){
1498                         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1499                             peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
1500                             break;
1501                         case P_W4_READ_BLOB_RESULT:
1502                             peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1503                             break;
1504                         case P_W4_READ_BY_TYPE_RESPONSE:
1505                             peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1506                             break;
1507                         case P_W4_READ_MULTIPLE_RESPONSE:
1508                             peripheral->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1509                             break;
1510                         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1511                             peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1512                             break;
1513                         case P_W4_PREPARE_WRITE_RESULT:
1514                             peripheral->gatt_client_state = P_W2_PREPARE_WRITE;
1515                             break;
1516                         case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1517                             peripheral->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
1518                             break;
1519                         case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
1520                             peripheral->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1521                             break;
1522                         case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1523                             peripheral->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
1524                             break;
1525                         case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1526                             peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
1527                             break;
1528                         case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1529                             peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1530                             break;
1531                         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1532                             peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1533                             break;
1534                         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1535                             peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1536                             break;
1537                         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1538                             peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
1539                             break;
1540                         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1541                             peripheral->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1542                             break;
1543                         case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1544                             peripheral->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
1545                             break;
1546                         case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1547                             peripheral->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
1548                             break;
1549 #ifdef ENABLE_LE_SIGNED_WRITE
1550                         case P_W4_SEND_SINGED_WRITE_DONE:
1551                             peripheral->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1552                             break;
1553 #endif
1554                         default:
1555                             log_info("retry not supported for state %x", peripheral->gatt_client_state);
1556                             retry = 0;
1557                             break;
1558                     }
1559 
1560                     if (!retry) {
1561                         gatt_client_report_error_if_pending(peripheral, packet[4]);
1562                         break;
1563                     }
1564 
1565                     log_info("security error, start pairing");
1566 
1567                     // requrest pairing
1568                     peripheral->wait_for_pairing_complete = 1;
1569                     peripheral->pending_error_code = packet[4];
1570                     sm_request_pairing(peripheral->con_handle);
1571                     break;
1572 #endif
1573 
1574                 // nothing we can do about that
1575                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
1576                 default:
1577                     gatt_client_report_error_if_pending(peripheral, packet[4]);
1578                     break;
1579             }
1580             break;
1581 
1582         default:
1583             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
1584             break;
1585     }
1586     gatt_client_run();
1587 }
1588 
1589 #ifdef ENABLE_LE_SIGNED_WRITE
1590 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
1591     btstack_linked_list_iterator_t it;
1592     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
1593     while (btstack_linked_list_iterator_has_next(&it)){
1594         gatt_client_t * peripheral = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
1595         if (peripheral->gatt_client_state == P_W4_CMAC_RESULT){
1596             // store result
1597             memcpy(peripheral->cmac, hash, 8);
1598             // reverse_64(hash, peripheral->cmac);
1599             peripheral->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1600             gatt_client_run();
1601             return;
1602         }
1603     }
1604 }
1605 
1606 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){
1607     gatt_client_t * peripheral = provide_context_for_conn_handle(con_handle);
1608     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1609     peripheral->le_device_index = sm_le_device_index(con_handle);
1610     if (peripheral->le_device_index < 0) return GATT_CLIENT_IN_WRONG_STATE; // device lookup not done / no stored bonding information
1611 
1612     peripheral->callback = callback;
1613     peripheral->attribute_handle = handle;
1614     peripheral->attribute_length = message_len;
1615     peripheral->attribute_value = message;
1616     peripheral->gatt_client_state = P_W4_CMAC_READY;
1617 
1618     gatt_client_run();
1619     return 0;
1620 }
1621 #endif
1622 
1623 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1624     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1625     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1626     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1627 
1628     peripheral->callback = callback;
1629     peripheral->start_group_handle = 0x0001;
1630     peripheral->end_group_handle   = 0xffff;
1631     peripheral->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
1632     peripheral->uuid16 = 0;
1633     gatt_client_run();
1634     return 0;
1635 }
1636 
1637 
1638 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
1639     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1640 
1641     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1642     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1643 
1644     peripheral->callback = callback;
1645     peripheral->start_group_handle = 0x0001;
1646     peripheral->end_group_handle   = 0xffff;
1647     peripheral->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1648     peripheral->uuid16 = uuid16;
1649     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), peripheral->uuid16);
1650     gatt_client_run();
1651     return 0;
1652 }
1653 
1654 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
1655     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1656 
1657     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1658     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1659 
1660     peripheral->callback = callback;
1661     peripheral->start_group_handle = 0x0001;
1662     peripheral->end_group_handle   = 0xffff;
1663     peripheral->uuid16 = 0;
1664     memcpy(peripheral->uuid128, uuid128, 16);
1665     peripheral->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1666     gatt_client_run();
1667     return 0;
1668 }
1669 
1670 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t *service){
1671     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1672 
1673     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1674     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1675 
1676     peripheral->callback = callback;
1677     peripheral->start_group_handle = service->start_group_handle;
1678     peripheral->end_group_handle   = service->end_group_handle;
1679     peripheral->filter_with_uuid = 0;
1680     peripheral->characteristic_start_handle = 0;
1681     peripheral->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
1682     gatt_client_run();
1683     return 0;
1684 }
1685 
1686 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){
1687     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1688 
1689     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1690     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1691 
1692     peripheral->callback = callback;
1693     peripheral->start_group_handle = service->start_group_handle;
1694     peripheral->end_group_handle   = service->end_group_handle;
1695     peripheral->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
1696 
1697     gatt_client_run();
1698     return 0;
1699 }
1700 
1701 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){
1702     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1703 
1704     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1705     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1706 
1707     peripheral->callback = callback;
1708     peripheral->start_group_handle = start_handle;
1709     peripheral->end_group_handle   = end_handle;
1710     peripheral->filter_with_uuid = 1;
1711     peripheral->uuid16 = uuid16;
1712     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), uuid16);
1713     peripheral->characteristic_start_handle = 0;
1714     peripheral->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
1715 
1716     gatt_client_run();
1717     return 0;
1718 }
1719 
1720 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){
1721     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1722 
1723     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1724     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1725 
1726     peripheral->callback = callback;
1727     peripheral->start_group_handle = start_handle;
1728     peripheral->end_group_handle   = end_handle;
1729     peripheral->filter_with_uuid = 1;
1730     peripheral->uuid16 = 0;
1731     memcpy(peripheral->uuid128, uuid128, 16);
1732     peripheral->characteristic_start_handle = 0;
1733     peripheral->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
1734 
1735     gatt_client_run();
1736     return 0;
1737 }
1738 
1739 
1740 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){
1741     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, handle, service->start_group_handle, service->end_group_handle, uuid16);
1742 }
1743 
1744 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){
1745     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, handle, service->start_group_handle, service->end_group_handle, uuid128);
1746 }
1747 
1748 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t *characteristic){
1749     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1750 
1751     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1752     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1753 
1754     if (characteristic->value_handle == characteristic->end_handle){
1755         emit_gatt_complete_event(peripheral, 0);
1756         return 0;
1757     }
1758     peripheral->callback = callback;
1759     peripheral->start_group_handle = characteristic->value_handle + 1;
1760     peripheral->end_group_handle   = characteristic->end_handle;
1761     peripheral->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
1762 
1763     gatt_client_run();
1764     return 0;
1765 }
1766 
1767 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){
1768     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1769 
1770     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1771     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1772 
1773     peripheral->callback = callback;
1774     peripheral->attribute_handle = value_handle;
1775     peripheral->attribute_offset = 0;
1776     peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
1777     gatt_client_run();
1778     return 0;
1779 }
1780 
1781 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){
1782     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1783 
1784     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1785     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1786 
1787     peripheral->callback = callback;
1788     peripheral->start_group_handle = start_handle;
1789     peripheral->end_group_handle = end_handle;
1790     peripheral->query_start_handle = start_handle;
1791     peripheral->query_end_handle = end_handle;
1792     peripheral->uuid16 = uuid16;
1793     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), uuid16);
1794     peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1795     gatt_client_run();
1796     return 0;
1797 }
1798 
1799 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){
1800     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1801 
1802     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1803     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1804 
1805     peripheral->callback = callback;
1806     peripheral->start_group_handle = start_handle;
1807     peripheral->end_group_handle = end_handle;
1808     peripheral->query_start_handle = start_handle;
1809     peripheral->query_end_handle = end_handle;
1810     peripheral->uuid16 = 0;
1811     memcpy(peripheral->uuid128, uuid128, 16);
1812     peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1813     gatt_client_run();
1814     return 0;
1815 }
1816 
1817 
1818 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, uint16_t handle, gatt_client_characteristic_t *characteristic){
1819     return gatt_client_read_value_of_characteristic_using_value_handle(callback, handle, characteristic->value_handle);
1820 }
1821 
1822 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){
1823     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1824 
1825     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1826     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1827 
1828     peripheral->callback = callback;
1829     peripheral->attribute_handle = characteristic_value_handle;
1830     peripheral->attribute_offset = offset;
1831     peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1832     gatt_client_run();
1833     return 0;
1834 }
1835 
1836 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){
1837     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, characteristic_value_handle, 0);
1838 }
1839 
1840 uint8_t gatt_client_read_long_value_of_characteristic(btstack_packet_handler_t callback, uint16_t handle, gatt_client_characteristic_t *characteristic){
1841     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, handle, characteristic->value_handle);
1842 }
1843 
1844 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){
1845     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1846 
1847     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1848     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1849 
1850     peripheral->callback = callback;
1851     peripheral->read_multiple_handle_count = num_value_handles;
1852     peripheral->read_multiple_handles = value_handles;
1853     peripheral->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1854     gatt_client_run();
1855     return 0;
1856 }
1857 
1858 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){
1859     gatt_client_t * peripheral = provide_context_for_conn_handle(con_handle);
1860 
1861     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1862     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1863 
1864     if (value_length > peripheral_mtu(peripheral) - 3) return GATT_CLIENT_VALUE_TOO_LONG;
1865     if (!att_dispatch_client_can_send_now(peripheral->con_handle)) return GATT_CLIENT_BUSY;
1866 
1867     att_write_request(ATT_WRITE_COMMAND, peripheral->con_handle, value_handle, value_length, value);
1868     return 0;
1869 }
1870 
1871 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){
1872     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1873 
1874     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1875     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1876 
1877     peripheral->callback = callback;
1878     peripheral->attribute_handle = value_handle;
1879     peripheral->attribute_length = value_length;
1880     peripheral->attribute_value = data;
1881     peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1882     gatt_client_run();
1883     return 0;
1884 }
1885 
1886 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){
1887     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1888 
1889     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1890     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1891 
1892     peripheral->callback = callback;
1893     peripheral->attribute_handle = value_handle;
1894     peripheral->attribute_length = value_length;
1895     peripheral->attribute_offset = offset;
1896     peripheral->attribute_value = data;
1897     peripheral->gatt_client_state = P_W2_PREPARE_WRITE;
1898     gatt_client_run();
1899     return 0;
1900 }
1901 
1902 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){
1903     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
1904 }
1905 
1906 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){
1907     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1908 
1909     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1910     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1911 
1912     peripheral->callback = callback;
1913     peripheral->attribute_handle = value_handle;
1914     peripheral->attribute_length = value_length;
1915     peripheral->attribute_offset = 0;
1916     peripheral->attribute_value = value;
1917     peripheral->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1918     gatt_client_run();
1919     return 0;
1920 }
1921 
1922 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){
1923     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1924 
1925     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1926     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1927 
1928     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
1929         (characteristic->properties & ATT_PROPERTY_NOTIFY) == 0) {
1930         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
1931         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
1932     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
1933                (characteristic->properties & ATT_PROPERTY_INDICATE) == 0){
1934         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
1935         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
1936     }
1937 
1938     peripheral->callback = callback;
1939     peripheral->start_group_handle = characteristic->value_handle;
1940     peripheral->end_group_handle = characteristic->end_handle;
1941     little_endian_store_16(peripheral->client_characteristic_configuration_value, 0, configuration);
1942 
1943 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1944     peripheral->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1945 #else
1946     peripheral->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1947 #endif
1948     gatt_client_run();
1949     return 0;
1950 }
1951 
1952 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){
1953     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1954 
1955     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1956     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1957 
1958     peripheral->callback = callback;
1959     peripheral->attribute_handle = descriptor_handle;
1960 
1961     peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1962     gatt_client_run();
1963     return 0;
1964 }
1965 
1966 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
1967     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
1968 }
1969 
1970 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){
1971     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1972 
1973     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1974     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1975 
1976     peripheral->callback = callback;
1977     peripheral->attribute_handle = descriptor_handle;
1978     peripheral->attribute_offset = offset;
1979     peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1980     gatt_client_run();
1981     return 0;
1982 }
1983 
1984 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){
1985     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
1986 }
1987 
1988 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){
1989     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
1990 }
1991 
1992 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){
1993     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1994 
1995     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1996     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1997 
1998     peripheral->callback = callback;
1999     peripheral->attribute_handle = descriptor_handle;
2000     peripheral->attribute_length = length;
2001     peripheral->attribute_offset = 0;
2002     peripheral->attribute_value = data;
2003     peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2004     gatt_client_run();
2005     return 0;
2006 }
2007 
2008 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){
2009     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, length, value);
2010 }
2011 
2012 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){
2013     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2014 
2015     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
2016     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
2017 
2018     peripheral->callback = callback;
2019     peripheral->attribute_handle = descriptor_handle;
2020     peripheral->attribute_length = length;
2021     peripheral->attribute_offset = offset;
2022     peripheral->attribute_value = data;
2023     peripheral->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2024     gatt_client_run();
2025     return 0;
2026 }
2027 
2028 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){
2029     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, length, data );
2030 }
2031 
2032 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){
2033     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, length, value);
2034 }
2035 
2036 /**
2037  * @brief -> gatt complete event
2038  */
2039 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){
2040     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2041 
2042     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
2043     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
2044 
2045     peripheral->callback = callback;
2046     peripheral->attribute_handle = attribute_handle;
2047     peripheral->attribute_length = length;
2048     peripheral->attribute_offset = offset;
2049     peripheral->attribute_value = data;
2050     peripheral->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
2051     gatt_client_run();
2052     return 0;
2053 }
2054 
2055 /**
2056  * @brief -> gatt complete event
2057  */
2058 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2059     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2060 
2061     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
2062     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
2063 
2064     peripheral->callback = callback;
2065     peripheral->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
2066     gatt_client_run();
2067     return 0;
2068 }
2069 
2070 /**
2071  * @brief -> gatt complete event
2072  */
2073 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2074     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2075 
2076     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
2077     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
2078 
2079     peripheral->callback = callback;
2080     peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
2081     gatt_client_run();
2082     return 0;
2083 }
2084 
2085 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t *service){
2086     service->start_group_handle = little_endian_read_16(packet, offset);
2087     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2088     reverse_128(&packet[offset + 4], service->uuid128);
2089     if (uuid_has_bluetooth_prefix(service->uuid128)){
2090         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2091     }
2092 }
2093 
2094 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2095     characteristic->start_handle = little_endian_read_16(packet, offset);
2096     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2097     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2098     characteristic->properties = little_endian_read_16(packet, offset + 6);
2099     reverse_128(&packet[offset+8], characteristic->uuid128);
2100     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2101         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2102     }
2103 }
2104 
2105 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2106     descriptor->handle = little_endian_read_16(packet, offset);
2107     reverse_128(&packet[offset+2], descriptor->uuid128);
2108     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2109         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2110     }
2111 }
2112 
2113 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2114     gatt_client_t * context = provide_context_for_conn_handle(con_handle);
2115     if (!context) return;
2116     if (context->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2117         context->callback = callback;
2118         context->mtu_state = SEND_MTU_EXCHANGE;
2119         gatt_client_run();
2120     }
2121 }
2122 
2123 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2124     gatt_client_t * context = provide_context_for_conn_handle(con_handle);
2125     if (!context) return BTSTACK_MEMORY_ALLOC_FAILED;
2126     if (context->write_without_response_callback) return GATT_CLIENT_IN_WRONG_STATE;
2127     context->write_without_response_callback = callback;
2128     att_dispatch_client_request_can_send_now_event(context->con_handle);
2129     return 0;
2130 }
2131