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