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