xref: /btstack/src/ble/gatt_client.c (revision 1882d12dc36ae7b48f7f4ed3fd8d029fba3b08b1)
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     gatt_client_t * peripheral;
1081 
1082     if (packet_type == HCI_EVENT_PACKET) {
1083         switch (packet[0]){
1084             case L2CAP_EVENT_CAN_SEND_NOW:
1085                 gatt_client_run();
1086                 break;
1087             // att_server has negotiated the mtu for this connection, cache if context exists
1088             case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
1089                 peripheral = get_gatt_client_context_for_handle(handle);
1090                 if (!peripheral) break;
1091                 peripheral->mtu = little_endian_read_16(packet, 4);
1092                 break;
1093             default:
1094                 break;
1095         }
1096         return;
1097     }
1098 
1099     if (packet_type != ATT_DATA_PACKET) return;
1100 
1101     // special cases: notifications don't need a context while indications motivate creating one
1102     switch (packet[0]){
1103         case ATT_HANDLE_VALUE_NOTIFICATION:
1104             report_gatt_notification(handle, little_endian_read_16(packet,1), &packet[3], size-3);
1105             return;
1106         case ATT_HANDLE_VALUE_INDICATION:
1107             peripheral = provide_context_for_conn_handle(handle);
1108             break;
1109         default:
1110             peripheral = get_gatt_client_context_for_handle(handle);
1111             break;
1112     }
1113 
1114     if (!peripheral) return;
1115 
1116     switch (packet[0]){
1117         case ATT_EXCHANGE_MTU_RESPONSE:
1118         {
1119             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1120             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1121             peripheral->mtu = remote_rx_mtu < local_rx_mtu ? remote_rx_mtu : local_rx_mtu;
1122             peripheral->mtu_state = MTU_EXCHANGED;
1123             emit_gatt_mtu_exchanged_result_event(peripheral, peripheral->mtu);
1124             break;
1125         }
1126         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
1127             switch(peripheral->gatt_client_state){
1128                 case P_W4_SERVICE_QUERY_RESULT:
1129                     report_gatt_services(peripheral, packet, size);
1130                     trigger_next_service_query(peripheral, get_last_result_handle_from_service_list(packet, size));
1131                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1132                     break;
1133                 default:
1134                     break;
1135             }
1136             break;
1137         case ATT_HANDLE_VALUE_INDICATION:
1138             report_gatt_indication(handle, little_endian_read_16(packet,1), &packet[3], size-3);
1139             peripheral->send_confirmation = 1;
1140             break;
1141 
1142         case ATT_READ_BY_TYPE_RESPONSE:
1143             switch (peripheral->gatt_client_state){
1144                 case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1145                     report_gatt_characteristics(peripheral, packet, size);
1146                     trigger_next_characteristic_query(peripheral, get_last_result_handle_from_characteristics_list(packet, size));
1147                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1148                     break;
1149                 case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1150                     report_gatt_characteristics(peripheral, packet, size);
1151                     trigger_next_characteristic_query(peripheral, get_last_result_handle_from_characteristics_list(packet, size));
1152                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1153                     break;
1154                 case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1155                 {
1156                     uint16_t uuid16 = 0;
1157                     uint16_t pair_size = packet[1];
1158 
1159                     if (pair_size < 7){
1160                         // UUIDs not available, query first included service
1161                         peripheral->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1162                         peripheral->query_start_handle = little_endian_read_16(packet, 4);
1163                         peripheral->query_end_handle = little_endian_read_16(packet,6);
1164                         peripheral->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1165                         break;
1166                     }
1167 
1168                     uint16_t offset;
1169                     for (offset = 2; offset < size; offset += pair_size){
1170                         uint16_t include_handle = little_endian_read_16(packet, offset);
1171                         peripheral->query_start_handle = little_endian_read_16(packet,offset+2);
1172                         peripheral->query_end_handle = little_endian_read_16(packet,offset+4);
1173                         uuid16 = little_endian_read_16(packet, offset+6);
1174                         report_gatt_included_service_uuid16(peripheral, include_handle, uuid16);
1175                     }
1176 
1177                     trigger_next_included_service_query(peripheral, get_last_result_handle_from_included_services_list(packet, size));
1178                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1179                     break;
1180                 }
1181                 case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1182                     peripheral->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1183                     peripheral->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1184                     break;
1185                 case P_W4_READ_BY_TYPE_RESPONSE: {
1186                     uint16_t pair_size = packet[1];
1187                     uint16_t offset;
1188                     uint16_t last_result_handle = 0;
1189                     for (offset = 2; offset < size ; offset += pair_size){
1190                         uint16_t value_handle = little_endian_read_16(packet, offset);
1191                         report_gatt_characteristic_value(peripheral, value_handle, &packet[offset+2], pair_size-2);
1192                         last_result_handle = value_handle;
1193                     }
1194                     trigger_next_read_by_type_query(peripheral, last_result_handle);
1195                     break;
1196                 }
1197                 default:
1198                     break;
1199             }
1200             break;
1201         case ATT_READ_RESPONSE:
1202             switch (peripheral->gatt_client_state){
1203                 case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT: {
1204                     uint8_t uuid128[16];
1205                     reverse_128(&packet[1], uuid128);
1206                     report_gatt_included_service_uuid128(peripheral, peripheral->start_group_handle, uuid128);
1207                     trigger_next_included_service_query(peripheral, peripheral->start_group_handle);
1208                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1209                     break;
1210                 }
1211                 case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1212                     gatt_client_handle_transaction_complete(peripheral);
1213                     report_gatt_characteristic_value(peripheral, peripheral->attribute_handle, &packet[1], size-1);
1214                     emit_gatt_complete_event(peripheral, 0);
1215                     break;
1216 
1217                 case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1218                     gatt_client_handle_transaction_complete(peripheral);
1219                     report_gatt_characteristic_descriptor(peripheral, peripheral->attribute_handle, &packet[1], size-1, 0);
1220                     emit_gatt_complete_event(peripheral, 0);
1221                     break;
1222                 }
1223                 default:
1224                     break;
1225             }
1226             break;
1227 
1228         case ATT_FIND_BY_TYPE_VALUE_RESPONSE:
1229         {
1230             uint8_t pair_size = 4;
1231             int i;
1232             uint16_t start_group_handle;
1233             uint16_t   end_group_handle= 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
1234             for (i = 1; i<size; i+=pair_size){
1235                 start_group_handle = little_endian_read_16(packet,i);
1236                 end_group_handle = little_endian_read_16(packet,i+2);
1237                 emit_gatt_service_query_result_event(peripheral, start_group_handle, end_group_handle, peripheral->uuid128);
1238             }
1239             trigger_next_service_by_uuid_query(peripheral, end_group_handle);
1240             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1241             break;
1242         }
1243         case ATT_FIND_INFORMATION_REPLY:
1244         {
1245             uint8_t pair_size = 4;
1246             if (packet[1] == 2){
1247                 pair_size = 18;
1248             }
1249             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
1250             report_gatt_all_characteristic_descriptors(peripheral, &packet[2], size-2, pair_size);
1251             trigger_next_characteristic_descriptor_query(peripheral, last_descriptor_handle);
1252             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1253             break;
1254         }
1255 
1256         case ATT_WRITE_RESPONSE:
1257             switch (peripheral->gatt_client_state){
1258                 case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1259                     gatt_client_handle_transaction_complete(peripheral);
1260                     emit_gatt_complete_event(peripheral, 0);
1261                     break;
1262                 case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1263                     gatt_client_handle_transaction_complete(peripheral);
1264                     emit_gatt_complete_event(peripheral, 0);
1265                     break;
1266                 case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1267                     gatt_client_handle_transaction_complete(peripheral);
1268                     emit_gatt_complete_event(peripheral, 0);
1269                     break;
1270                 default:
1271                     break;
1272             }
1273             break;
1274 
1275         case ATT_READ_BLOB_RESPONSE:{
1276             uint16_t received_blob_length = size-1;
1277             switch(peripheral->gatt_client_state){
1278                 case P_W4_READ_BLOB_RESULT:
1279                     report_gatt_long_characteristic_value_blob(peripheral, peripheral->attribute_handle, &packet[1], received_blob_length, peripheral->attribute_offset);
1280                     trigger_next_blob_query(peripheral, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
1281                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1282                     break;
1283                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1284                     report_gatt_long_characteristic_descriptor(peripheral, peripheral->attribute_handle,
1285                                                           &packet[1], received_blob_length,
1286                                                           peripheral->attribute_offset);
1287                     trigger_next_blob_query(peripheral, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY, received_blob_length);
1288                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1289                     break;
1290                 default:
1291                     break;
1292             }
1293             break;
1294         }
1295         case ATT_PREPARE_WRITE_RESPONSE:
1296             switch (peripheral->gatt_client_state){
1297                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1298                     gatt_client_handle_transaction_complete(peripheral);
1299                     if (is_value_valid(peripheral, packet, size)){
1300                         emit_gatt_complete_event(peripheral, 0);
1301                     } else {
1302                         emit_gatt_complete_event(peripheral, ATT_ERROR_DATA_MISMATCH);
1303                     }
1304                     break;
1305 
1306                 case P_W4_PREPARE_WRITE_RESULT:{
1307                     peripheral->attribute_offset = little_endian_read_16(packet, 3);
1308                     trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1309                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1310                     break;
1311                 }
1312                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1313                     peripheral->attribute_offset = little_endian_read_16(packet, 3);
1314                     trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR, P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1315                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1316                     break;
1317                 }
1318                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT:{
1319                     if (is_value_valid(peripheral, packet, size)){
1320                         peripheral->attribute_offset = little_endian_read_16(packet, 3);
1321                         trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_RELIABLE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1322                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1323                         break;
1324                     }
1325                     peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1326                     break;
1327                 }
1328                 default:
1329                     break;
1330             }
1331             break;
1332 
1333         case ATT_EXECUTE_WRITE_RESPONSE:
1334             switch (peripheral->gatt_client_state){
1335                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1336                     gatt_client_handle_transaction_complete(peripheral);
1337                     emit_gatt_complete_event(peripheral, 0);
1338                     break;
1339                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1340                     gatt_client_handle_transaction_complete(peripheral);
1341                     emit_gatt_complete_event(peripheral, 0);
1342                     break;
1343                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1344                     gatt_client_handle_transaction_complete(peripheral);
1345                     emit_gatt_complete_event(peripheral, ATT_ERROR_DATA_MISMATCH);
1346                     break;
1347                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1348                     gatt_client_handle_transaction_complete(peripheral);
1349                     emit_gatt_complete_event(peripheral, 0);
1350                     break;
1351                 default:
1352                     break;
1353 
1354             }
1355             break;
1356 
1357         case ATT_READ_MULTIPLE_RESPONSE:
1358             switch(peripheral->gatt_client_state){
1359                 case P_W4_READ_MULTIPLE_RESPONSE:
1360                     report_gatt_characteristic_value(peripheral, 0, &packet[1], size-1);
1361                     gatt_client_handle_transaction_complete(peripheral);
1362                     emit_gatt_complete_event(peripheral, 0);
1363                     break;
1364                 default:
1365                     break;
1366             }
1367             break;
1368 
1369         case ATT_ERROR_RESPONSE:
1370 
1371             switch (packet[4]){
1372                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1373                     switch(peripheral->gatt_client_state){
1374                         case P_W4_SERVICE_QUERY_RESULT:
1375                         case P_W4_SERVICE_WITH_UUID_RESULT:
1376                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1377                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1378                             gatt_client_handle_transaction_complete(peripheral);
1379                             emit_gatt_complete_event(peripheral, 0);
1380                             break;
1381                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1382                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1383                             characteristic_end_found(peripheral, peripheral->end_group_handle);
1384                             gatt_client_handle_transaction_complete(peripheral);
1385                             emit_gatt_complete_event(peripheral, 0);
1386                             break;
1387                         case P_W4_READ_BY_TYPE_RESPONSE:
1388                             gatt_client_handle_transaction_complete(peripheral);
1389                             if (peripheral->start_group_handle == peripheral->query_start_handle){
1390                                 emit_gatt_complete_event(peripheral, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
1391                             } else {
1392                                 emit_gatt_complete_event(peripheral, 0);
1393                             }
1394                             break;
1395                         default:
1396                             gatt_client_report_error_if_pending(peripheral, packet[4]);
1397                             break;
1398                     }
1399                     break;
1400                 }
1401                 default:
1402                     gatt_client_report_error_if_pending(peripheral, packet[4]);
1403                     break;
1404             }
1405             break;
1406 
1407         default:
1408             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
1409             break;
1410     }
1411     gatt_client_run();
1412 }
1413 
1414 #ifdef ENABLE_LE_SIGNED_WRITE
1415 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
1416     btstack_linked_list_iterator_t it;
1417     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
1418     while (btstack_linked_list_iterator_has_next(&it)){
1419         gatt_client_t * peripheral = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
1420         if (peripheral->gatt_client_state == P_W4_CMAC_RESULT){
1421             // store result
1422             memcpy(peripheral->cmac, hash, 8);
1423             // reverse_64(hash, peripheral->cmac);
1424             peripheral->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1425             gatt_client_run();
1426             return;
1427         }
1428     }
1429 }
1430 
1431 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){
1432     gatt_client_t * peripheral = provide_context_for_conn_handle(con_handle);
1433     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1434     peripheral->le_device_index = sm_le_device_index(con_handle);
1435     if (peripheral->le_device_index < 0) return GATT_CLIENT_IN_WRONG_STATE; // device lookup not done / no stored bonding information
1436 
1437     peripheral->callback = callback;
1438     peripheral->attribute_handle = handle;
1439     peripheral->attribute_length = message_len;
1440     peripheral->attribute_value = message;
1441     peripheral->gatt_client_state = P_W4_CMAC_READY;
1442 
1443     gatt_client_run();
1444     return 0;
1445 }
1446 #endif
1447 
1448 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1449     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1450     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1451     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1452 
1453     peripheral->callback = callback;
1454     peripheral->start_group_handle = 0x0001;
1455     peripheral->end_group_handle   = 0xffff;
1456     peripheral->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
1457     peripheral->uuid16 = 0;
1458     gatt_client_run();
1459     return 0;
1460 }
1461 
1462 
1463 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
1464     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1465 
1466     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1467     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1468 
1469     peripheral->callback = callback;
1470     peripheral->start_group_handle = 0x0001;
1471     peripheral->end_group_handle   = 0xffff;
1472     peripheral->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1473     peripheral->uuid16 = uuid16;
1474     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), peripheral->uuid16);
1475     gatt_client_run();
1476     return 0;
1477 }
1478 
1479 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
1480     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1481 
1482     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1483     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1484 
1485     peripheral->callback = callback;
1486     peripheral->start_group_handle = 0x0001;
1487     peripheral->end_group_handle   = 0xffff;
1488     peripheral->uuid16 = 0;
1489     memcpy(peripheral->uuid128, uuid128, 16);
1490     peripheral->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1491     gatt_client_run();
1492     return 0;
1493 }
1494 
1495 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t *service){
1496     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1497 
1498     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1499     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1500 
1501     peripheral->callback = callback;
1502     peripheral->start_group_handle = service->start_group_handle;
1503     peripheral->end_group_handle   = service->end_group_handle;
1504     peripheral->filter_with_uuid = 0;
1505     peripheral->characteristic_start_handle = 0;
1506     peripheral->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
1507     gatt_client_run();
1508     return 0;
1509 }
1510 
1511 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){
1512     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1513 
1514     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1515     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1516 
1517     peripheral->callback = callback;
1518     peripheral->start_group_handle = service->start_group_handle;
1519     peripheral->end_group_handle   = service->end_group_handle;
1520     peripheral->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
1521 
1522     gatt_client_run();
1523     return 0;
1524 }
1525 
1526 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){
1527     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1528 
1529     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1530     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1531 
1532     peripheral->callback = callback;
1533     peripheral->start_group_handle = start_handle;
1534     peripheral->end_group_handle   = end_handle;
1535     peripheral->filter_with_uuid = 1;
1536     peripheral->uuid16 = uuid16;
1537     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), uuid16);
1538     peripheral->characteristic_start_handle = 0;
1539     peripheral->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
1540 
1541     gatt_client_run();
1542     return 0;
1543 }
1544 
1545 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){
1546     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1547 
1548     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1549     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1550 
1551     peripheral->callback = callback;
1552     peripheral->start_group_handle = start_handle;
1553     peripheral->end_group_handle   = end_handle;
1554     peripheral->filter_with_uuid = 1;
1555     peripheral->uuid16 = 0;
1556     memcpy(peripheral->uuid128, uuid128, 16);
1557     peripheral->characteristic_start_handle = 0;
1558     peripheral->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
1559 
1560     gatt_client_run();
1561     return 0;
1562 }
1563 
1564 
1565 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){
1566     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, handle, service->start_group_handle, service->end_group_handle, uuid16);
1567 }
1568 
1569 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){
1570     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, handle, service->start_group_handle, service->end_group_handle, uuid128);
1571 }
1572 
1573 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t *characteristic){
1574     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1575 
1576     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1577     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1578 
1579     if (characteristic->value_handle == characteristic->end_handle){
1580         emit_gatt_complete_event(peripheral, 0);
1581         return 0;
1582     }
1583     peripheral->callback = callback;
1584     peripheral->start_group_handle = characteristic->value_handle + 1;
1585     peripheral->end_group_handle   = characteristic->end_handle;
1586     peripheral->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
1587 
1588     gatt_client_run();
1589     return 0;
1590 }
1591 
1592 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){
1593     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1594 
1595     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1596     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1597 
1598     peripheral->callback = callback;
1599     peripheral->attribute_handle = value_handle;
1600     peripheral->attribute_offset = 0;
1601     peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
1602     gatt_client_run();
1603     return 0;
1604 }
1605 
1606 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){
1607     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1608 
1609     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1610     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1611 
1612     peripheral->callback = callback;
1613     peripheral->start_group_handle = start_handle;
1614     peripheral->end_group_handle = end_handle;
1615     peripheral->query_start_handle = start_handle;
1616     peripheral->query_end_handle = end_handle;
1617     peripheral->uuid16 = uuid16;
1618     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), uuid16);
1619     peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1620     gatt_client_run();
1621     return 0;
1622 }
1623 
1624 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){
1625     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1626 
1627     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1628     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1629 
1630     peripheral->callback = callback;
1631     peripheral->start_group_handle = start_handle;
1632     peripheral->end_group_handle = end_handle;
1633     peripheral->query_start_handle = start_handle;
1634     peripheral->query_end_handle = end_handle;
1635     peripheral->uuid16 = 0;
1636     memcpy(peripheral->uuid128, uuid128, 16);
1637     peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1638     gatt_client_run();
1639     return 0;
1640 }
1641 
1642 
1643 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, uint16_t handle, gatt_client_characteristic_t *characteristic){
1644     return gatt_client_read_value_of_characteristic_using_value_handle(callback, handle, characteristic->value_handle);
1645 }
1646 
1647 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){
1648     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1649 
1650     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1651     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1652 
1653     peripheral->callback = callback;
1654     peripheral->attribute_handle = characteristic_value_handle;
1655     peripheral->attribute_offset = offset;
1656     peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1657     gatt_client_run();
1658     return 0;
1659 }
1660 
1661 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){
1662     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, characteristic_value_handle, 0);
1663 }
1664 
1665 uint8_t gatt_client_read_long_value_of_characteristic(btstack_packet_handler_t callback, uint16_t handle, gatt_client_characteristic_t *characteristic){
1666     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, handle, characteristic->value_handle);
1667 }
1668 
1669 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){
1670     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1671 
1672     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1673     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1674 
1675     peripheral->callback = callback;
1676     peripheral->read_multiple_handle_count = num_value_handles;
1677     peripheral->read_multiple_handles = value_handles;
1678     peripheral->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1679     gatt_client_run();
1680     return 0;
1681 }
1682 
1683 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){
1684     gatt_client_t * peripheral = provide_context_for_conn_handle(con_handle);
1685 
1686     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1687     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1688 
1689     if (value_length > peripheral_mtu(peripheral) - 3) return GATT_CLIENT_VALUE_TOO_LONG;
1690     if (!att_dispatch_client_can_send_now(peripheral->con_handle)) return GATT_CLIENT_BUSY;
1691 
1692     att_write_request(ATT_WRITE_COMMAND, peripheral->con_handle, value_handle, value_length, value);
1693     return 0;
1694 }
1695 
1696 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){
1697     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1698 
1699     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1700     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1701 
1702     peripheral->callback = callback;
1703     peripheral->attribute_handle = value_handle;
1704     peripheral->attribute_length = value_length;
1705     peripheral->attribute_value = data;
1706     peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1707     gatt_client_run();
1708     return 0;
1709 }
1710 
1711 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){
1712     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1713 
1714     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1715     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1716 
1717     peripheral->callback = callback;
1718     peripheral->attribute_handle = value_handle;
1719     peripheral->attribute_length = value_length;
1720     peripheral->attribute_offset = offset;
1721     peripheral->attribute_value = data;
1722     peripheral->gatt_client_state = P_W2_PREPARE_WRITE;
1723     gatt_client_run();
1724     return 0;
1725 }
1726 
1727 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){
1728     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
1729 }
1730 
1731 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){
1732     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1733 
1734     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1735     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1736 
1737     peripheral->callback = callback;
1738     peripheral->attribute_handle = value_handle;
1739     peripheral->attribute_length = value_length;
1740     peripheral->attribute_offset = 0;
1741     peripheral->attribute_value = value;
1742     peripheral->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1743     gatt_client_run();
1744     return 0;
1745 }
1746 
1747 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){
1748     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1749 
1750     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1751     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1752 
1753     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
1754         (characteristic->properties & ATT_PROPERTY_NOTIFY) == 0) {
1755         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
1756         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
1757     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
1758                (characteristic->properties & ATT_PROPERTY_INDICATE) == 0){
1759         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
1760         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
1761     }
1762 
1763     peripheral->callback = callback;
1764     peripheral->start_group_handle = characteristic->value_handle;
1765     peripheral->end_group_handle = characteristic->end_handle;
1766     little_endian_store_16(peripheral->client_characteristic_configuration_value, 0, configuration);
1767 
1768     peripheral->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1769     gatt_client_run();
1770     return 0;
1771 }
1772 
1773 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){
1774     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1775 
1776     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1777     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1778 
1779     peripheral->callback = callback;
1780     peripheral->attribute_handle = descriptor_handle;
1781 
1782     peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1783     gatt_client_run();
1784     return 0;
1785 }
1786 
1787 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
1788     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
1789 }
1790 
1791 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){
1792     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1793 
1794     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1795     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1796 
1797     peripheral->callback = callback;
1798     peripheral->attribute_handle = descriptor_handle;
1799     peripheral->attribute_offset = offset;
1800     peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1801     gatt_client_run();
1802     return 0;
1803 }
1804 
1805 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){
1806     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
1807 }
1808 
1809 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){
1810     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
1811 }
1812 
1813 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){
1814     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1815 
1816     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1817     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1818 
1819     peripheral->callback = callback;
1820     peripheral->attribute_handle = descriptor_handle;
1821     peripheral->attribute_length = length;
1822     peripheral->attribute_offset = 0;
1823     peripheral->attribute_value = data;
1824     peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
1825     gatt_client_run();
1826     return 0;
1827 }
1828 
1829 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){
1830     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, length, value);
1831 }
1832 
1833 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){
1834     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1835 
1836     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1837     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1838 
1839     peripheral->callback = callback;
1840     peripheral->attribute_handle = descriptor_handle;
1841     peripheral->attribute_length = length;
1842     peripheral->attribute_offset = offset;
1843     peripheral->attribute_value = data;
1844     peripheral->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
1845     gatt_client_run();
1846     return 0;
1847 }
1848 
1849 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){
1850     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, length, data );
1851 }
1852 
1853 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){
1854     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, length, value);
1855 }
1856 
1857 /**
1858  * @brief -> gatt complete event
1859  */
1860 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){
1861     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1862 
1863     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1864     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1865 
1866     peripheral->callback = callback;
1867     peripheral->attribute_handle = attribute_handle;
1868     peripheral->attribute_length = length;
1869     peripheral->attribute_offset = offset;
1870     peripheral->attribute_value = data;
1871     peripheral->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
1872     gatt_client_run();
1873     return 0;
1874 }
1875 
1876 /**
1877  * @brief -> gatt complete event
1878  */
1879 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1880     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1881 
1882     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1883     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1884 
1885     peripheral->callback = callback;
1886     peripheral->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
1887     gatt_client_run();
1888     return 0;
1889 }
1890 
1891 /**
1892  * @brief -> gatt complete event
1893  */
1894 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1895     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1896 
1897     if (!peripheral) return BTSTACK_MEMORY_ALLOC_FAILED;
1898     if (!is_ready(peripheral)) return GATT_CLIENT_IN_WRONG_STATE;
1899 
1900     peripheral->callback = callback;
1901     peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
1902     gatt_client_run();
1903     return 0;
1904 }
1905 
1906 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t *service){
1907     service->start_group_handle = little_endian_read_16(packet, offset);
1908     service->end_group_handle = little_endian_read_16(packet, offset + 2);
1909     reverse_128(&packet[offset + 4], service->uuid128);
1910     if (uuid_has_bluetooth_prefix(service->uuid128)){
1911         service->uuid16 = big_endian_read_32(service->uuid128, 0);
1912     }
1913 }
1914 
1915 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
1916     characteristic->start_handle = little_endian_read_16(packet, offset);
1917     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
1918     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
1919     characteristic->properties = little_endian_read_16(packet, offset + 6);
1920     reverse_128(&packet[offset+8], characteristic->uuid128);
1921     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
1922         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
1923     }
1924 }
1925 
1926 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
1927     descriptor->handle = little_endian_read_16(packet, offset);
1928     reverse_128(&packet[offset+2], descriptor->uuid128);
1929     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
1930         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
1931     }
1932 }
1933 
1934 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1935     gatt_client_t * context = provide_context_for_conn_handle(con_handle);
1936     if (!context) return;
1937     if (context->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
1938         context->callback = callback;
1939         context->mtu_state = SEND_MTU_EXCHANGE;
1940         gatt_client_run();
1941     }
1942 }
1943 
1944 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1945     gatt_client_t * context = provide_context_for_conn_handle(con_handle);
1946     if (!context) return BTSTACK_MEMORY_ALLOC_FAILED;
1947     if (context->write_without_response_callback) return GATT_CLIENT_IN_WRONG_STATE;
1948     context->write_without_response_callback = callback;
1949     att_dispatch_client_request_can_send_now_event(context->con_handle);
1950     return 0;
1951 }
1952