xref: /btstack/src/ble/gatt_client.c (revision a0a4507b35ea396d076a62a67efb1a5a800c5ff9)
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 == 6){
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                     if (pair_size != 8) break;
1265 
1266                     // UUIDs included, report all of them
1267                     uint16_t offset;
1268                     for (offset = 2; (offset + 8) <= size; offset += pair_size){
1269                         uint16_t include_handle = little_endian_read_16(packet, offset);
1270                         peripheral->query_start_handle = little_endian_read_16(packet,offset+2);
1271                         peripheral->query_end_handle = little_endian_read_16(packet,offset+4);
1272                         uuid16 = little_endian_read_16(packet, offset+6);
1273                         report_gatt_included_service_uuid16(peripheral, include_handle, uuid16);
1274                     }
1275 
1276                     trigger_next_included_service_query(peripheral, get_last_result_handle_from_included_services_list(packet, size));
1277                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1278                     break;
1279                 }
1280 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1281                 case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1282                     peripheral->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1283                     peripheral->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1284                     break;
1285 #endif
1286                 case P_W4_READ_BY_TYPE_RESPONSE: {
1287                     uint16_t pair_size = packet[1];
1288                     uint16_t offset;
1289                     uint16_t last_result_handle = 0;
1290                     for (offset = 2; offset < size ; offset += pair_size){
1291                         uint16_t value_handle = little_endian_read_16(packet, offset);
1292                         report_gatt_characteristic_value(peripheral, value_handle, &packet[offset+2], pair_size-2);
1293                         last_result_handle = value_handle;
1294                     }
1295                     trigger_next_read_by_type_query(peripheral, last_result_handle);
1296                     break;
1297                 }
1298                 default:
1299                     break;
1300             }
1301             break;
1302         case ATT_READ_RESPONSE:
1303             switch (peripheral->gatt_client_state){
1304                 case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT: {
1305                     uint8_t uuid128[16];
1306                     reverse_128(&packet[1], uuid128);
1307                     report_gatt_included_service_uuid128(peripheral, peripheral->start_group_handle, uuid128);
1308                     trigger_next_included_service_query(peripheral, peripheral->start_group_handle);
1309                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1310                     break;
1311                 }
1312                 case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1313                     gatt_client_handle_transaction_complete(peripheral);
1314                     report_gatt_characteristic_value(peripheral, peripheral->attribute_handle, &packet[1], size-1);
1315                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1316                     break;
1317 
1318                 case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1319                     gatt_client_handle_transaction_complete(peripheral);
1320                     report_gatt_characteristic_descriptor(peripheral, peripheral->attribute_handle, &packet[1], size-1, 0);
1321                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1322                     break;
1323                 }
1324                 default:
1325                     break;
1326             }
1327             break;
1328 
1329         case ATT_FIND_BY_TYPE_VALUE_RESPONSE:
1330         {
1331             uint8_t pair_size = 4;
1332             int i;
1333             uint16_t start_group_handle;
1334             uint16_t   end_group_handle= 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
1335             for (i = 1; (i + pair_size) <= size; i += pair_size){
1336                 start_group_handle = little_endian_read_16(packet,i);
1337                 end_group_handle = little_endian_read_16(packet,i+2);
1338                 emit_gatt_service_query_result_event(peripheral, start_group_handle, end_group_handle, peripheral->uuid128);
1339             }
1340             trigger_next_service_by_uuid_query(peripheral, end_group_handle);
1341             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1342             break;
1343         }
1344         case ATT_FIND_INFORMATION_REPLY:
1345         {
1346             if (size < 2) break;
1347 
1348             uint8_t pair_size = 4;
1349             if (packet[1] == 2){
1350                 pair_size = 18;
1351             }
1352             uint16_t offset = 2;
1353 
1354             if (size < (pair_size + offset)) break;
1355             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
1356 
1357 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1358             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", peripheral->gatt_client_state);
1359             if (peripheral->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
1360                 // iterate over descriptors looking for CCC
1361                 if (pair_size == 4){
1362                     while ((offset + 4) <= size){
1363                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
1364                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
1365                             peripheral->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
1366                             peripheral->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1367                             log_info("CCC found %x", peripheral->client_characteristic_configuration_handle);
1368                             break;
1369                         }
1370                         offset += pair_size;
1371                     }
1372                 }
1373                 if (is_query_done(peripheral, last_descriptor_handle)){
1374 
1375                 } else {
1376                     // next
1377                     peripheral->start_group_handle = last_descriptor_handle + 1;
1378                     peripheral->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1379                 }
1380                 break;
1381             }
1382 #endif
1383             report_gatt_all_characteristic_descriptors(peripheral, &packet[2], size-2, pair_size);
1384             trigger_next_characteristic_descriptor_query(peripheral, last_descriptor_handle);
1385             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1386             break;
1387         }
1388 
1389         case ATT_WRITE_RESPONSE:
1390             switch (peripheral->gatt_client_state){
1391                 case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1392                     gatt_client_handle_transaction_complete(peripheral);
1393                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1394                     break;
1395                 case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1396                     gatt_client_handle_transaction_complete(peripheral);
1397                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1398                     break;
1399                 case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1400                     gatt_client_handle_transaction_complete(peripheral);
1401                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1402                     break;
1403                 default:
1404                     break;
1405             }
1406             break;
1407 
1408         case ATT_READ_BLOB_RESPONSE:{
1409             uint16_t received_blob_length = size-1;
1410             switch(peripheral->gatt_client_state){
1411                 case P_W4_READ_BLOB_RESULT:
1412                     report_gatt_long_characteristic_value_blob(peripheral, peripheral->attribute_handle, &packet[1], received_blob_length, peripheral->attribute_offset);
1413                     trigger_next_blob_query(peripheral, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
1414                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1415                     break;
1416                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1417                     report_gatt_long_characteristic_descriptor(peripheral, peripheral->attribute_handle,
1418                                                           &packet[1], received_blob_length,
1419                                                           peripheral->attribute_offset);
1420                     trigger_next_blob_query(peripheral, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY, received_blob_length);
1421                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1422                     break;
1423                 default:
1424                     break;
1425             }
1426             break;
1427         }
1428         case ATT_PREPARE_WRITE_RESPONSE:
1429             switch (peripheral->gatt_client_state){
1430                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1431                     gatt_client_handle_transaction_complete(peripheral);
1432                     if (is_value_valid(peripheral, packet, size)){
1433                         emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1434                     } else {
1435                         emit_gatt_complete_event(peripheral, ATT_ERROR_DATA_MISMATCH);
1436                     }
1437                     break;
1438 
1439                 case P_W4_PREPARE_WRITE_RESULT:{
1440                     peripheral->attribute_offset = little_endian_read_16(packet, 3);
1441                     trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1442                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1443                     break;
1444                 }
1445                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:{
1446                     peripheral->attribute_offset = little_endian_read_16(packet, 3);
1447                     trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR, P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1448                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1449                     break;
1450                 }
1451                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT:{
1452                     if (is_value_valid(peripheral, packet, size)){
1453                         peripheral->attribute_offset = little_endian_read_16(packet, 3);
1454                         trigger_next_prepare_write_query(peripheral, P_W2_PREPARE_RELIABLE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1455                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1456                         break;
1457                     }
1458                     peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1459                     break;
1460                 }
1461                 default:
1462                     break;
1463             }
1464             break;
1465 
1466         case ATT_EXECUTE_WRITE_RESPONSE:
1467             switch (peripheral->gatt_client_state){
1468                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1469                     gatt_client_handle_transaction_complete(peripheral);
1470                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1471                     break;
1472                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1473                     gatt_client_handle_transaction_complete(peripheral);
1474                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1475                     break;
1476                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1477                     gatt_client_handle_transaction_complete(peripheral);
1478                     emit_gatt_complete_event(peripheral, ATT_ERROR_DATA_MISMATCH);
1479                     break;
1480                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1481                     gatt_client_handle_transaction_complete(peripheral);
1482                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1483                     break;
1484                 default:
1485                     break;
1486 
1487             }
1488             break;
1489 
1490         case ATT_READ_MULTIPLE_RESPONSE:
1491             switch(peripheral->gatt_client_state){
1492                 case P_W4_READ_MULTIPLE_RESPONSE:
1493                     report_gatt_characteristic_value(peripheral, 0, &packet[1], size-1);
1494                     gatt_client_handle_transaction_complete(peripheral);
1495                     emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1496                     break;
1497                 default:
1498                     break;
1499             }
1500             break;
1501 
1502         case ATT_ERROR_RESPONSE:
1503             if (size < 5) return;
1504             switch (packet[4]){
1505                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1506                     switch(peripheral->gatt_client_state){
1507                         case P_W4_SERVICE_QUERY_RESULT:
1508                         case P_W4_SERVICE_WITH_UUID_RESULT:
1509                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1510                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1511                             gatt_client_handle_transaction_complete(peripheral);
1512                             emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1513                             break;
1514                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1515                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1516                             characteristic_end_found(peripheral, peripheral->end_group_handle);
1517                             gatt_client_handle_transaction_complete(peripheral);
1518                             emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1519                             break;
1520                         case P_W4_READ_BY_TYPE_RESPONSE:
1521                             gatt_client_handle_transaction_complete(peripheral);
1522                             if (peripheral->start_group_handle == peripheral->query_start_handle){
1523                                 emit_gatt_complete_event(peripheral, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
1524                             } else {
1525                                 emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1526                             }
1527                             break;
1528                         default:
1529                             gatt_client_report_error_if_pending(peripheral, packet[4]);
1530                             break;
1531                     }
1532                     break;
1533                 }
1534 
1535 #ifdef ENABLE_GATT_CLIENT_PAIRING
1536 
1537                 case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
1538                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
1539                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
1540 
1541                     // security too low
1542                     if (peripheral->security_counter > 0) {
1543                         gatt_client_report_error_if_pending(peripheral, packet[4]);
1544                         break;
1545                     }
1546                     // start security
1547                     peripheral->security_counter++;
1548 
1549                     // setup action
1550                     int retry = 1;
1551                     switch (peripheral->gatt_client_state){
1552                         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1553                             peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
1554                             break;
1555                         case P_W4_READ_BLOB_RESULT:
1556                             peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1557                             break;
1558                         case P_W4_READ_BY_TYPE_RESPONSE:
1559                             peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1560                             break;
1561                         case P_W4_READ_MULTIPLE_RESPONSE:
1562                             peripheral->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1563                             break;
1564                         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1565                             peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1566                             break;
1567                         case P_W4_PREPARE_WRITE_RESULT:
1568                             peripheral->gatt_client_state = P_W2_PREPARE_WRITE;
1569                             break;
1570                         case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1571                             peripheral->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
1572                             break;
1573                         case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
1574                             peripheral->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1575                             break;
1576                         case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1577                             peripheral->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
1578                             break;
1579                         case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1580                             peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
1581                             break;
1582                         case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1583                             peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1584                             break;
1585                         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1586                             peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1587                             break;
1588                         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1589                             peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1590                             break;
1591                         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1592                             peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
1593                             break;
1594                         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1595                             peripheral->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1596                             break;
1597                         case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1598                             peripheral->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
1599                             break;
1600                         case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1601                             peripheral->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
1602                             break;
1603 #ifdef ENABLE_LE_SIGNED_WRITE
1604                         case P_W4_SEND_SINGED_WRITE_DONE:
1605                             peripheral->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1606                             break;
1607 #endif
1608                         default:
1609                             log_info("retry not supported for state %x", peripheral->gatt_client_state);
1610                             retry = 0;
1611                             break;
1612                     }
1613 
1614                     if (!retry) {
1615                         gatt_client_report_error_if_pending(peripheral, packet[4]);
1616                         break;
1617                     }
1618 
1619                     log_info("security error, start pairing");
1620 
1621                     // requrest pairing
1622                     peripheral->wait_for_pairing_complete = 1;
1623                     peripheral->pending_error_code = packet[4];
1624                     sm_request_pairing(peripheral->con_handle);
1625                     break;
1626                 }
1627 #endif
1628 
1629                 // nothing we can do about that
1630                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
1631                 default:
1632                     gatt_client_report_error_if_pending(peripheral, packet[4]);
1633                     break;
1634             }
1635             break;
1636 
1637         default:
1638             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
1639             break;
1640     }
1641     gatt_client_run();
1642 }
1643 
1644 #ifdef ENABLE_LE_SIGNED_WRITE
1645 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
1646     btstack_linked_list_iterator_t it;
1647     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
1648     while (btstack_linked_list_iterator_has_next(&it)){
1649         gatt_client_t * peripheral = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
1650         if (peripheral->gatt_client_state == P_W4_CMAC_RESULT){
1651             // store result
1652             (void)memcpy(peripheral->cmac, hash, 8);
1653             // reverse_64(hash, peripheral->cmac);
1654             peripheral->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1655             gatt_client_run();
1656             return;
1657         }
1658     }
1659 }
1660 
1661 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){
1662     gatt_client_t * peripheral = provide_context_for_conn_handle(con_handle);
1663     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1664     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1665 
1666     peripheral->callback = callback;
1667     peripheral->attribute_handle = handle;
1668     peripheral->attribute_length = message_len;
1669     peripheral->attribute_value = message;
1670     peripheral->gatt_client_state = P_W4_IDENTITY_RESOLVING;
1671     gatt_client_run();
1672     return ERROR_CODE_SUCCESS;
1673 }
1674 #endif
1675 
1676 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
1677     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1678     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1679     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1680 
1681     peripheral->callback = callback;
1682     peripheral->start_group_handle = 0x0001;
1683     peripheral->end_group_handle   = 0xffff;
1684     peripheral->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
1685     peripheral->uuid16 = 0;
1686     gatt_client_run();
1687     return ERROR_CODE_SUCCESS;
1688 }
1689 
1690 
1691 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
1692     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1693     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1694     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1695 
1696     peripheral->callback = callback;
1697     peripheral->start_group_handle = 0x0001;
1698     peripheral->end_group_handle   = 0xffff;
1699     peripheral->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1700     peripheral->uuid16 = uuid16;
1701     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), peripheral->uuid16);
1702     gatt_client_run();
1703     return ERROR_CODE_SUCCESS;
1704 }
1705 
1706 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
1707     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1708     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1709     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1710 
1711     peripheral->callback = callback;
1712     peripheral->start_group_handle = 0x0001;
1713     peripheral->end_group_handle   = 0xffff;
1714     peripheral->uuid16 = 0;
1715     (void)memcpy(peripheral->uuid128, uuid128, 16);
1716     peripheral->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
1717     gatt_client_run();
1718     return ERROR_CODE_SUCCESS;
1719 }
1720 
1721 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t *service){
1722     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1723     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1724     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1725 
1726     peripheral->callback = callback;
1727     peripheral->start_group_handle = service->start_group_handle;
1728     peripheral->end_group_handle   = service->end_group_handle;
1729     peripheral->filter_with_uuid = 0;
1730     peripheral->characteristic_start_handle = 0;
1731     peripheral->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
1732     gatt_client_run();
1733     return ERROR_CODE_SUCCESS;
1734 }
1735 
1736 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){
1737     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1738     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1739     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1740     peripheral->callback = callback;
1741     peripheral->start_group_handle = service->start_group_handle;
1742     peripheral->end_group_handle   = service->end_group_handle;
1743     peripheral->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
1744 
1745     gatt_client_run();
1746     return ERROR_CODE_SUCCESS;
1747 }
1748 
1749 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){
1750     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1751     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1752     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1753 
1754     peripheral->callback = callback;
1755     peripheral->start_group_handle = start_handle;
1756     peripheral->end_group_handle   = end_handle;
1757     peripheral->filter_with_uuid = 1;
1758     peripheral->uuid16 = uuid16;
1759     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), uuid16);
1760     peripheral->characteristic_start_handle = 0;
1761     peripheral->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
1762     gatt_client_run();
1763     return ERROR_CODE_SUCCESS;
1764 }
1765 
1766 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){
1767     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1768     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1769     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1770 
1771     peripheral->callback = callback;
1772     peripheral->start_group_handle = start_handle;
1773     peripheral->end_group_handle   = end_handle;
1774     peripheral->filter_with_uuid = 1;
1775     peripheral->uuid16 = 0;
1776     (void)memcpy(peripheral->uuid128, uuid128, 16);
1777     peripheral->characteristic_start_handle = 0;
1778     peripheral->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
1779     gatt_client_run();
1780     return ERROR_CODE_SUCCESS;
1781 }
1782 
1783 
1784 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){
1785     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, handle, service->start_group_handle, service->end_group_handle, uuid16);
1786 }
1787 
1788 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){
1789     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, handle, service->start_group_handle, service->end_group_handle, uuid128);
1790 }
1791 
1792 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t *characteristic){
1793     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1794     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1795     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1796 
1797     if (characteristic->value_handle == characteristic->end_handle){
1798         emit_gatt_complete_event(peripheral, ATT_ERROR_SUCCESS);
1799         return ERROR_CODE_SUCCESS;
1800     }
1801     peripheral->callback = callback;
1802     peripheral->start_group_handle = characteristic->value_handle + 1;
1803     peripheral->end_group_handle   = characteristic->end_handle;
1804     peripheral->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
1805     gatt_client_run();
1806     return ERROR_CODE_SUCCESS;
1807 }
1808 
1809 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){
1810     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1811     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1812     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1813 
1814     peripheral->callback = callback;
1815     peripheral->attribute_handle = value_handle;
1816     peripheral->attribute_offset = 0;
1817     peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
1818     gatt_client_run();
1819     return ERROR_CODE_SUCCESS;
1820 }
1821 
1822 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){
1823     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1824     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1825     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1826 
1827     peripheral->callback = callback;
1828     peripheral->start_group_handle = start_handle;
1829     peripheral->end_group_handle = end_handle;
1830     peripheral->query_start_handle = start_handle;
1831     peripheral->query_end_handle = end_handle;
1832     peripheral->uuid16 = uuid16;
1833     uuid_add_bluetooth_prefix((uint8_t*) &(peripheral->uuid128), uuid16);
1834     peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1835     gatt_client_run();
1836     return ERROR_CODE_SUCCESS;
1837 }
1838 
1839 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){
1840     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1841     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1842     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1843 
1844     peripheral->callback = callback;
1845     peripheral->start_group_handle = start_handle;
1846     peripheral->end_group_handle = end_handle;
1847     peripheral->query_start_handle = start_handle;
1848     peripheral->query_end_handle = end_handle;
1849     peripheral->uuid16 = 0;
1850     (void)memcpy(peripheral->uuid128, uuid128, 16);
1851     peripheral->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1852     gatt_client_run();
1853     return ERROR_CODE_SUCCESS;
1854 }
1855 
1856 
1857 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, uint16_t handle, gatt_client_characteristic_t *characteristic){
1858     return gatt_client_read_value_of_characteristic_using_value_handle(callback, handle, characteristic->value_handle);
1859 }
1860 
1861 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){
1862     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1863     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1864     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1865 
1866     peripheral->callback = callback;
1867     peripheral->attribute_handle = characteristic_value_handle;
1868     peripheral->attribute_offset = offset;
1869     peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1870     gatt_client_run();
1871     return ERROR_CODE_SUCCESS;
1872 }
1873 
1874 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){
1875     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, characteristic_value_handle, 0);
1876 }
1877 
1878 uint8_t gatt_client_read_long_value_of_characteristic(btstack_packet_handler_t callback, uint16_t handle, gatt_client_characteristic_t *characteristic){
1879     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, handle, characteristic->value_handle);
1880 }
1881 
1882 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){
1883     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1884     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1885     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1886 
1887     peripheral->callback = callback;
1888     peripheral->read_multiple_handle_count = num_value_handles;
1889     peripheral->read_multiple_handles = value_handles;
1890     peripheral->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1891     gatt_client_run();
1892     return ERROR_CODE_SUCCESS;
1893 }
1894 
1895 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){
1896     gatt_client_t * peripheral = provide_context_for_conn_handle(con_handle);
1897     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1898 
1899     if (value_length > (peripheral_mtu(peripheral) - 3)) return GATT_CLIENT_VALUE_TOO_LONG;
1900     if (!att_dispatch_client_can_send_now(peripheral->con_handle)) return GATT_CLIENT_BUSY;
1901 
1902     return att_write_request(ATT_WRITE_COMMAND, peripheral->con_handle, value_handle, value_length, value);
1903 }
1904 
1905 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){
1906     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1907     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1908     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1909 
1910     peripheral->callback = callback;
1911     peripheral->attribute_handle = value_handle;
1912     peripheral->attribute_length = value_length;
1913     peripheral->attribute_value = data;
1914     peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1915     gatt_client_run();
1916     return ERROR_CODE_SUCCESS;
1917 }
1918 
1919 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){
1920     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1921     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1922     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1923 
1924     peripheral->callback = callback;
1925     peripheral->attribute_handle = value_handle;
1926     peripheral->attribute_length = value_length;
1927     peripheral->attribute_offset = offset;
1928     peripheral->attribute_value = data;
1929     peripheral->gatt_client_state = P_W2_PREPARE_WRITE;
1930     gatt_client_run();
1931     return ERROR_CODE_SUCCESS;
1932 }
1933 
1934 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){
1935     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
1936 }
1937 
1938 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){
1939     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1940     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1941     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1942 
1943     peripheral->callback = callback;
1944     peripheral->attribute_handle = value_handle;
1945     peripheral->attribute_length = value_length;
1946     peripheral->attribute_offset = 0;
1947     peripheral->attribute_value = value;
1948     peripheral->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1949     gatt_client_run();
1950     return ERROR_CODE_SUCCESS;
1951 }
1952 
1953 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){
1954     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1955     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1956     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1957 
1958     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
1959         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0)) {
1960         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
1961         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
1962     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
1963                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0)){
1964         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
1965         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
1966     }
1967 
1968     peripheral->callback = callback;
1969     peripheral->start_group_handle = characteristic->value_handle;
1970     peripheral->end_group_handle = characteristic->end_handle;
1971     little_endian_store_16(peripheral->client_characteristic_configuration_value, 0, configuration);
1972 
1973 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1974     peripheral->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1975 #else
1976     peripheral->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1977 #endif
1978     gatt_client_run();
1979     return ERROR_CODE_SUCCESS;
1980 }
1981 
1982 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){
1983     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
1984     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
1985     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
1986 
1987     peripheral->callback = callback;
1988     peripheral->attribute_handle = descriptor_handle;
1989 
1990     peripheral->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1991     gatt_client_run();
1992     return ERROR_CODE_SUCCESS;
1993 }
1994 
1995 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
1996     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
1997 }
1998 
1999 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){
2000     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2001     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
2002     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
2003 
2004     peripheral->callback = callback;
2005     peripheral->attribute_handle = descriptor_handle;
2006     peripheral->attribute_offset = offset;
2007     peripheral->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2008     gatt_client_run();
2009     return ERROR_CODE_SUCCESS;
2010 }
2011 
2012 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){
2013     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2014 }
2015 
2016 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){
2017     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2018 }
2019 
2020 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){
2021     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2022     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
2023     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
2024 
2025     peripheral->callback = callback;
2026     peripheral->attribute_handle = descriptor_handle;
2027     peripheral->attribute_length = length;
2028     peripheral->attribute_offset = 0;
2029     peripheral->attribute_value = data;
2030     peripheral->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2031     gatt_client_run();
2032     return ERROR_CODE_SUCCESS;
2033 }
2034 
2035 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){
2036     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, length, value);
2037 }
2038 
2039 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){
2040     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2041     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
2042     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
2043 
2044     peripheral->callback = callback;
2045     peripheral->attribute_handle = descriptor_handle;
2046     peripheral->attribute_length = length;
2047     peripheral->attribute_offset = offset;
2048     peripheral->attribute_value = data;
2049     peripheral->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2050     gatt_client_run();
2051     return ERROR_CODE_SUCCESS;
2052 }
2053 
2054 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){
2055     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, length, data );
2056 }
2057 
2058 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){
2059     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, length, value);
2060 }
2061 
2062 /**
2063  * @brief -> gatt complete event
2064  */
2065 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){
2066     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2067     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
2068     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
2069 
2070     peripheral->callback = callback;
2071     peripheral->attribute_handle = attribute_handle;
2072     peripheral->attribute_length = length;
2073     peripheral->attribute_offset = offset;
2074     peripheral->attribute_value = data;
2075     peripheral->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
2076     gatt_client_run();
2077     return ERROR_CODE_SUCCESS;
2078 }
2079 
2080 /**
2081  * @brief -> gatt complete event
2082  */
2083 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2084     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2085 
2086     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
2087     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
2088 
2089     peripheral->callback = callback;
2090     peripheral->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
2091     gatt_client_run();
2092     return ERROR_CODE_SUCCESS;
2093 }
2094 
2095 /**
2096  * @brief -> gatt complete event
2097  */
2098 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2099     gatt_client_t * peripheral = provide_context_for_conn_handle_and_start_timer(con_handle);
2100     if (peripheral == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
2101     if (is_ready(peripheral) == 0) return GATT_CLIENT_IN_WRONG_STATE;
2102 
2103     peripheral->callback = callback;
2104     peripheral->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
2105     gatt_client_run();
2106     return ERROR_CODE_SUCCESS;
2107 }
2108 
2109 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t *service){
2110     service->start_group_handle = little_endian_read_16(packet, offset);
2111     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2112     reverse_128(&packet[offset + 4], service->uuid128);
2113     if (uuid_has_bluetooth_prefix(service->uuid128)){
2114         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2115     } else {
2116         service->uuid16 = 0;
2117     }
2118 }
2119 
2120 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2121     characteristic->start_handle = little_endian_read_16(packet, offset);
2122     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2123     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2124     characteristic->properties = little_endian_read_16(packet, offset + 6);
2125     reverse_128(&packet[offset+8], characteristic->uuid128);
2126     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2127         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2128     } else {
2129         characteristic->uuid16 = 0;
2130     }
2131 }
2132 
2133 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2134     descriptor->handle = little_endian_read_16(packet, offset);
2135     reverse_128(&packet[offset+2], descriptor->uuid128);
2136     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2137         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2138     } else {
2139         descriptor->uuid16 = 0;
2140     }
2141 }
2142 
2143 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2144     gatt_client_t * context = provide_context_for_conn_handle(con_handle);
2145     if (context == NULL) return;
2146     if (context->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2147         context->callback = callback;
2148         context->mtu_state = SEND_MTU_EXCHANGE;
2149         gatt_client_run();
2150     }
2151 }
2152 
2153 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2154     gatt_client_t * context = provide_context_for_conn_handle(con_handle);
2155     if (context == NULL) return BTSTACK_MEMORY_ALLOC_FAILED;
2156     if (context->write_without_response_callback != NULL) return GATT_CLIENT_IN_WRONG_STATE;
2157     context->write_without_response_callback = callback;
2158     att_dispatch_client_request_can_send_now_event(context->con_handle);
2159     return ERROR_CODE_SUCCESS;
2160 }
2161 
2162 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2163 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2164     gatt_client_att_packet_handler(packet_type, handle, packet, size);
2165 }
2166 #endif
2167