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