xref: /btstack/src/ble/gatt_client.c (revision ae1d1237377ceeda35e3b9dbaa74700c74a44881)
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 inline 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 inline 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 inline 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 inline 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 inline 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 inline 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 inline 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 inline 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     switch (peripheral->mtu_state) {
826         case SEND_MTU_EXCHANGE:
827             peripheral->mtu_state = SENT_MTU_EXCHANGE;
828             att_exchange_mtu_request(peripheral->con_handle);
829             return 1;
830         case SENT_MTU_EXCHANGE:
831             return 0;
832         default:
833             break;
834     }
835 
836     if (peripheral->send_confirmation){
837         peripheral->send_confirmation = 0;
838         att_confirmation(peripheral->con_handle);
839         return 1;
840     }
841 
842     // check MTU for writes
843     switch (peripheral->gatt_client_state){
844         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
845         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
846             if (peripheral->attribute_length <= peripheral_mtu(peripheral) - 3) break;
847             log_error("gatt_client_run: value len %u > MTU %u - 3\n", peripheral->attribute_length, peripheral_mtu(peripheral));
848             gatt_client_handle_transaction_complete(peripheral);
849             emit_gatt_complete_event(peripheral, ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH);
850             return 0;
851         default:
852             break;
853     }
854 
855     // log_info("gatt_client_state %u", peripheral->gatt_client_state);
856     switch (peripheral->gatt_client_state){
857         case P_W2_SEND_SERVICE_QUERY:
858             peripheral->gatt_client_state = P_W4_SERVICE_QUERY_RESULT;
859             send_gatt_services_request(peripheral);
860             return 1;
861 
862         case P_W2_SEND_SERVICE_WITH_UUID_QUERY:
863             peripheral->gatt_client_state = P_W4_SERVICE_WITH_UUID_RESULT;
864             send_gatt_services_by_uuid_request(peripheral);
865             return 1;
866 
867         case P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY:
868             peripheral->gatt_client_state = P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT;
869             send_gatt_characteristic_request(peripheral);
870             return 1;
871 
872         case P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY:
873             peripheral->gatt_client_state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
874             send_gatt_characteristic_request(peripheral);
875             return 1;
876 
877         case P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY:
878             peripheral->gatt_client_state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
879             send_gatt_characteristic_descriptor_request(peripheral);
880             return 1;
881 
882         case P_W2_SEND_INCLUDED_SERVICE_QUERY:
883             peripheral->gatt_client_state = P_W4_INCLUDED_SERVICE_QUERY_RESULT;
884             send_gatt_included_service_request(peripheral);
885             return 1;
886 
887         case P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY:
888             peripheral->gatt_client_state = P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT;
889             send_gatt_included_service_uuid_request(peripheral);
890             return 1;
891 
892         case P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY:
893             peripheral->gatt_client_state = P_W4_READ_CHARACTERISTIC_VALUE_RESULT;
894             send_gatt_read_characteristic_value_request(peripheral);
895             return 1;
896 
897         case P_W2_SEND_READ_BLOB_QUERY:
898             peripheral->gatt_client_state = P_W4_READ_BLOB_RESULT;
899             send_gatt_read_blob_request(peripheral);
900             return 1;
901 
902         case P_W2_SEND_READ_BY_TYPE_REQUEST:
903             peripheral->gatt_client_state = P_W4_READ_BY_TYPE_RESPONSE;
904             send_gatt_read_by_type_request(peripheral);
905             return 1;
906 
907         case P_W2_SEND_READ_MULTIPLE_REQUEST:
908             peripheral->gatt_client_state = P_W4_READ_MULTIPLE_RESPONSE;
909             send_gatt_read_multiple_request(peripheral);
910             return 1;
911 
912         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
913             peripheral->gatt_client_state = P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT;
914             send_gatt_write_attribute_value_request(peripheral);
915             return 1;
916 
917         case P_W2_PREPARE_WRITE:
918             peripheral->gatt_client_state = P_W4_PREPARE_WRITE_RESULT;
919             send_gatt_prepare_write_request(peripheral);
920             return 1;
921 
922         case P_W2_PREPARE_WRITE_SINGLE:
923             peripheral->gatt_client_state = P_W4_PREPARE_WRITE_SINGLE_RESULT;
924             send_gatt_prepare_write_request(peripheral);
925             return 1;
926 
927         case P_W2_PREPARE_RELIABLE_WRITE:
928             peripheral->gatt_client_state = P_W4_PREPARE_RELIABLE_WRITE_RESULT;
929             send_gatt_prepare_write_request(peripheral);
930             return 1;
931 
932         case P_W2_EXECUTE_PREPARED_WRITE:
933             peripheral->gatt_client_state = P_W4_EXECUTE_PREPARED_WRITE_RESULT;
934             send_gatt_execute_write_request(peripheral);
935             return 1;
936 
937         case P_W2_CANCEL_PREPARED_WRITE:
938             peripheral->gatt_client_state = P_W4_CANCEL_PREPARED_WRITE_RESULT;
939             send_gatt_cancel_prepared_write_request(peripheral);
940             return 1;
941 
942         case P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH:
943             peripheral->gatt_client_state = P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT;
944             send_gatt_cancel_prepared_write_request(peripheral);
945             return 1;
946 
947         case P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
948             peripheral->gatt_client_state = P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
949             send_gatt_read_client_characteristic_configuration_request(peripheral);
950             return 1;
951 
952         case P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY:
953             peripheral->gatt_client_state = P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT;
954             send_gatt_read_characteristic_descriptor_request(peripheral);
955             return 1;
956 
957         case P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY:
958             peripheral->gatt_client_state = P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT;
959             send_gatt_read_blob_request(peripheral);
960             return 1;
961 
962         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
963             peripheral->gatt_client_state = P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
964             send_gatt_write_attribute_value_request(peripheral);
965             return 1;
966 
967         case P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:
968             peripheral->gatt_client_state = P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT;
969             send_gatt_write_client_characteristic_configuration_request(peripheral);
970             return 1;
971 
972         case P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR:
973             peripheral->gatt_client_state = P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
974             send_gatt_prepare_write_request(peripheral);
975             return 1;
976 
977         case P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR:
978             peripheral->gatt_client_state = P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
979             send_gatt_execute_write_request(peripheral);
980             return 1;
981 
982 #ifdef ENABLE_LE_SIGNED_WRITE
983         case P_W4_CMAC_READY:
984             if (sm_cmac_ready()){
985                 sm_key_t csrk;
986                 le_device_db_local_csrk_get(peripheral->le_device_index, csrk);
987                 uint32_t sign_counter = le_device_db_local_counter_get(peripheral->le_device_index);
988                 peripheral->gatt_client_state = P_W4_CMAC_RESULT;
989                 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);
990             }
991             return 0;
992 
993         case P_W2_SEND_SIGNED_WRITE: {
994             peripheral->gatt_client_state = P_W4_SEND_SINGED_WRITE_DONE;
995             // bump local signing counter
996             uint32_t sign_counter = le_device_db_local_counter_get(peripheral->le_device_index);
997             le_device_db_local_counter_set(peripheral->le_device_index, sign_counter + 1);
998 
999             send_gatt_signed_write_request(peripheral, sign_counter);
1000             peripheral->gatt_client_state = P_READY;
1001             // finally, notifiy client that write is complete
1002             gatt_client_handle_transaction_complete(peripheral);
1003             return 1;
1004         }
1005 #endif
1006         default:
1007             break;
1008     }
1009 
1010     // requested can send snow?
1011     if (peripheral->write_without_response_callback){
1012         btstack_packet_handler_t packet_handler = peripheral->write_without_response_callback;
1013         peripheral->write_without_response_callback = NULL;
1014         uint8_t event[4];
1015         event[0] = GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE;
1016         event[1] = sizeof(event) - 2;
1017         little_endian_store_16(event, 2, peripheral->con_handle);
1018         packet_handler(HCI_EVENT_PACKET, peripheral->con_handle, event, sizeof(event));
1019         return 1; // to trigger requeueing (even if higher layer didn't sent)
1020     }
1021 
1022     return 0;
1023 }
1024 
1025 static void gatt_client_run(void){
1026     btstack_linked_item_t *it;
1027     for (it = (btstack_linked_item_t *) gatt_client_connections; it ; it = it->next){
1028         gatt_client_t * peripheral = (gatt_client_t *) it;
1029         if (!att_dispatch_client_can_send_now(peripheral->con_handle)) {
1030             att_dispatch_client_request_can_send_now_event(peripheral->con_handle);
1031             return;
1032         }
1033         int packet_sent = gatt_client_run_for_peripheral(peripheral);
1034         if (packet_sent){
1035             // request new permission
1036             att_dispatch_client_request_can_send_now_event(peripheral->con_handle);
1037             // requeue client for fairness and exit
1038             // note: iterator has become invalid
1039             btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) peripheral);
1040             btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) peripheral);
1041             return;
1042         }
1043     }
1044 }
1045 
1046 static void gatt_client_report_error_if_pending(gatt_client_t *peripheral, uint8_t error_code) {
1047     if (is_ready(peripheral)) return;
1048     gatt_client_handle_transaction_complete(peripheral);
1049     emit_gatt_complete_event(peripheral, error_code);
1050 }
1051 
1052 static void gatt_client_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1053     UNUSED(channel);    // ok: handling own l2cap events
1054     UNUSED(size);       // ok: there is no channel
1055 
1056     if (packet_type != HCI_EVENT_PACKET) return;
1057 
1058     switch (hci_event_packet_get_type(packet)) {
1059         case HCI_EVENT_DISCONNECTION_COMPLETE:
1060         {
1061             log_info("GATT Client: HCI_EVENT_DISCONNECTION_COMPLETE");
1062             hci_con_handle_t con_handle = little_endian_read_16(packet,3);
1063             gatt_client_t * peripheral = get_gatt_client_context_for_handle(con_handle);
1064             if (!peripheral) break;
1065             gatt_client_report_error_if_pending(peripheral, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1066 
1067             btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) peripheral);
1068             btstack_memory_gatt_client_free(peripheral);
1069             break;
1070         }
1071         default:
1072             break;
1073     }
1074 
1075     gatt_client_run();
1076 }
1077 
1078 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
1079 
1080     if (packet_type == HCI_EVENT_PACKET && packet[0] == L2CAP_EVENT_CAN_SEND_NOW){
1081         gatt_client_run();
1082     }
1083 
1084     if (packet_type != ATT_DATA_PACKET) return;
1085 
1086     // special cases: notifications don't need a context while indications motivate creating one
1087     gatt_client_t * peripheral;
1088     switch (packet[0]){
1089         case ATT_HANDLE_VALUE_NOTIFICATION:
1090             report_gatt_notification(handle, little_endian_read_16(packet,1), &packet[3], size-3);
1091             return;
1092         case ATT_HANDLE_VALUE_INDICATION:
1093             peripheral = provide_context_for_conn_handle(handle);
1094             break;
1095         default:
1096             peripheral = get_gatt_client_context_for_handle(handle);
1097             break;
1098     }
1099 
1100     if (!peripheral) return;
1101 
1102     switch (packet[0]){
1103         // att_server has negotiated the mtu for this connection
1104         case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
1105         {
1106             peripheral->mtu = little_endian_read_16(packet, 4);
1107             break;
1108         }
1109         case ATT_EXCHANGE_MTU_RESPONSE:
1110         {
1111             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1112             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1113             peripheral->mtu = remote_rx_mtu < local_rx_mtu ? remote_rx_mtu : local_rx_mtu;
1114             peripheral->mtu_state = MTU_EXCHANGED;
1115             emit_gatt_mtu_exchanged_result_event(peripheral, peripheral->mtu);
1116             break;
1117         }
1118         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
1119             switch(peripheral->gatt_client_state){
1120                 case P_W4_SERVICE_QUERY_RESULT:
1121                     report_gatt_services(peripheral, packet, size);
1122                     trigger_next_service_query(peripheral, get_last_result_handle_from_service_list(packet, size));
1123                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1124                     break;
1125                 default:
1126                     break;
1127             }
1128             break;
1129         case ATT_HANDLE_VALUE_INDICATION:
1130             report_gatt_indication(handle, little_endian_read_16(packet,1), &packet[3], size-3);
1131             peripheral->send_confirmation = 1;
1132             break;
1133 
1134         case ATT_READ_BY_TYPE_RESPONSE:
1135             switch (peripheral->gatt_client_state){
1136                 case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1137                     report_gatt_characteristics(peripheral, packet, size);
1138                     trigger_next_characteristic_query(peripheral, get_last_result_handle_from_characteristics_list(packet, size));
1139                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1140                     break;
1141                 case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1142                     report_gatt_characteristics(peripheral, packet, size);
1143                     trigger_next_characteristic_query(peripheral, get_last_result_handle_from_characteristics_list(packet, size));
1144                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1145                     break;
1146                 case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1147                 {
1148                     uint16_t uuid16 = 0;
1149                     uint16_t pair_size = packet[1];
1150 
1151                     if (pair_size < 7){
1152                         // UUIDs not available, query first included service
1153                         peripheral->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1154                         peripheral->query_start_handle = little_endian_read_16(packet, 4);
1155                         peripheral->query_end_handle = little_endian_read_16(packet,6);
1156                         peripheral->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1157                         break;
1158                     }
1159 
1160                     uint16_t offset;
1161                     for (offset = 2; offset < size; offset += pair_size){
1162                         uint16_t include_handle = little_endian_read_16(packet, offset);
1163                         peripheral->query_start_handle = little_endian_read_16(packet,offset+2);
1164                         peripheral->query_end_handle = little_endian_read_16(packet,offset+4);
1165                         uuid16 = little_endian_read_16(packet, offset+6);
1166                         report_gatt_included_service_uuid16(peripheral, include_handle, uuid16);
1167                     }
1168 
1169                     trigger_next_included_service_query(peripheral, get_last_result_handle_from_included_services_list(packet, size));
1170                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1171                     break;
1172                 }
1173                 case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1174                     peripheral->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1175                     peripheral->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1176                     break;
1177                 case P_W4_READ_BY_TYPE_RESPONSE: {
1178                     uint16_t pair_size = packet[1];
1179                     uint16_t offset;
1180                     uint16_t last_result_handle = 0;
1181                     for (offset = 2; offset < size ; offset += pair_size){
1182                         uint16_t value_handle = little_endian_read_16(packet, offset);
1183                         report_gatt_characteristic_value(peripheral, value_handle, &packet[offset+2], pair_size-2);
1184                         last_result_handle = value_handle;
1185                     }
1186                     trigger_next_read_by_type_query(peripheral, last_result_handle);
1187                     break;
1188                 }
1189                 default:
1190                     break;
1191             }
1192             break;
1193         case ATT_READ_RESPONSE:
1194             switch (peripheral->gatt_client_state){
1195                 case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT: {
1196                     uint8_t uuid128[16];
1197                     reverse_128(&packet[1], uuid128);
1198                     report_gatt_included_service_uuid128(peripheral, peripheral->start_group_handle, uuid128);
1199                     trigger_next_included_service_query(peripheral, peripheral->start_group_handle);
1200                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1201                     break;
1202                 }
1203                 case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1204                     gatt_client_handle_transaction_complete(peripheral);
1205                     report_gatt_characteristic_value(peripheral, peripheral->attribute_handle, &packet[1], size-1);
1206                     emit_gatt_complete_event(peripheral, 0);
1207                     break;
1208 
1209                 case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1210                     gatt_client_handle_transaction_complete(peripheral);
1211                     report_gatt_characteristic_descriptor(peripheral, peripheral->attribute_handle, &packet[1], size-1, 0);
1212                     emit_gatt_complete_event(peripheral, 0);
1213                     break;
1214                 }
1215                 default:
1216                     break;
1217             }
1218             break;
1219 
1220         case ATT_FIND_BY_TYPE_VALUE_RESPONSE:
1221         {
1222             uint8_t pair_size = 4;
1223             int i;
1224             uint16_t start_group_handle;
1225             uint16_t   end_group_handle= 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
1226             for (i = 1; i<size; i+=pair_size){
1227                 start_group_handle = little_endian_read_16(packet,i);
1228                 end_group_handle = little_endian_read_16(packet,i+2);
1229                 emit_gatt_service_query_result_event(peripheral, start_group_handle, end_group_handle, peripheral->uuid128);
1230             }
1231             trigger_next_service_by_uuid_query(peripheral, end_group_handle);
1232             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1233             break;
1234         }
1235         case ATT_FIND_INFORMATION_REPLY:
1236         {
1237             uint8_t pair_size = 4;
1238             if (packet[1] == 2){
1239                 pair_size = 18;
1240             }
1241             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
1242             report_gatt_all_characteristic_descriptors(peripheral, &packet[2], size-2, pair_size);
1243             trigger_next_characteristic_descriptor_query(peripheral, last_descriptor_handle);
1244             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1245             break;
1246         }
1247 
1248         case ATT_WRITE_RESPONSE:
1249             switch (peripheral->gatt_client_state){
1250                 case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1251                     gatt_client_handle_transaction_complete(peripheral);
1252                     emit_gatt_complete_event(peripheral, 0);
1253                     break;
1254                 case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1255                     gatt_client_handle_transaction_complete(peripheral);
1256                     emit_gatt_complete_event(peripheral, 0);
1257                     break;
1258                 case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1259                     gatt_client_handle_transaction_complete(peripheral);
1260                     emit_gatt_complete_event(peripheral, 0);
1261                     break;
1262                 default:
1263                     break;
1264             }
1265             break;
1266 
1267         case ATT_READ_BLOB_RESPONSE:{
1268             uint16_t received_blob_length = size-1;
1269             switch(peripheral->gatt_client_state){
1270                 case P_W4_READ_BLOB_RESULT:
1271                     report_gatt_long_characteristic_value_blob(peripheral, peripheral->attribute_handle, &packet[1], received_blob_length, peripheral->attribute_offset);
1272                     trigger_next_blob_query(peripheral, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
1273                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1274                     break;
1275                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1276                     report_gatt_long_characteristic_descriptor(peripheral, peripheral->attribute_handle,
1277                                                           &packet[1], received_blob_length,
1278                                                           peripheral->attribute_offset);
1279                     trigger_next_blob_query(peripheral, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY, received_blob_length);
1280                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1281                     break;
1282                 default:
1283                     break;
1284             }
1285             break;
1286         }
1287         case ATT_PREPARE_WRITE_RESPONSE:
1288             switch (peripheral->gatt_client_state){
1289                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1290                     gatt_client_handle_transaction_complete(peripheral);
1291                     if (is_value_valid(peripheral, packet, size)){
1292                         emit_gatt_complete_event(peripheral, 0);
1293                     } else {
1294                         emit_gatt_complete_event(peripheral, ATT_ERROR_DATA_MISMATCH);
1295                     }
1296                     break;
1297 
1298                 case P_W4_PREPARE_WRITE_RESULT:{
1299                     peripheral->attribute_offset = little_endian_read_16(packet, 3);
1300                     trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1301                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1302                     break;
1303                 }
1304                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1305                     peripheral->attribute_offset = little_endian_read_16(packet, 3);
1306                     trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR, P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1307                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1308                     break;
1309                 }
1310                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT:{
1311                     if (is_value_valid(peripheral, packet, size)){
1312                         peripheral->attribute_offset = little_endian_read_16(packet, 3);
1313                         trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_RELIABLE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1314                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1315                         break;
1316                     }
1317                     peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1318                     break;
1319                 }
1320                 default:
1321                     break;
1322             }
1323             break;
1324 
1325         case ATT_EXECUTE_WRITE_RESPONSE:
1326             switch (peripheral->gatt_client_state){
1327                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1328                     gatt_client_handle_transaction_complete(peripheral);
1329                     emit_gatt_complete_event(peripheral, 0);
1330                     break;
1331                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1332                     gatt_client_handle_transaction_complete(peripheral);
1333                     emit_gatt_complete_event(peripheral, 0);
1334                     break;
1335                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1336                     gatt_client_handle_transaction_complete(peripheral);
1337                     emit_gatt_complete_event(peripheral, ATT_ERROR_DATA_MISMATCH);
1338                     break;
1339                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1340                     gatt_client_handle_transaction_complete(peripheral);
1341                     emit_gatt_complete_event(peripheral, 0);
1342                     break;
1343                 default:
1344                     break;
1345 
1346             }
1347             break;
1348 
1349         case ATT_READ_MULTIPLE_RESPONSE:
1350             switch(peripheral->gatt_client_state){
1351                 case P_W4_READ_MULTIPLE_RESPONSE:
1352                     report_gatt_characteristic_value(peripheral, 0, &packet[1], size-1);
1353                     gatt_client_handle_transaction_complete(peripheral);
1354                     emit_gatt_complete_event(peripheral, 0);
1355                     break;
1356                 default:
1357                     break;
1358             }
1359             break;
1360 
1361         case ATT_ERROR_RESPONSE:
1362 
1363             switch (packet[4]){
1364                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1365                     switch(peripheral->gatt_client_state){
1366                         case P_W4_SERVICE_QUERY_RESULT:
1367                         case P_W4_SERVICE_WITH_UUID_RESULT:
1368                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1369                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1370                             gatt_client_handle_transaction_complete(peripheral);
1371                             emit_gatt_complete_event(peripheral, 0);
1372                             break;
1373                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1374                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1375                             characteristic_end_found(peripheral, peripheral->end_group_handle);
1376                             gatt_client_handle_transaction_complete(peripheral);
1377                             emit_gatt_complete_event(peripheral, 0);
1378                             break;
1379                         case P_W4_READ_BY_TYPE_RESPONSE:
1380                             gatt_client_handle_transaction_complete(peripheral);
1381                             if (peripheral->start_group_handle == peripheral->query_start_handle){
1382                                 emit_gatt_complete_event(peripheral, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
1383                             } else {
1384                                 emit_gatt_complete_event(peripheral, 0);
1385                             }
1386                             break;
1387                         default:
1388                             gatt_client_report_error_if_pending(peripheral, packet[4]);
1389                             break;
1390                     }
1391                     break;
1392                 }
1393                 default:
1394                     gatt_client_report_error_if_pending(peripheral, packet[4]);
1395                     break;
1396             }
1397             break;
1398 
1399         default:
1400             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
1401             break;
1402     }
1403     gatt_client_run();
1404 }
1405 
1406 #ifdef ENABLE_LE_SIGNED_WRITE
1407 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
1408     btstack_linked_list_iterator_t it;
1409     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
1410     while (btstack_linked_list_iterator_has_next(&it)){
1411         gatt_client_t * peripheral = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
1412         if (peripheral->gatt_client_state == P_W4_CMAC_RESULT){
1413             // store result
1414             memcpy(peripheral->cmac, hash, 8);
1415             // reverse_64(hash, peripheral->cmac);
1416             peripheral->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1417             gatt_client_run();
1418             return;
1419         }
1420     }
1421 }
1422 
1423 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){
1424     gatt_client_t * peripheral = provide_context_for_conn_handle(con_handle);
1425     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1426     peripheral->le_device_index = sm_le_device_index(con_handle);
1427     if (peripheral->le_device_index < 0) return GATT_CLIENT_IN_WRONG_STATE; // device lookup not done / no stored bonding information
1428 
1429     peripheral->callback = callback;
1430     peripheral->attribute_handle = handle;
1431     peripheral->attribute_length = message_len;
1432     peripheral->attribute_value = message;
1433     peripheral->gatt_client_state = P_W4_CMAC_READY;
1434 
1435     gatt_client_run();
1436     return 0;
1437 }
1438 #endif
1439 
1440 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1441     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1442     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1443     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1444 
1445     peripheral->callback = callback;
1446     peripheral->start_group_handle = 0x0001;
1447     peripheral->end_group_handle   = 0xffff;
1448     peripheral->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
1449     peripheral->uuid16 = 0;
1450     gatt_client_run();
1451     return 0;
1452 }
1453 
1454 
1455 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
1456     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1457 
1458     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1459     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1460 
1461     peripheral->callback = callback;
1462     peripheral->start_group_handle = 0x0001;
1463     peripheral->end_group_handle   = 0xffff;
1464     peripheral->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1465     peripheral->uuid16 = uuid16;
1466     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), peripheral->uuid16);
1467     gatt_client_run();
1468     return 0;
1469 }
1470 
1471 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
1472     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1473 
1474     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1475     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1476 
1477     peripheral->callback = callback;
1478     peripheral->start_group_handle = 0x0001;
1479     peripheral->end_group_handle   = 0xffff;
1480     peripheral->uuid16 = 0;
1481     memcpy(peripheral->uuid128, uuid128, 16);
1482     peripheral->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1483     gatt_client_run();
1484     return 0;
1485 }
1486 
1487 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t *service){
1488     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1489 
1490     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1491     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1492 
1493     peripheral->callback = callback;
1494     peripheral->start_group_handle = service->start_group_handle;
1495     peripheral->end_group_handle   = service->end_group_handle;
1496     peripheral->filter_with_uuid = 0;
1497     peripheral->characteristic_start_handle = 0;
1498     peripheral->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
1499     gatt_client_run();
1500     return 0;
1501 }
1502 
1503 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){
1504     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1505 
1506     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1507     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1508 
1509     peripheral->callback = callback;
1510     peripheral->start_group_handle = service->start_group_handle;
1511     peripheral->end_group_handle   = service->end_group_handle;
1512     peripheral->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
1513 
1514     gatt_client_run();
1515     return 0;
1516 }
1517 
1518 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){
1519     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1520 
1521     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1522     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1523 
1524     peripheral->callback = callback;
1525     peripheral->start_group_handle = start_handle;
1526     peripheral->end_group_handle   = end_handle;
1527     peripheral->filter_with_uuid = 1;
1528     peripheral->uuid16 = uuid16;
1529     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), uuid16);
1530     peripheral->characteristic_start_handle = 0;
1531     peripheral->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
1532 
1533     gatt_client_run();
1534     return 0;
1535 }
1536 
1537 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){
1538     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1539 
1540     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1541     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1542 
1543     peripheral->callback = callback;
1544     peripheral->start_group_handle = start_handle;
1545     peripheral->end_group_handle   = end_handle;
1546     peripheral->filter_with_uuid = 1;
1547     peripheral->uuid16 = 0;
1548     memcpy(peripheral->uuid128, uuid128, 16);
1549     peripheral->characteristic_start_handle = 0;
1550     peripheral->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
1551 
1552     gatt_client_run();
1553     return 0;
1554 }
1555 
1556 
1557 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){
1558     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, handle, service->start_group_handle, service->end_group_handle, uuid16);
1559 }
1560 
1561 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){
1562     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, handle, service->start_group_handle, service->end_group_handle, uuid128);
1563 }
1564 
1565 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t *characteristic){
1566     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1567 
1568     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1569     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1570 
1571     if (characteristic->value_handle == characteristic->end_handle){
1572         emit_gatt_complete_event(peripheral, 0);
1573         return 0;
1574     }
1575     peripheral->callback = callback;
1576     peripheral->start_group_handle = characteristic->value_handle + 1;
1577     peripheral->end_group_handle   = characteristic->end_handle;
1578     peripheral->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
1579 
1580     gatt_client_run();
1581     return 0;
1582 }
1583 
1584 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){
1585     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1586 
1587     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1588     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1589 
1590     peripheral->callback = callback;
1591     peripheral->attribute_handle = value_handle;
1592     peripheral->attribute_offset = 0;
1593     peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
1594     gatt_client_run();
1595     return 0;
1596 }
1597 
1598 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){
1599     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1600 
1601     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1602     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1603 
1604     peripheral->callback = callback;
1605     peripheral->start_group_handle = start_handle;
1606     peripheral->end_group_handle = end_handle;
1607     peripheral->query_start_handle = start_handle;
1608     peripheral->query_end_handle = end_handle;
1609     peripheral->uuid16 = uuid16;
1610     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), uuid16);
1611     peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1612     gatt_client_run();
1613     return 0;
1614 }
1615 
1616 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){
1617     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1618 
1619     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1620     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1621 
1622     peripheral->callback = callback;
1623     peripheral->start_group_handle = start_handle;
1624     peripheral->end_group_handle = end_handle;
1625     peripheral->query_start_handle = start_handle;
1626     peripheral->query_end_handle = end_handle;
1627     peripheral->uuid16 = 0;
1628     memcpy(peripheral->uuid128, uuid128, 16);
1629     peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1630     gatt_client_run();
1631     return 0;
1632 }
1633 
1634 
1635 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, uint16_t handle, gatt_client_characteristic_t *characteristic){
1636     return gatt_client_read_value_of_characteristic_using_value_handle(callback, handle, characteristic->value_handle);
1637 }
1638 
1639 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){
1640     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1641 
1642     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1643     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1644 
1645     peripheral->callback = callback;
1646     peripheral->attribute_handle = characteristic_value_handle;
1647     peripheral->attribute_offset = offset;
1648     peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1649     gatt_client_run();
1650     return 0;
1651 }
1652 
1653 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){
1654     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, characteristic_value_handle, 0);
1655 }
1656 
1657 uint8_t gatt_client_read_long_value_of_characteristic(btstack_packet_handler_t callback, uint16_t handle, gatt_client_characteristic_t *characteristic){
1658     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, handle, characteristic->value_handle);
1659 }
1660 
1661 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){
1662     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1663 
1664     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1665     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1666 
1667     peripheral->callback = callback;
1668     peripheral->read_multiple_handle_count = num_value_handles;
1669     peripheral->read_multiple_handles = value_handles;
1670     peripheral->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1671     gatt_client_run();
1672     return 0;
1673 }
1674 
1675 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){
1676     gatt_client_t * peripheral = provide_context_for_conn_handle(con_handle);
1677 
1678     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1679     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1680 
1681     if (value_length > peripheral_mtu(peripheral) - 3) return GATT_CLIENT_VALUE_TOO_LONG;
1682     if (!att_dispatch_client_can_send_now(peripheral->con_handle)) return GATT_CLIENT_BUSY;
1683 
1684     att_write_request(ATT_WRITE_COMMAND, peripheral->con_handle, value_handle, value_length, value);
1685     return 0;
1686 }
1687 
1688 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){
1689     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1690 
1691     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1692     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1693 
1694     peripheral->callback = callback;
1695     peripheral->attribute_handle = value_handle;
1696     peripheral->attribute_length = value_length;
1697     peripheral->attribute_value = data;
1698     peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1699     gatt_client_run();
1700     return 0;
1701 }
1702 
1703 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){
1704     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1705 
1706     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1707     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1708 
1709     peripheral->callback = callback;
1710     peripheral->attribute_handle = value_handle;
1711     peripheral->attribute_length = value_length;
1712     peripheral->attribute_offset = offset;
1713     peripheral->attribute_value = data;
1714     peripheral->gatt_client_state = P_W2_PREPARE_WRITE;
1715     gatt_client_run();
1716     return 0;
1717 }
1718 
1719 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){
1720     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
1721 }
1722 
1723 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){
1724     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1725 
1726     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1727     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1728 
1729     peripheral->callback = callback;
1730     peripheral->attribute_handle = value_handle;
1731     peripheral->attribute_length = value_length;
1732     peripheral->attribute_offset = 0;
1733     peripheral->attribute_value = value;
1734     peripheral->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1735     gatt_client_run();
1736     return 0;
1737 }
1738 
1739 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){
1740     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1741 
1742     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1743     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1744 
1745     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
1746         (characteristic->properties & ATT_PROPERTY_NOTIFY) == 0) {
1747         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
1748         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
1749     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
1750                (characteristic->properties & ATT_PROPERTY_INDICATE) == 0){
1751         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
1752         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
1753     }
1754 
1755     peripheral->callback = callback;
1756     peripheral->start_group_handle = characteristic->value_handle;
1757     peripheral->end_group_handle = characteristic->end_handle;
1758     little_endian_store_16(peripheral->client_characteristic_configuration_value, 0, configuration);
1759 
1760     peripheral->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1761     gatt_client_run();
1762     return 0;
1763 }
1764 
1765 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){
1766     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1767 
1768     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1769     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1770 
1771     peripheral->callback = callback;
1772     peripheral->attribute_handle = descriptor_handle;
1773 
1774     peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1775     gatt_client_run();
1776     return 0;
1777 }
1778 
1779 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
1780     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
1781 }
1782 
1783 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){
1784     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1785 
1786     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1787     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1788 
1789     peripheral->callback = callback;
1790     peripheral->attribute_handle = descriptor_handle;
1791     peripheral->attribute_offset = offset;
1792     peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1793     gatt_client_run();
1794     return 0;
1795 }
1796 
1797 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){
1798     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
1799 }
1800 
1801 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){
1802     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
1803 }
1804 
1805 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){
1806     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1807 
1808     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1809     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1810 
1811     peripheral->callback = callback;
1812     peripheral->attribute_handle = descriptor_handle;
1813     peripheral->attribute_length = length;
1814     peripheral->attribute_offset = 0;
1815     peripheral->attribute_value = data;
1816     peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
1817     gatt_client_run();
1818     return 0;
1819 }
1820 
1821 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){
1822     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, length, value);
1823 }
1824 
1825 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){
1826     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1827 
1828     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1829     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1830 
1831     peripheral->callback = callback;
1832     peripheral->attribute_handle = descriptor_handle;
1833     peripheral->attribute_length = length;
1834     peripheral->attribute_offset = offset;
1835     peripheral->attribute_value = data;
1836     peripheral->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
1837     gatt_client_run();
1838     return 0;
1839 }
1840 
1841 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){
1842     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, length, data );
1843 }
1844 
1845 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){
1846     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, length, value);
1847 }
1848 
1849 /**
1850  * @brief -> gatt complete event
1851  */
1852 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){
1853     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1854 
1855     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1856     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1857 
1858     peripheral->callback = callback;
1859     peripheral->attribute_handle = attribute_handle;
1860     peripheral->attribute_length = length;
1861     peripheral->attribute_offset = offset;
1862     peripheral->attribute_value = data;
1863     peripheral->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
1864     gatt_client_run();
1865     return 0;
1866 }
1867 
1868 /**
1869  * @brief -> gatt complete event
1870  */
1871 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1872     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1873 
1874     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1875     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1876 
1877     peripheral->callback = callback;
1878     peripheral->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
1879     gatt_client_run();
1880     return 0;
1881 }
1882 
1883 /**
1884  * @brief -> gatt complete event
1885  */
1886 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1887     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1888 
1889     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1890     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1891 
1892     peripheral->callback = callback;
1893     peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
1894     gatt_client_run();
1895     return 0;
1896 }
1897 
1898 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t *service){
1899     service->start_group_handle = little_endian_read_16(packet, offset);
1900     service->end_group_handle = little_endian_read_16(packet, offset + 2);
1901     reverse_128(&packet[offset + 4], service->uuid128);
1902     if (uuid_has_bluetooth_prefix(service->uuid128)){
1903         service->uuid16 = big_endian_read_32(service->uuid128, 0);
1904     }
1905 }
1906 
1907 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
1908     characteristic->start_handle = little_endian_read_16(packet, offset);
1909     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
1910     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
1911     characteristic->properties = little_endian_read_16(packet, offset + 6);
1912     reverse_128(&packet[offset+8], characteristic->uuid128);
1913     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
1914         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
1915     }
1916 }
1917 
1918 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
1919     descriptor->handle = little_endian_read_16(packet, offset);
1920     reverse_128(&packet[offset+2], descriptor->uuid128);
1921     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
1922         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
1923     }
1924 }
1925 
1926 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1927     gatt_client_t * context = provide_context_for_conn_handle(con_handle);
1928     if (!context) return;
1929     if (context->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
1930         context->callback = callback;
1931         context->mtu_state = SEND_MTU_EXCHANGE;
1932         gatt_client_run();
1933     }
1934 }
1935 
1936 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1937     gatt_client_t * context = provide_context_for_conn_handle(con_handle);
1938     if (!context) return BTSTACK_MEMORY_ALLOC_FAILED;
1939     if (context->write_without_response_callback) return GATT_CLIENT_IN_WRONG_STATE;
1940     context->write_without_response_callback = callback;
1941     att_dispatch_client_request_can_send_now_event(context->con_handle);
1942     return 0;
1943 }
1944