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