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