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