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