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