xref: /btstack/src/ble/gatt_client.c (revision 36e79bd03e5e29d1ad86f14c3d2408bbfc035a2f)
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 BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "gatt_client.c"
39 
40 #include <stdint.h>
41 #include <string.h>
42 #include <stddef.h>
43 
44 #include "btstack_config.h"
45 
46 #include "ble/att_dispatch.h"
47 #include "ble/att_db.h"
48 #include "ble/gatt_client.h"
49 #include "ble/le_device_db.h"
50 #include "ble/sm.h"
51 #include "btstack_debug.h"
52 #include "btstack_event.h"
53 #include "btstack_memory.h"
54 #include "btstack_run_loop.h"
55 #include "btstack_util.h"
56 #include "hci.h"
57 #include "hci_dump.h"
58 #include "l2cap.h"
59 #include "classic/sdp_client.h"
60 #include "bluetooth_gatt.h"
61 #include "bluetooth_sdp.h"
62 #include "classic/sdp_util.h"
63 
64 static btstack_linked_list_t gatt_client_connections;
65 static btstack_linked_list_t gatt_client_value_listeners;
66 static btstack_packet_callback_registration_t hci_event_callback_registration;
67 static btstack_packet_callback_registration_t sm_event_callback_registration;
68 
69 // GATT Client Configuration
70 static bool                 gatt_client_mtu_exchange_enabled;
71 static gap_security_level_t gatt_client_required_security_level;
72 
73 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size);
74 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
75 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code);
76 
77 #ifdef ENABLE_LE_SIGNED_WRITE
78 static void att_signed_write_handle_cmac_result(uint8_t hash[8]);
79 #endif
80 
81 #ifdef ENABLE_GATT_OVER_EATT
82 static bool gatt_client_eatt_handle_can_send_query(gatt_client_t * gatt_client);
83 #endif
84 
85 void gatt_client_init(void){
86     gatt_client_connections = NULL;
87 
88     // default configuration
89     gatt_client_mtu_exchange_enabled    = true;
90     gatt_client_required_security_level = LEVEL_0;
91 
92     // register for HCI Events
93     hci_event_callback_registration.callback = &gatt_client_event_packet_handler;
94     hci_add_event_handler(&hci_event_callback_registration);
95 
96     // register for SM Events
97     sm_event_callback_registration.callback = &gatt_client_event_packet_handler;
98     sm_add_event_handler(&sm_event_callback_registration);
99 
100     // and ATT Client PDUs
101     att_dispatch_register_client(gatt_client_att_packet_handler);
102 }
103 
104 void gatt_client_set_required_security_level(gap_security_level_t level){
105     gatt_client_required_security_level = level;
106 }
107 
108 static gatt_client_t * gatt_client_for_timer(btstack_timer_source_t * ts){
109     btstack_linked_list_iterator_t it;
110     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
111     while (btstack_linked_list_iterator_has_next(&it)){
112         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
113         if (&gatt_client->gc_timeout == ts) {
114             return gatt_client;
115         }
116     }
117     return NULL;
118 }
119 
120 static void gatt_client_timeout_handler(btstack_timer_source_t * timer){
121     gatt_client_t * gatt_client = gatt_client_for_timer(timer);
122     if (gatt_client == NULL) return;
123     log_info("GATT client timeout handle, handle 0x%02x", gatt_client->con_handle);
124     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_TIMEOUT);
125 }
126 
127 static void gatt_client_timeout_start(gatt_client_t * gatt_client){
128     log_info("GATT client timeout start, handle 0x%02x", gatt_client->con_handle);
129     btstack_run_loop_remove_timer(&gatt_client->gc_timeout);
130     btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_timeout_handler);
131     btstack_run_loop_set_timer(&gatt_client->gc_timeout, 30000); // 30 seconds sm timeout
132     btstack_run_loop_add_timer(&gatt_client->gc_timeout);
133 }
134 
135 static void gatt_client_timeout_stop(gatt_client_t * gatt_client){
136     log_info("GATT client timeout stop, handle 0x%02x", gatt_client->con_handle);
137     btstack_run_loop_remove_timer(&gatt_client->gc_timeout);
138 }
139 
140 static gap_security_level_t gatt_client_le_security_level_for_connection(hci_con_handle_t con_handle){
141     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
142     if (encryption_key_size == 0) return LEVEL_0;
143 
144     bool authenticated = gap_authenticated(con_handle);
145     if (!authenticated) return LEVEL_2;
146 
147     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
148 }
149 
150 static gatt_client_t * gatt_client_get_context_for_handle(uint16_t handle){
151     btstack_linked_item_t *it;
152     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
153         gatt_client_t * gatt_client = (gatt_client_t *) it;
154         if (gatt_client->con_handle == handle){
155             return gatt_client;
156         }
157     }
158     return NULL;
159 }
160 
161 
162 // @return gatt_client context
163 // returns existing one, or tries to setup new one
164 static uint8_t gatt_client_provide_context_for_handle(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
165     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
166 
167     if (gatt_client != NULL){
168         *out_gatt_client = gatt_client;
169         return ERROR_CODE_SUCCESS;
170     }
171 
172     // bail if no such hci connection
173     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
174     if (hci_connection == NULL){
175         log_error("No connection for handle 0x%04x", con_handle);
176         *out_gatt_client = NULL;
177         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
178     }
179 
180     gatt_client = btstack_memory_gatt_client_get();
181     if (gatt_client == NULL){
182         *out_gatt_client = NULL;
183         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
184     }
185     // init state
186     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_LE;
187     gatt_client->con_handle = con_handle;
188     gatt_client->mtu = ATT_DEFAULT_MTU;
189     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
190     if (gatt_client_mtu_exchange_enabled){
191         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
192     } else {
193         gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
194     }
195     gatt_client->gatt_client_state = P_READY;
196 #ifdef ENABLE_GATT_OVER_EATT
197     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
198 #endif
199     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
200 
201     // get unenhanced att bearer state
202     if (hci_connection->att_connection.mtu_exchanged){
203         gatt_client->mtu = hci_connection->att_connection.mtu;
204         gatt_client->mtu_state = MTU_EXCHANGED;
205     }
206     *out_gatt_client = gatt_client;
207     return ERROR_CODE_SUCCESS;
208 }
209 
210 static bool is_ready(gatt_client_t * gatt_client){
211     return gatt_client->gatt_client_state == P_READY;
212 }
213 
214 static uint8_t gatt_client_provide_context_for_request(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
215     gatt_client_t * gatt_client = NULL;
216     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
217     if (status != ERROR_CODE_SUCCESS){
218         return status;
219     }
220 
221     if (is_ready(gatt_client) == 0){
222         return GATT_CLIENT_IN_WRONG_STATE;
223     }
224 
225     gatt_client_timeout_start(gatt_client);
226 
227     *out_gatt_client = gatt_client;
228 
229     return status;
230 }
231 
232 int gatt_client_is_ready(hci_con_handle_t con_handle){
233     gatt_client_t * gatt_client;
234     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
235     if (status != ERROR_CODE_SUCCESS){
236         return 0;
237     }
238     return is_ready(gatt_client) ? 1 : 0;
239 }
240 
241 void gatt_client_mtu_enable_auto_negotiation(uint8_t enabled){
242     gatt_client_mtu_exchange_enabled = enabled != 0;
243 }
244 
245 uint8_t gatt_client_get_mtu(hci_con_handle_t con_handle, uint16_t * mtu){
246     gatt_client_t * gatt_client;
247     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
248     if (status != ERROR_CODE_SUCCESS){
249         return status;
250     }
251 
252     if ((gatt_client->mtu_state == MTU_EXCHANGED) || (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED)){
253         *mtu = gatt_client->mtu;
254         return ERROR_CODE_SUCCESS;
255     }
256     *mtu = ATT_DEFAULT_MTU;
257     return GATT_CLIENT_IN_WRONG_STATE;
258 }
259 
260 static uint8_t *gatt_client_reserve_request_buffer(gatt_client_t *gatt_client) {
261     l2cap_reserve_packet_buffer();
262     return l2cap_get_outgoing_buffer();
263 }
264 
265 // precondition: can_send_packet_now == TRUE
266 static uint8_t gatt_client_send(gatt_client_t * gatt_client, uint16_t len){
267     switch (gatt_client->bearer_type){
268         case ATT_BEARER_UNENHANCED_LE:
269             return l2cap_send_prepared_connectionless(gatt_client->con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, len);
270 #ifdef ENABLE_GATT_OVER_CLASSIC
271         case ATT_BEARER_UNENHANCED_CLASSIC:
272             return l2cap_send_prepared(gatt_client->l2cap_cid, len);
273 #endif
274         default:
275             btstack_unreachable();
276             return ERROR_CODE_HARDWARE_FAILURE;
277     }
278 }
279 
280 // precondition: can_send_packet_now == TRUE
281 static uint8_t att_confirmation(gatt_client_t * gatt_client) {
282     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
283 
284     request[0] = ATT_HANDLE_VALUE_CONFIRMATION;
285 
286     return gatt_client_send(gatt_client, 1);
287 }
288 
289 // precondition: can_send_packet_now == TRUE
290 static uint8_t att_find_information_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t start_handle,
291                                             uint16_t end_handle) {
292     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
293 
294     request[0] = request_type;
295     little_endian_store_16(request, 1, start_handle);
296     little_endian_store_16(request, 3, end_handle);
297 
298     return gatt_client_send(gatt_client, 5);
299 }
300 
301 // precondition: can_send_packet_now == TRUE
302 static uint8_t
303 att_find_by_type_value_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_group_type,
304                                uint16_t start_handle, uint16_t end_handle, uint8_t *value, uint16_t value_size) {
305     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
306     request[0] = request_type;
307 
308     little_endian_store_16(request, 1, start_handle);
309     little_endian_store_16(request, 3, end_handle);
310     little_endian_store_16(request, 5, attribute_group_type);
311     (void)memcpy(&request[7], value, value_size);
312 
313     return gatt_client_send(gatt_client, 7u + value_size);
314 }
315 
316 // precondition: can_send_packet_now == TRUE
317 static uint8_t
318 att_read_by_type_or_group_request_for_uuid16(gatt_client_t *gatt_client, uint8_t request_type, uint16_t uuid16,
319                                              uint16_t start_handle, uint16_t end_handle) {
320     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
321 
322     request[0] = request_type;
323     little_endian_store_16(request, 1, start_handle);
324     little_endian_store_16(request, 3, end_handle);
325     little_endian_store_16(request, 5, uuid16);
326 
327     return gatt_client_send(gatt_client, 7);
328 }
329 
330 // precondition: can_send_packet_now == TRUE
331 static uint8_t
332 att_read_by_type_or_group_request_for_uuid128(gatt_client_t *gatt_client, uint8_t request_type, const uint8_t *uuid128,
333                                               uint16_t start_handle, uint16_t end_handle) {
334     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
335 
336     request[0] = request_type;
337     little_endian_store_16(request, 1, start_handle);
338     little_endian_store_16(request, 3, end_handle);
339     reverse_128(uuid128, &request[5]);
340 
341     return gatt_client_send(gatt_client, 21);
342 }
343 
344 // precondition: can_send_packet_now == TRUE
345 static uint8_t att_read_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_handle) {
346     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
347 
348     request[0] = request_type;
349     little_endian_store_16(request, 1, attribute_handle);
350 
351     return gatt_client_send(gatt_client, 3);
352 }
353 
354 // precondition: can_send_packet_now == TRUE
355 static uint8_t att_read_blob_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_handle,
356                                      uint16_t value_offset) {
357     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
358 
359     request[0] = request_type;
360     little_endian_store_16(request, 1, attribute_handle);
361     little_endian_store_16(request, 3, value_offset);
362 
363     return gatt_client_send(gatt_client, 5);
364 }
365 
366 static uint8_t
367 att_read_multiple_request(gatt_client_t *gatt_client, uint16_t num_value_handles, uint16_t *value_handles) {
368     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
369 
370     request[0] = ATT_READ_MULTIPLE_REQUEST;
371     uint16_t i;
372     uint16_t offset = 1;
373     for (i=0;i<num_value_handles;i++){
374         little_endian_store_16(request, offset, value_handles[i]);
375         offset += 2;
376     }
377 
378     return gatt_client_send(gatt_client, offset);
379 }
380 
381 #ifdef ENABLE_LE_SIGNED_WRITE
382 // precondition: can_send_packet_now == TRUE
383 static uint8_t att_signed_write_request(gatt_client_t *gatt_client, uint16_t request_type, uint16_t attribute_handle,
384                                         uint16_t value_length, uint8_t *value, uint32_t sign_counter, uint8_t sgn[8]) {
385     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
386 
387     request[0] = request_type;
388     little_endian_store_16(request, 1, attribute_handle);
389     (void)memcpy(&request[3], value, value_length);
390     little_endian_store_32(request, 3 + value_length, sign_counter);
391     reverse_64(sgn, &request[3 + value_length + 4]);
392 
393     return gatt_client_send(gatt_client, 3 + value_length + 12);
394 }
395 #endif
396 
397 // precondition: can_send_packet_now == TRUE
398 static uint8_t
399 att_write_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_handle, uint16_t value_length,
400                   uint8_t *value) {
401     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
402 
403     request[0] = request_type;
404     little_endian_store_16(request, 1, attribute_handle);
405     (void)memcpy(&request[3], value, value_length);
406 
407     return gatt_client_send(gatt_client, 3u + value_length);
408 }
409 
410 // precondition: can_send_packet_now == TRUE
411 static uint8_t att_execute_write_request(gatt_client_t *gatt_client, uint8_t request_type, uint8_t execute_write) {
412     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
413 
414     request[0] = request_type;
415     request[1] = execute_write;
416 
417     return gatt_client_send(gatt_client, 2);
418 }
419 
420 // precondition: can_send_packet_now == TRUE
421 static uint8_t att_prepare_write_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_handle,
422                                          uint16_t value_offset, uint16_t blob_length, uint8_t *value) {
423     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
424 
425     request[0] = request_type;
426     little_endian_store_16(request, 1, attribute_handle);
427     little_endian_store_16(request, 3, value_offset);
428     (void)memcpy(&request[5], &value[value_offset], blob_length);
429 
430     return gatt_client_send(gatt_client,  5u + blob_length);
431 }
432 
433 static uint8_t att_exchange_mtu_request(gatt_client_t *gatt_client) {
434     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
435 
436     request[0] = ATT_EXCHANGE_MTU_REQUEST;
437     uint16_t mtu = l2cap_max_le_mtu();
438     little_endian_store_16(request, 1, mtu);
439 
440     return gatt_client_send(gatt_client, 3);
441 }
442 
443 static uint16_t write_blob_length(gatt_client_t * gatt_client){
444     uint16_t max_blob_length = gatt_client->mtu - 5u;
445     if (gatt_client->attribute_offset >= gatt_client->attribute_length) {
446         return 0;
447     }
448     uint16_t rest_length = gatt_client->attribute_length - gatt_client->attribute_offset;
449     if (max_blob_length > rest_length){
450         return rest_length;
451     }
452     return max_blob_length;
453 }
454 
455 static void send_gatt_services_request(gatt_client_t *gatt_client){
456     att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_GROUP_TYPE_REQUEST,
457                                                  gatt_client->uuid16, gatt_client->start_group_handle,
458                                                  gatt_client->end_group_handle);
459 }
460 
461 static void send_gatt_by_uuid_request(gatt_client_t *gatt_client, uint16_t attribute_group_type){
462     if (gatt_client->uuid16){
463         uint8_t uuid16[2];
464         little_endian_store_16(uuid16, 0, gatt_client->uuid16);
465         att_find_by_type_value_request(gatt_client, ATT_FIND_BY_TYPE_VALUE_REQUEST, attribute_group_type,
466                                        gatt_client->start_group_handle, gatt_client->end_group_handle, uuid16, 2);
467         return;
468     }
469     uint8_t uuid128[16];
470     reverse_128(gatt_client->uuid128, uuid128);
471     att_find_by_type_value_request(gatt_client, ATT_FIND_BY_TYPE_VALUE_REQUEST, attribute_group_type,
472                                    gatt_client->start_group_handle, gatt_client->end_group_handle, uuid128, 16);
473 }
474 
475 static void send_gatt_services_by_uuid_request(gatt_client_t *gatt_client){
476     send_gatt_by_uuid_request(gatt_client, GATT_PRIMARY_SERVICE_UUID);
477 }
478 
479 static void send_gatt_included_service_uuid_request(gatt_client_t *gatt_client){
480     att_read_request(gatt_client, ATT_READ_REQUEST, gatt_client->query_start_handle);
481 }
482 
483 static void send_gatt_included_service_request(gatt_client_t *gatt_client){
484     att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_TYPE_REQUEST,
485                                                  GATT_INCLUDE_SERVICE_UUID, gatt_client->start_group_handle,
486                                                  gatt_client->end_group_handle);
487 }
488 
489 static void send_gatt_characteristic_request(gatt_client_t *gatt_client){
490     att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_TYPE_REQUEST,
491                                                  GATT_CHARACTERISTICS_UUID, gatt_client->start_group_handle,
492                                                  gatt_client->end_group_handle);
493 }
494 
495 static void send_gatt_characteristic_descriptor_request(gatt_client_t *gatt_client){
496     att_find_information_request(gatt_client, ATT_FIND_INFORMATION_REQUEST, gatt_client->start_group_handle,
497                                  gatt_client->end_group_handle);
498 }
499 
500 static void send_gatt_read_characteristic_value_request(gatt_client_t *gatt_client){
501     att_read_request(gatt_client, ATT_READ_REQUEST, gatt_client->attribute_handle);
502 }
503 
504 static void send_gatt_read_by_type_request(gatt_client_t * gatt_client){
505     if (gatt_client->uuid16){
506         att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_TYPE_REQUEST,
507                                                      gatt_client->uuid16, gatt_client->start_group_handle,
508                                                      gatt_client->end_group_handle);
509     } else {
510         att_read_by_type_or_group_request_for_uuid128(gatt_client, ATT_READ_BY_TYPE_REQUEST,
511                                                       gatt_client->uuid128, gatt_client->start_group_handle,
512                                                       gatt_client->end_group_handle);
513     }
514 }
515 
516 static void send_gatt_read_blob_request(gatt_client_t *gatt_client){
517     if (gatt_client->attribute_offset == 0){
518         att_read_request(gatt_client, ATT_READ_REQUEST, gatt_client->attribute_handle);
519     } else {
520         att_read_blob_request(gatt_client, ATT_READ_BLOB_REQUEST, gatt_client->attribute_handle,
521                               gatt_client->attribute_offset);
522     }
523 }
524 
525 static void send_gatt_read_multiple_request(gatt_client_t * gatt_client){
526     att_read_multiple_request(gatt_client, gatt_client->read_multiple_handle_count, gatt_client->read_multiple_handles);
527 }
528 
529 static void send_gatt_write_attribute_value_request(gatt_client_t * gatt_client){
530     att_write_request(gatt_client, ATT_WRITE_REQUEST, gatt_client->attribute_handle, gatt_client->attribute_length,
531                       gatt_client->attribute_value);
532 }
533 
534 static void send_gatt_write_client_characteristic_configuration_request(gatt_client_t * gatt_client){
535     att_write_request(gatt_client, ATT_WRITE_REQUEST, gatt_client->client_characteristic_configuration_handle, 2,
536                       gatt_client->client_characteristic_configuration_value);
537 }
538 
539 static void send_gatt_prepare_write_request(gatt_client_t * gatt_client){
540     att_prepare_write_request(gatt_client, ATT_PREPARE_WRITE_REQUEST, gatt_client->attribute_handle,
541                               gatt_client->attribute_offset, write_blob_length(gatt_client),
542                               gatt_client->attribute_value);
543 }
544 
545 static void send_gatt_execute_write_request(gatt_client_t * gatt_client){
546     att_execute_write_request(gatt_client, ATT_EXECUTE_WRITE_REQUEST, 1);
547 }
548 
549 static void send_gatt_cancel_prepared_write_request(gatt_client_t * gatt_client){
550     att_execute_write_request(gatt_client, ATT_EXECUTE_WRITE_REQUEST, 0);
551 }
552 
553 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
554 static void send_gatt_read_client_characteristic_configuration_request(gatt_client_t * gatt_client){
555     att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_TYPE_REQUEST,
556                                                  GATT_CLIENT_CHARACTERISTICS_CONFIGURATION,
557                                                  gatt_client->start_group_handle, gatt_client->end_group_handle);
558 }
559 #endif
560 
561 static void send_gatt_read_characteristic_descriptor_request(gatt_client_t * gatt_client){
562     att_read_request(gatt_client, ATT_READ_REQUEST, gatt_client->attribute_handle);
563 }
564 
565 #ifdef ENABLE_LE_SIGNED_WRITE
566 static void send_gatt_signed_write_request(gatt_client_t * gatt_client, uint32_t sign_counter){
567     att_signed_write_request(gatt_client, ATT_SIGNED_WRITE_COMMAND, gatt_client->attribute_handle,
568                              gatt_client->attribute_length, gatt_client->attribute_value, sign_counter,
569                              gatt_client->cmac);
570 }
571 #endif
572 
573 static uint16_t get_last_result_handle_from_service_list(uint8_t * packet, uint16_t size){
574     if (size < 2) return 0xffff;
575     uint8_t attr_length = packet[1];
576     if ((2 + attr_length) > size) return 0xffff;
577     return little_endian_read_16(packet, size - attr_length + 2u);
578 }
579 
580 static uint16_t get_last_result_handle_from_characteristics_list(uint8_t * packet, uint16_t size){
581     if (size < 2) return 0xffff;
582     uint8_t attr_length = packet[1];
583     if ((2 + attr_length) > size) return 0xffff;
584     return little_endian_read_16(packet, size - attr_length + 3u);
585 }
586 
587 static uint16_t get_last_result_handle_from_included_services_list(uint8_t * packet, uint16_t size){
588     if (size < 2) return 0xffff;
589     uint8_t attr_length = packet[1];
590     if ((2 + attr_length) > size) return 0xffff;
591     return little_endian_read_16(packet, size - attr_length);
592 }
593 
594 static void gatt_client_notify_can_send_query(gatt_client_t * gatt_client){
595     while (gatt_client->gatt_client_state == P_READY){
596 #ifdef ENABLE_GATT_OVER_EATT
597         bool query_sent = gatt_client_eatt_handle_can_send_query(gatt_client);
598         if (query_sent){
599             continue;
600         }
601 #endif
602         btstack_context_callback_registration_t * callback = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->query_requests);
603         if (callback == NULL) {
604             return;
605         }
606         (*callback->callback)(callback->context);
607     }
608 }
609 
610 static void gatt_client_handle_transaction_complete(gatt_client_t * gatt_client){
611     gatt_client->gatt_client_state = P_READY;
612     gatt_client_timeout_stop(gatt_client);
613     gatt_client_notify_can_send_query(gatt_client);
614 }
615 
616 static void emit_event_new(btstack_packet_handler_t callback, uint8_t * packet, uint16_t size){
617     if (!callback) return;
618     hci_dump_packet(HCI_EVENT_PACKET, 1, packet, size);
619     (*callback)(HCI_EVENT_PACKET, 0, packet, size);
620 }
621 
622 void gatt_client_listen_for_characteristic_value_updates(gatt_client_notification_t * notification, btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
623     notification->callback = callback;
624     notification->con_handle = con_handle;
625     if (characteristic == NULL){
626         notification->attribute_handle = GATT_CLIENT_ANY_VALUE_HANDLE;
627     } else {
628         notification->attribute_handle = characteristic->value_handle;
629     }
630     btstack_linked_list_add(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
631 }
632 
633 void gatt_client_stop_listening_for_characteristic_value_updates(gatt_client_notification_t * notification){
634     btstack_linked_list_remove(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
635 }
636 
637 static void emit_event_to_registered_listeners(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t * packet, uint16_t size){
638     btstack_linked_list_iterator_t it;
639     btstack_linked_list_iterator_init(&it, &gatt_client_value_listeners);
640     while (btstack_linked_list_iterator_has_next(&it)){
641         gatt_client_notification_t * notification = (gatt_client_notification_t*) btstack_linked_list_iterator_next(&it);
642         if ((notification->con_handle       != GATT_CLIENT_ANY_CONNECTION)   && (notification->con_handle       != con_handle)) continue;
643         if ((notification->attribute_handle != GATT_CLIENT_ANY_VALUE_HANDLE) && (notification->attribute_handle != attribute_handle)) continue;
644         (*notification->callback)(HCI_EVENT_PACKET, 0, packet, size);
645     }
646 }
647 
648 static void emit_gatt_complete_event(gatt_client_t * gatt_client, uint8_t att_status){
649     // @format H1
650     uint8_t packet[5];
651     packet[0] = GATT_EVENT_QUERY_COMPLETE;
652     packet[1] = 3;
653     little_endian_store_16(packet, 2, gatt_client->con_handle);
654     packet[4] = att_status;
655     emit_event_new(gatt_client->callback, packet, sizeof(packet));
656 }
657 
658 static void emit_gatt_service_query_result_event(gatt_client_t * gatt_client, uint16_t start_group_handle, uint16_t end_group_handle, const uint8_t * uuid128){
659     // @format HX
660     uint8_t packet[24];
661     packet[0] = GATT_EVENT_SERVICE_QUERY_RESULT;
662     packet[1] = sizeof(packet) - 2u;
663     little_endian_store_16(packet, 2, gatt_client->con_handle);
664     ///
665     little_endian_store_16(packet, 4, start_group_handle);
666     little_endian_store_16(packet, 6, end_group_handle);
667     reverse_128(uuid128, &packet[8]);
668     emit_event_new(gatt_client->callback, packet, sizeof(packet));
669 }
670 
671 static void emit_gatt_included_service_query_result_event(gatt_client_t * gatt_client, uint16_t include_handle, uint16_t start_group_handle, uint16_t end_group_handle, const uint8_t * uuid128){
672     // @format HX
673     uint8_t packet[26];
674     packet[0] = GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT;
675     packet[1] = sizeof(packet) - 2u;
676     little_endian_store_16(packet, 2, gatt_client->con_handle);
677     ///
678     little_endian_store_16(packet, 4, include_handle);
679     //
680     little_endian_store_16(packet, 6, start_group_handle);
681     little_endian_store_16(packet, 8, end_group_handle);
682     reverse_128(uuid128, &packet[10]);
683     emit_event_new(gatt_client->callback, packet, sizeof(packet));
684 }
685 
686 static void emit_gatt_characteristic_query_result_event(gatt_client_t * gatt_client, uint16_t start_handle, uint16_t value_handle, uint16_t end_handle,
687                                                         uint16_t properties, const uint8_t * uuid128){
688     // @format HY
689     uint8_t packet[28];
690     packet[0] = GATT_EVENT_CHARACTERISTIC_QUERY_RESULT;
691     packet[1] = sizeof(packet) - 2u;
692     little_endian_store_16(packet, 2, gatt_client->con_handle);
693     ///
694     little_endian_store_16(packet, 4,  start_handle);
695     little_endian_store_16(packet, 6,  value_handle);
696     little_endian_store_16(packet, 8,  end_handle);
697     little_endian_store_16(packet, 10, properties);
698     reverse_128(uuid128, &packet[12]);
699     emit_event_new(gatt_client->callback, packet, sizeof(packet));
700 }
701 
702 static void emit_gatt_all_characteristic_descriptors_result_event(
703         gatt_client_t * gatt_client, uint16_t descriptor_handle, const uint8_t * uuid128){
704     // @format HZ
705     uint8_t packet[22];
706     packet[0] = GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT;
707     packet[1] = sizeof(packet) - 2u;
708     little_endian_store_16(packet, 2, gatt_client->con_handle);
709     ///
710     little_endian_store_16(packet, 4,  descriptor_handle);
711     reverse_128(uuid128, &packet[6]);
712     emit_event_new(gatt_client->callback, packet, sizeof(packet));
713 }
714 
715 static void emit_gatt_mtu_exchanged_result_event(gatt_client_t * gatt_client, uint16_t new_mtu){
716     // @format H2
717     uint8_t packet[6];
718     packet[0] = GATT_EVENT_MTU;
719     packet[1] = sizeof(packet) - 2u;
720     little_endian_store_16(packet, 2, gatt_client->con_handle);
721     little_endian_store_16(packet, 4, new_mtu);
722     att_dispatch_client_mtu_exchanged(gatt_client->con_handle, new_mtu);
723     emit_event_new(gatt_client->callback, packet, sizeof(packet));
724 }
725 ///
726 static void report_gatt_services(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
727     if (size < 2) return;
728     uint8_t attr_length = packet[1];
729     uint8_t uuid_length = attr_length - 4u;
730 
731     int i;
732     for (i = 2; (i+attr_length) <= size; i += attr_length){
733         uint16_t start_group_handle = little_endian_read_16(packet,i);
734         uint16_t end_group_handle   = little_endian_read_16(packet,i+2);
735         uint8_t  uuid128[16];
736         uint16_t uuid16 = 0;
737 
738         if (uuid_length == 2u){
739             uuid16 = little_endian_read_16(packet, i+4);
740             uuid_add_bluetooth_prefix((uint8_t*) &uuid128, uuid16);
741         } else if (uuid_length == 16u) {
742             reverse_128(&packet[i+4], uuid128);
743         } else {
744             return;
745         }
746         emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle, uuid128);
747     }
748 }
749 
750 // helper
751 static void characteristic_start_found(gatt_client_t * gatt_client, uint16_t start_handle, uint8_t properties, uint16_t value_handle, uint8_t * uuid, uint16_t uuid_length){
752     uint8_t uuid128[16];
753     uint16_t uuid16 = 0;
754     if (uuid_length == 2u){
755         uuid16 = little_endian_read_16(uuid, 0);
756         uuid_add_bluetooth_prefix((uint8_t*) uuid128, uuid16);
757     } else if (uuid_length == 16u){
758         reverse_128(uuid, uuid128);
759     } else {
760         return;
761     }
762 
763     if (gatt_client->filter_with_uuid && (memcmp(gatt_client->uuid128, uuid128, 16) != 0)) return;
764 
765     gatt_client->characteristic_properties = properties;
766     gatt_client->characteristic_start_handle = start_handle;
767     gatt_client->attribute_handle = value_handle;
768 
769     if (gatt_client->filter_with_uuid) return;
770 
771     gatt_client->uuid16 = uuid16;
772     (void)memcpy(gatt_client->uuid128, uuid128, 16);
773 }
774 
775 static void characteristic_end_found(gatt_client_t * gatt_client, uint16_t end_handle){
776     // TODO: stop searching if filter and uuid found
777 
778     if (!gatt_client->characteristic_start_handle) return;
779 
780     emit_gatt_characteristic_query_result_event(gatt_client, gatt_client->characteristic_start_handle, gatt_client->attribute_handle,
781                                                 end_handle, gatt_client->characteristic_properties, gatt_client->uuid128);
782 
783     gatt_client->characteristic_start_handle = 0;
784 }
785 
786 static void report_gatt_characteristics(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
787     if (size < 2u) return;
788     uint8_t attr_length = packet[1];
789     if ((attr_length != 7u) && (attr_length != 21u)) return;
790     uint8_t uuid_length = attr_length - 5u;
791     int i;
792     for (i = 2u; (i + attr_length) <= size; i += attr_length){
793         uint16_t start_handle = little_endian_read_16(packet, i);
794         uint8_t  properties = packet[i+2];
795         uint16_t value_handle = little_endian_read_16(packet, i+3);
796         characteristic_end_found(gatt_client, start_handle - 1u);
797         characteristic_start_found(gatt_client, start_handle, properties, value_handle, &packet[i + 5], uuid_length);
798     }
799 }
800 
801 static void report_gatt_included_service_uuid16(gatt_client_t * gatt_client, uint16_t include_handle, uint16_t uuid16){
802     uint8_t normalized_uuid128[16];
803     uuid_add_bluetooth_prefix(normalized_uuid128, uuid16);
804     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
805                                                   gatt_client->query_end_handle, normalized_uuid128);
806 }
807 
808 static void report_gatt_included_service_uuid128(gatt_client_t * gatt_client, uint16_t include_handle, const uint8_t * uuid128){
809     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
810                                                   gatt_client->query_end_handle, uuid128);
811 }
812 
813 // @return packet pointer
814 // @note assume that value is part of an l2cap buffer - overwrite HCI + L2CAP packet headers
815 static const int characteristic_value_event_header_size = 8;
816 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){
817 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
818     // copy value into test packet for testing
819     static uint8_t packet[1000];
820     memcpy(&packet[8], value, length);
821 #else
822     // before the value inside the ATT PDU
823     uint8_t * packet = value - characteristic_value_event_header_size;
824 #endif
825     packet[0] = type;
826     packet[1] = characteristic_value_event_header_size - 2 + length;
827     little_endian_store_16(packet, 2, con_handle);
828     little_endian_store_16(packet, 4, attribute_handle);
829     little_endian_store_16(packet, 6, length);
830     return packet;
831 }
832 
833 // @return packet pointer
834 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
835 static const int long_characteristic_value_event_header_size = 10;
836 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){
837 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
838     // avoid using pre ATT headers.
839     return NULL;
840 #endif
841 #if defined(HCI_INCOMING_PRE_BUFFER_SIZE) && (HCI_INCOMING_PRE_BUFFER_SIZE >= 10 - 8) // L2CAP Header (4) - ACL Header (4)
842     // before the value inside the ATT PDU
843     uint8_t * packet = value - long_characteristic_value_event_header_size;
844     packet[0] = type;
845     packet[1] = long_characteristic_value_event_header_size - 2 + length;
846     little_endian_store_16(packet, 2, con_handle);
847     little_endian_store_16(packet, 4, attribute_handle);
848     little_endian_store_16(packet, 6, offset);
849     little_endian_store_16(packet, 8, length);
850     return packet;
851 #else
852     log_error("HCI_INCOMING_PRE_BUFFER_SIZE >= 2 required for long characteristic reads");
853     return NULL;
854 #endif
855 }
856 
857 // test if notification/indication should be delivered to application (BLESA)
858 static bool gatt_client_accept_server_message(gatt_client_t *gatt_client) {
859 #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
860 	// ignore messages until re-encryption is complete
861     if (gap_reconnect_security_setup_active(gatt_client->con_handle)) return false;
862 
863 	// after that ignore if bonded but not encrypted
864 	return !gap_bonded(gatt_client->con_handle) || (gap_encryption_key_size(gatt_client->con_handle) > 0);
865 #else
866     UNUSED(gatt_client);
867 	return true;
868 #endif
869 }
870 
871 
872 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
873 static void report_gatt_notification(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
874 	if (!gatt_client_accept_server_message(gatt_client)) return;
875     uint8_t * packet = setup_characteristic_value_packet(GATT_EVENT_NOTIFICATION, gatt_client->con_handle, value_handle, value, length);
876     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, characteristic_value_event_header_size + length);
877 }
878 
879 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
880 static void report_gatt_indication(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
881 	if (!gatt_client_accept_server_message(gatt_client)) return;
882     uint8_t * packet = setup_characteristic_value_packet(GATT_EVENT_INDICATION, gatt_client->con_handle, value_handle, value, length);
883     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, characteristic_value_event_header_size + length);
884 }
885 
886 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
887 static void report_gatt_characteristic_value(gatt_client_t * gatt_client, uint16_t attribute_handle, uint8_t * value, uint16_t length){
888     uint8_t * packet = setup_characteristic_value_packet(GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT, gatt_client->con_handle, attribute_handle, value, length);
889     emit_event_new(gatt_client->callback, packet, characteristic_value_event_header_size + length);
890 }
891 
892 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
893 static void report_gatt_long_characteristic_value_blob(gatt_client_t * gatt_client, uint16_t attribute_handle, uint8_t * blob, uint16_t blob_length, int value_offset){
894     uint8_t * packet = setup_long_characteristic_value_packet(GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT, gatt_client->con_handle, attribute_handle, value_offset, blob, blob_length);
895     if (!packet) return;
896     emit_event_new(gatt_client->callback, packet, blob_length + long_characteristic_value_event_header_size);
897 }
898 
899 static void report_gatt_characteristic_descriptor(gatt_client_t * gatt_client, uint16_t descriptor_handle, uint8_t *value, uint16_t value_length, uint16_t value_offset){
900     UNUSED(value_offset);
901     uint8_t * packet = setup_characteristic_value_packet(GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT, gatt_client->con_handle, descriptor_handle, value, value_length);
902     emit_event_new(gatt_client->callback, packet, value_length + 8u);
903 }
904 
905 static void report_gatt_long_characteristic_descriptor(gatt_client_t * gatt_client, uint16_t descriptor_handle, uint8_t *blob, uint16_t blob_length, uint16_t value_offset){
906     uint8_t * packet = setup_long_characteristic_value_packet(GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT, gatt_client->con_handle, descriptor_handle, value_offset, blob, blob_length);
907     if (!packet) return;
908     emit_event_new(gatt_client->callback, packet, blob_length + long_characteristic_value_event_header_size);
909 }
910 
911 static void report_gatt_all_characteristic_descriptors(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size, uint16_t pair_size){
912     int i;
913     for (i = 0u; (i + pair_size) <= size; i += pair_size){
914         uint16_t descriptor_handle = little_endian_read_16(packet,i);
915         uint8_t uuid128[16];
916         uint16_t uuid16 = 0;
917         if (pair_size == 4u){
918             uuid16 = little_endian_read_16(packet,i+2);
919             uuid_add_bluetooth_prefix(uuid128, uuid16);
920         } else {
921             reverse_128(&packet[i+2], uuid128);
922         }
923         emit_gatt_all_characteristic_descriptors_result_event(gatt_client, descriptor_handle, uuid128);
924     }
925 
926 }
927 
928 static int is_query_done(gatt_client_t * gatt_client, uint16_t last_result_handle){
929     return last_result_handle >= gatt_client->end_group_handle;
930 }
931 
932 static void trigger_next_query(gatt_client_t * gatt_client, uint16_t last_result_handle, gatt_client_state_t next_query_state){
933     if (is_query_done(gatt_client, last_result_handle)){
934         gatt_client_handle_transaction_complete(gatt_client);
935         emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
936         return;
937     }
938     // next
939     gatt_client->start_group_handle = last_result_handle + 1u;
940     gatt_client->gatt_client_state = next_query_state;
941 }
942 
943 static void trigger_next_included_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
944     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_INCLUDED_SERVICE_QUERY);
945 }
946 
947 static void trigger_next_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
948     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_QUERY);
949 }
950 
951 static void trigger_next_service_by_uuid_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
952     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_WITH_UUID_QUERY);
953 }
954 
955 static void trigger_next_characteristic_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
956     if (is_query_done(gatt_client, last_result_handle)){
957         // report last characteristic
958         characteristic_end_found(gatt_client, gatt_client->end_group_handle);
959     }
960     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY);
961 }
962 
963 static void trigger_next_characteristic_descriptor_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
964     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY);
965 }
966 
967 static void trigger_next_read_by_type_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
968     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_READ_BY_TYPE_REQUEST);
969 }
970 
971 static void trigger_next_prepare_write_query(gatt_client_t * gatt_client, gatt_client_state_t next_query_state, gatt_client_state_t done_state){
972     gatt_client->attribute_offset += write_blob_length(gatt_client);
973     uint16_t next_blob_length =  write_blob_length(gatt_client);
974 
975     if (next_blob_length == 0u){
976         gatt_client->gatt_client_state = done_state;
977         return;
978     }
979     gatt_client->gatt_client_state = next_query_state;
980 }
981 
982 static void trigger_next_blob_query(gatt_client_t * gatt_client, gatt_client_state_t next_query_state, uint16_t received_blob_length){
983 
984     uint16_t max_blob_length = gatt_client->mtu - 1u;
985     if (received_blob_length < max_blob_length){
986         gatt_client_handle_transaction_complete(gatt_client);
987         emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
988         return;
989     }
990 
991     gatt_client->attribute_offset += received_blob_length;
992     gatt_client->gatt_client_state = next_query_state;
993 }
994 
995 
996 static int is_value_valid(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size){
997     uint16_t attribute_handle = little_endian_read_16(packet, 1);
998     uint16_t value_offset = little_endian_read_16(packet, 3);
999 
1000     if (gatt_client->attribute_handle != attribute_handle) return 0;
1001     if (gatt_client->attribute_offset != value_offset) return 0;
1002     return memcmp(&gatt_client->attribute_value[gatt_client->attribute_offset], &packet[5], size - 5u) == 0u;
1003 }
1004 
1005 #ifdef ENABLE_LE_SIGNED_WRITE
1006 static void gatt_client_run_for_client_start_signed_write(gatt_client_t *gatt_client) {
1007     sm_key_t csrk;
1008     le_device_db_local_csrk_get(gatt_client->le_device_index, csrk);
1009     uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1010     gatt_client->gatt_client_state = P_W4_CMAC_RESULT;
1011     sm_cmac_signed_write_start(csrk, ATT_SIGNED_WRITE_COMMAND, gatt_client->attribute_handle, gatt_client->attribute_length, gatt_client->attribute_value, sign_counter, att_signed_write_handle_cmac_result);
1012 }
1013 #endif
1014 
1015 // returns true if packet was sent
1016 static bool gatt_client_run_for_gatt_client(gatt_client_t * gatt_client){
1017 
1018     // wait until re-encryption is complete
1019     if (gap_reconnect_security_setup_active(gatt_client->con_handle)) return false;
1020 
1021     // wait until re-encryption is complete
1022     if (gatt_client->reencryption_active) return false;
1023 
1024     // wait until pairing complete (either reactive authentication or due to required security level)
1025     if (gatt_client->wait_for_authentication_complete) return false;
1026 
1027     bool client_request_pending = gatt_client->gatt_client_state != P_READY;
1028 
1029     // verify security level for Mandatory Authentication over LE
1030     bool check_security;
1031     switch (gatt_client->bearer_type){
1032         case ATT_BEARER_UNENHANCED_LE:
1033             check_security = true;
1034             break;
1035         default:
1036             check_security = false;
1037             break;
1038     }
1039     if (client_request_pending && (gatt_client_required_security_level > gatt_client->security_level) && check_security){
1040         log_info("Trigger pairing, current security level %u, required %u\n", gatt_client->security_level, gatt_client_required_security_level);
1041         gatt_client->wait_for_authentication_complete = 1;
1042         // set att error code for pairing failure based on required level
1043         switch (gatt_client_required_security_level){
1044             case LEVEL_4:
1045             case LEVEL_3:
1046                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
1047                 break;
1048             default:
1049                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_ENCRYPTION;
1050                 break;
1051         }
1052         sm_request_pairing(gatt_client->con_handle);
1053         // sm probably just sent a pdu
1054         return true;
1055     }
1056 
1057     switch (gatt_client->mtu_state) {
1058         case SEND_MTU_EXCHANGE:
1059             gatt_client->mtu_state = SENT_MTU_EXCHANGE;
1060             att_exchange_mtu_request(gatt_client);
1061             return true;
1062         case SENT_MTU_EXCHANGE:
1063             return false;
1064         default:
1065             break;
1066     }
1067 
1068     if (gatt_client->send_confirmation){
1069         gatt_client->send_confirmation = 0;
1070         att_confirmation(gatt_client);
1071         return true;
1072     }
1073 
1074     // check MTU for writes
1075     switch (gatt_client->gatt_client_state){
1076         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1077         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1078             if (gatt_client->attribute_length <= (gatt_client->mtu - 3u)) break;
1079             log_error("gatt_client_run: value len %u > MTU %u - 3\n", gatt_client->attribute_length,gatt_client->mtu);
1080             gatt_client_handle_transaction_complete(gatt_client);
1081             emit_gatt_complete_event(gatt_client, ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH);
1082             return false;
1083         default:
1084             break;
1085     }
1086 
1087     bool packet_sent = true;
1088     bool done = true;
1089     switch (gatt_client->gatt_client_state){
1090         case P_W2_SEND_SERVICE_QUERY:
1091             gatt_client->gatt_client_state = P_W4_SERVICE_QUERY_RESULT;
1092             send_gatt_services_request(gatt_client);
1093             break;
1094 
1095         case P_W2_SEND_SERVICE_WITH_UUID_QUERY:
1096             gatt_client->gatt_client_state = P_W4_SERVICE_WITH_UUID_RESULT;
1097             send_gatt_services_by_uuid_request(gatt_client);
1098             break;
1099 
1100         case P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY:
1101             gatt_client->gatt_client_state = P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT;
1102             send_gatt_characteristic_request(gatt_client);
1103             break;
1104 
1105         case P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY:
1106             gatt_client->gatt_client_state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1107             send_gatt_characteristic_request(gatt_client);
1108             break;
1109 
1110         case P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY:
1111             gatt_client->gatt_client_state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1112             send_gatt_characteristic_descriptor_request(gatt_client);
1113             break;
1114 
1115         case P_W2_SEND_INCLUDED_SERVICE_QUERY:
1116             gatt_client->gatt_client_state = P_W4_INCLUDED_SERVICE_QUERY_RESULT;
1117             send_gatt_included_service_request(gatt_client);
1118             break;
1119 
1120         case P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY:
1121             gatt_client->gatt_client_state = P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT;
1122             send_gatt_included_service_uuid_request(gatt_client);
1123             break;
1124 
1125         case P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY:
1126             gatt_client->gatt_client_state = P_W4_READ_CHARACTERISTIC_VALUE_RESULT;
1127             send_gatt_read_characteristic_value_request(gatt_client);
1128             break;
1129 
1130         case P_W2_SEND_READ_BLOB_QUERY:
1131             gatt_client->gatt_client_state = P_W4_READ_BLOB_RESULT;
1132             send_gatt_read_blob_request(gatt_client);
1133             break;
1134 
1135         case P_W2_SEND_READ_BY_TYPE_REQUEST:
1136             gatt_client->gatt_client_state = P_W4_READ_BY_TYPE_RESPONSE;
1137             send_gatt_read_by_type_request(gatt_client);
1138             break;
1139 
1140         case P_W2_SEND_READ_MULTIPLE_REQUEST:
1141             gatt_client->gatt_client_state = P_W4_READ_MULTIPLE_RESPONSE;
1142             send_gatt_read_multiple_request(gatt_client);
1143             break;
1144 
1145         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1146             gatt_client->gatt_client_state = P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT;
1147             send_gatt_write_attribute_value_request(gatt_client);
1148             break;
1149 
1150         case P_W2_PREPARE_WRITE:
1151             gatt_client->gatt_client_state = P_W4_PREPARE_WRITE_RESULT;
1152             send_gatt_prepare_write_request(gatt_client);
1153             break;
1154 
1155         case P_W2_PREPARE_WRITE_SINGLE:
1156             gatt_client->gatt_client_state = P_W4_PREPARE_WRITE_SINGLE_RESULT;
1157             send_gatt_prepare_write_request(gatt_client);
1158             break;
1159 
1160         case P_W2_PREPARE_RELIABLE_WRITE:
1161             gatt_client->gatt_client_state = P_W4_PREPARE_RELIABLE_WRITE_RESULT;
1162             send_gatt_prepare_write_request(gatt_client);
1163             break;
1164 
1165         case P_W2_EXECUTE_PREPARED_WRITE:
1166             gatt_client->gatt_client_state = P_W4_EXECUTE_PREPARED_WRITE_RESULT;
1167             send_gatt_execute_write_request(gatt_client);
1168             break;
1169 
1170         case P_W2_CANCEL_PREPARED_WRITE:
1171             gatt_client->gatt_client_state = P_W4_CANCEL_PREPARED_WRITE_RESULT;
1172             send_gatt_cancel_prepared_write_request(gatt_client);
1173             break;
1174 
1175         case P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH:
1176             gatt_client->gatt_client_state = P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT;
1177             send_gatt_cancel_prepared_write_request(gatt_client);
1178             break;
1179 
1180 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1181         case P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1182             // use Find Information
1183             gatt_client->gatt_client_state = P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1184             send_gatt_characteristic_descriptor_request(gatt_client);
1185 #else
1186         case P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1187             // Use Read By Type
1188             gatt_client->gatt_client_state = P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1189             send_gatt_read_client_characteristic_configuration_request(gatt_client);
1190 #endif
1191             break;
1192 
1193         case P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY:
1194             gatt_client->gatt_client_state = P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT;
1195             send_gatt_read_characteristic_descriptor_request(gatt_client);
1196             break;
1197 
1198         case P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY:
1199             gatt_client->gatt_client_state = P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT;
1200             send_gatt_read_blob_request(gatt_client);
1201             break;
1202 
1203         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1204             gatt_client->gatt_client_state = P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1205             send_gatt_write_attribute_value_request(gatt_client);
1206             break;
1207 
1208         case P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:
1209             gatt_client->gatt_client_state = P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT;
1210             send_gatt_write_client_characteristic_configuration_request(gatt_client);
1211             break;
1212 
1213         case P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR:
1214             gatt_client->gatt_client_state = P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1215             send_gatt_prepare_write_request(gatt_client);
1216             break;
1217 
1218         case P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR:
1219             gatt_client->gatt_client_state = P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1220             send_gatt_execute_write_request(gatt_client);
1221             break;
1222 
1223 #ifdef ENABLE_LE_SIGNED_WRITE
1224         case P_W4_IDENTITY_RESOLVING:
1225             log_info("P_W4_IDENTITY_RESOLVING - state %x", sm_identity_resolving_state(gatt_client->con_handle));
1226             switch (sm_identity_resolving_state(gatt_client->con_handle)){
1227                 case IRK_LOOKUP_SUCCEEDED:
1228                     gatt_client->le_device_index = sm_le_device_index(gatt_client->con_handle);
1229                     gatt_client->gatt_client_state = P_W4_CMAC_READY;
1230                     if (sm_cmac_ready()){
1231                         gatt_client_run_for_client_start_signed_write(gatt_client);
1232                     }
1233                     break;
1234                 case IRK_LOOKUP_FAILED:
1235                     gatt_client_handle_transaction_complete(gatt_client);
1236                     emit_gatt_complete_event(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1237                     break;
1238                 default:
1239                     break;
1240             }
1241             packet_sent = false;
1242             break;
1243 
1244         case P_W4_CMAC_READY:
1245             if (sm_cmac_ready()){
1246                 gatt_client_run_for_client_start_signed_write(gatt_client);
1247             }
1248             packet_sent = false;
1249             break;
1250 
1251         case P_W2_SEND_SIGNED_WRITE: {
1252             gatt_client->gatt_client_state = P_W4_SEND_SINGED_WRITE_DONE;
1253             // bump local signing counter
1254             uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1255             le_device_db_local_counter_set(gatt_client->le_device_index, sign_counter + 1);
1256             // send signed write command
1257             send_gatt_signed_write_request(gatt_client, sign_counter);
1258             // finally, notifiy client that write is complete
1259             gatt_client_handle_transaction_complete(gatt_client);
1260             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1261             break;
1262         }
1263 #endif
1264         default:
1265             done = false;
1266             break;
1267     }
1268 
1269     if (done){
1270         return packet_sent;
1271     }
1272 
1273     // write without response callback
1274     btstack_context_callback_registration_t * callback =
1275             (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->write_without_response_requests);
1276     if (callback != NULL){
1277         (*callback->callback)(callback->context);
1278         return true;
1279     }
1280 
1281     // requested can send now old
1282     if (gatt_client->write_without_response_callback){
1283         btstack_packet_handler_t packet_handler = gatt_client->write_without_response_callback;
1284         gatt_client->write_without_response_callback = NULL;
1285         uint8_t event[4];
1286         event[0] = GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE;
1287         event[1] = sizeof(event) - 2u;
1288         little_endian_store_16(event, 2, gatt_client->con_handle);
1289         packet_handler(HCI_EVENT_PACKET, gatt_client->con_handle, event, sizeof(event));
1290         return true; // to trigger requeueing (even if higher layer didn't sent)
1291     }
1292 
1293     return false;
1294 }
1295 
1296 static void gatt_client_run(void){
1297     btstack_linked_item_t *it;
1298     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
1299         gatt_client_t * gatt_client = (gatt_client_t *) it;
1300         switch (gatt_client->bearer_type){
1301             case ATT_BEARER_UNENHANCED_LE:
1302                 if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) {
1303                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1304                     return;
1305                 }
1306                 bool packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1307                 if (packet_sent){
1308                     // request new permission
1309                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1310                     // requeue client for fairness and exit
1311                     // note: iterator has become invalid
1312                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1313                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1314                     return;
1315                 }
1316                 break;
1317 #ifdef ENABLE_GATT_OVER_CLASSIC
1318             case ATT_BEARER_UNENHANCED_CLASSIC:
1319                 if (gatt_client->con_handle == HCI_CON_HANDLE_INVALID) {
1320                     continue;
1321                 }
1322 
1323                 // handle GATT over BR/EDR
1324                 if (gatt_client->l2cap_psm != 0){
1325                     if (l2cap_can_send_packet_now(gatt_client->l2cap_cid) == false){
1326                         l2cap_request_can_send_now_event(gatt_client->l2cap_cid);
1327                         return;
1328                     }
1329                     bool packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1330                     if (packet_sent){
1331                         // request new permission
1332                         att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1333                         // requeue client for fairness and exit
1334                         // note: iterator has become invalid
1335                         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1336                         btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1337                         return;
1338                     }
1339                 }
1340                 break;
1341 #endif
1342             default:
1343                 btstack_unreachable();
1344                 break;
1345         }
1346 
1347 
1348     }
1349 }
1350 
1351 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code) {
1352     if (is_ready(gatt_client) == 1) return;
1353     gatt_client_handle_transaction_complete(gatt_client);
1354     emit_gatt_complete_event(gatt_client, att_error_code);
1355 }
1356 
1357 static void gatt_client_handle_reencryption_complete(const uint8_t * packet){
1358     hci_con_handle_t con_handle = sm_event_reencryption_complete_get_handle(packet);
1359     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1360     if (gatt_client == NULL) return;
1361 
1362     // update security level
1363     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1364 
1365     gatt_client->reencryption_result = sm_event_reencryption_complete_get_status(packet);
1366     gatt_client->reencryption_active = false;
1367     gatt_client->wait_for_authentication_complete = 0;
1368 
1369     if (gatt_client->gatt_client_state == P_READY) return;
1370 
1371     switch (sm_event_reencryption_complete_get_status(packet)){
1372         case ERROR_CODE_SUCCESS:
1373             log_info("re-encryption success, retry operation");
1374             break;
1375         case ERROR_CODE_AUTHENTICATION_FAILURE:
1376         case ERROR_CODE_PIN_OR_KEY_MISSING:
1377 #if defined(ENABLE_GATT_CLIENT_PAIRING) && !defined(ENABLE_LE_PROACTIVE_AUTHENTICATION)
1378             if (gatt_client_required_security_level == LEVEL_0) {
1379                 // re-encryption failed for reactive authentication with pairing and we have a pending client request
1380                 // => try to resolve it by deleting bonding information if we started pairing before
1381                 // delete bonding information
1382                 int le_device_db_index = sm_le_device_index(gatt_client->con_handle);
1383                 btstack_assert(le_device_db_index >= 0);
1384                 log_info("reactive auth with pairing: delete bonding and start pairing");
1385 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1386                 hci_remove_le_device_db_entry_from_resolving_list((uint16_t) le_device_db_index);
1387 #endif
1388                 le_device_db_remove(le_device_db_index);
1389                 // trigger pairing again
1390                 sm_request_pairing(gatt_client->con_handle);
1391                 break;
1392             }
1393 #endif
1394             // report bonding information missing
1395             gatt_client_handle_transaction_complete(gatt_client);
1396             emit_gatt_complete_event(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1397             break;
1398         default:
1399             // report bonding information missing
1400             gatt_client_handle_transaction_complete(gatt_client);
1401             emit_gatt_complete_event(gatt_client, gatt_client->pending_error_code);
1402             break;
1403     }
1404 }
1405 
1406 static void gatt_client_handle_disconnection_complete(const uint8_t * packet){
1407     log_info("GATT Client: HCI_EVENT_DISCONNECTION_COMPLETE");
1408     hci_con_handle_t con_handle = little_endian_read_16(packet,3);
1409     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1410     if (gatt_client == NULL) return;
1411 
1412     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1413     gatt_client_timeout_stop(gatt_client);
1414     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1415     btstack_memory_gatt_client_free(gatt_client);
1416 }
1417 
1418 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1419     UNUSED(channel);    // ok: handling own l2cap events
1420     UNUSED(size);       // ok: there is no channel
1421 
1422     if (packet_type != HCI_EVENT_PACKET) return;
1423 
1424     hci_con_handle_t con_handle;
1425     gatt_client_t * gatt_client;
1426     switch (hci_event_packet_get_type(packet)) {
1427         case HCI_EVENT_DISCONNECTION_COMPLETE:
1428             gatt_client_handle_disconnection_complete(packet);
1429             break;
1430 
1431         // Pairing complete (with/without bonding=storing of pairing information)
1432         case SM_EVENT_PAIRING_COMPLETE:
1433             con_handle = sm_event_pairing_complete_get_handle(packet);
1434             gatt_client = gatt_client_get_context_for_handle(con_handle);
1435             if (gatt_client == NULL) break;
1436 
1437             // update security level
1438             gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1439 
1440             if (gatt_client->wait_for_authentication_complete){
1441                 gatt_client->wait_for_authentication_complete = 0;
1442                 if (sm_event_pairing_complete_get_status(packet)){
1443                     log_info("pairing failed, report previous error 0x%x", gatt_client->pending_error_code);
1444                     gatt_client_report_error_if_pending(gatt_client, gatt_client->pending_error_code);
1445                 } else {
1446                     log_info("pairing success, retry operation");
1447                 }
1448             }
1449             break;
1450 
1451 #ifdef ENABLE_LE_SIGNED_WRITE
1452         // Identity Resolving completed (no code, gatt_client_run will continue)
1453         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
1454         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
1455             break;
1456 #endif
1457 
1458         // re-encryption started
1459         case SM_EVENT_REENCRYPTION_STARTED:
1460             con_handle = sm_event_reencryption_complete_get_handle(packet);
1461             gatt_client = gatt_client_get_context_for_handle(con_handle);
1462             if (gatt_client == NULL) break;
1463 
1464             gatt_client->reencryption_active = true;
1465             gatt_client->reencryption_result = ERROR_CODE_SUCCESS;
1466             break;
1467 
1468         // re-encryption complete
1469         case SM_EVENT_REENCRYPTION_COMPLETE:
1470             gatt_client_handle_reencryption_complete(packet);
1471             break;
1472         default:
1473             break;
1474     }
1475 
1476     gatt_client_run();
1477 }
1478 
1479 static void gatt_client_handle_att_read_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1480     switch (gatt_client->gatt_client_state) {
1481         case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT:
1482             if (size >= 17) {
1483                 uint8_t uuid128[16];
1484                 reverse_128(&packet[1], uuid128);
1485                 report_gatt_included_service_uuid128(gatt_client, gatt_client->start_group_handle, uuid128);
1486             }
1487             trigger_next_included_service_query(gatt_client, gatt_client->start_group_handle);
1488             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1489             break;
1490 
1491         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1492             report_gatt_characteristic_value(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u);
1493             gatt_client_handle_transaction_complete(gatt_client);
1494             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1495             break;
1496 
1497         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1498             report_gatt_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1499                                                   size - 1u, 0u);
1500             gatt_client_handle_transaction_complete(gatt_client);
1501             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1502             break;
1503 
1504             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic
1505         case P_W4_READ_BLOB_RESULT:
1506             report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1507                                                        size - 1u, gatt_client->attribute_offset);
1508             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, size - 1u);
1509             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1510             break;
1511 
1512             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic Descriptor
1513         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1514             report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1515                                                        size - 1u, gatt_client->attribute_offset);
1516             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
1517                                     size - 1u);
1518             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1519             break;
1520 
1521         default:
1522             break;
1523     }
1524 }
1525 
1526 static void gatt_client_handle_att_read_by_type_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1527     switch (gatt_client->gatt_client_state) {
1528         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1529             report_gatt_characteristics(gatt_client, packet, size);
1530             trigger_next_characteristic_query(gatt_client,
1531                                               get_last_result_handle_from_characteristics_list(packet, size));
1532             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1533             break;
1534         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1535             report_gatt_characteristics(gatt_client, packet, size);
1536             trigger_next_characteristic_query(gatt_client,
1537                                               get_last_result_handle_from_characteristics_list(packet, size));
1538             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1539             break;
1540         case P_W4_INCLUDED_SERVICE_QUERY_RESULT: {
1541             if (size < 2u) break;
1542             uint16_t uuid16 = 0;
1543             uint16_t pair_size = packet[1];
1544 
1545             if (pair_size == 6u) {
1546                 if (size < 8u) break;
1547                 // UUIDs not available, query first included service
1548                 gatt_client->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1549                 gatt_client->query_start_handle = little_endian_read_16(packet, 4);
1550                 gatt_client->query_end_handle = little_endian_read_16(packet, 6);
1551                 gatt_client->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1552                 break;
1553             }
1554 
1555             if (pair_size != 8u) break;
1556 
1557             // UUIDs included, report all of them
1558             uint16_t offset;
1559             for (offset = 2u; (offset + 8u) <= size; offset += pair_size) {
1560                 uint16_t include_handle = little_endian_read_16(packet, offset);
1561                 gatt_client->query_start_handle = little_endian_read_16(packet, offset + 2u);
1562                 gatt_client->query_end_handle = little_endian_read_16(packet, offset + 4u);
1563                 uuid16 = little_endian_read_16(packet, offset + 6u);
1564                 report_gatt_included_service_uuid16(gatt_client, include_handle, uuid16);
1565             }
1566 
1567             trigger_next_included_service_query(gatt_client,
1568                                                 get_last_result_handle_from_included_services_list(packet,
1569                                                                                                    size));
1570             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1571             break;
1572         }
1573 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1574         case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1575             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1576             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1577             break;
1578 #endif
1579         case P_W4_READ_BY_TYPE_RESPONSE: {
1580             uint16_t pair_size = packet[1];
1581             // set last result handle to last valid handle, only used if pair_size invalid
1582             uint16_t last_result_handle = 0xffff;
1583             if (pair_size > 2) {
1584                 uint16_t offset;
1585                 for (offset = 2; offset < size; offset += pair_size) {
1586                     uint16_t value_handle = little_endian_read_16(packet, offset);
1587                     report_gatt_characteristic_value(gatt_client, value_handle, &packet[offset + 2u],
1588                                                      pair_size - 2u);
1589                     last_result_handle = value_handle;
1590                 }
1591             }
1592             trigger_next_read_by_type_query(gatt_client, last_result_handle);
1593             break;
1594         }
1595         default:
1596             break;
1597     }
1598 }
1599 
1600 static void gatt_client_handle_att_write_response(gatt_client_t *gatt_client) {
1601     switch (gatt_client->gatt_client_state) {
1602         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1603             gatt_client_handle_transaction_complete(gatt_client);
1604             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1605             break;
1606         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1607             gatt_client_handle_transaction_complete(gatt_client);
1608             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1609             break;
1610         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1611             gatt_client_handle_transaction_complete(gatt_client);
1612             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1613             break;
1614         default:
1615             break;
1616     }
1617 }
1618 
1619 static void gatt_client_handle_att_response(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size) {
1620     uint8_t error_code;
1621     switch (packet[0]) {
1622         case ATT_EXCHANGE_MTU_RESPONSE: {
1623             if (size < 3u) break;
1624             bool update_gatt_server_att_mtu = false;
1625             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1626             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1627             switch (gatt_client->bearer_type){
1628                 case ATT_BEARER_UNENHANCED_LE:
1629                     update_gatt_server_att_mtu = true;
1630                     break;
1631 #ifdef ENABLE_GATT_OVER_CLASSIC
1632                 case ATT_BEARER_UNENHANCED_CLASSIC:
1633                     local_rx_mtu = gatt_client->mtu;
1634                     break;
1635 #endif
1636                 default:
1637                     btstack_unreachable();
1638                     break;
1639             }
1640 
1641             uint16_t mtu = (remote_rx_mtu < local_rx_mtu) ? remote_rx_mtu : local_rx_mtu;
1642 
1643             // set gatt client mtu
1644             gatt_client->mtu = mtu;
1645             gatt_client->mtu_state = MTU_EXCHANGED;
1646 
1647             if (update_gatt_server_att_mtu){
1648                 // set per connection mtu state - for fixed channel
1649                 hci_connection_t *hci_connection = hci_connection_for_handle(gatt_client->con_handle);
1650                 hci_connection->att_connection.mtu = gatt_client->mtu;
1651                 hci_connection->att_connection.mtu_exchanged = true;
1652             }
1653             emit_gatt_mtu_exchanged_result_event(gatt_client, gatt_client->mtu);
1654             break;
1655         }
1656         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
1657             switch (gatt_client->gatt_client_state) {
1658                 case P_W4_SERVICE_QUERY_RESULT:
1659                     report_gatt_services(gatt_client, packet, size);
1660                     trigger_next_service_query(gatt_client, get_last_result_handle_from_service_list(packet, size));
1661                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1662                     break;
1663                 default:
1664                     break;
1665             }
1666             break;
1667         case ATT_HANDLE_VALUE_NOTIFICATION:
1668             if (size < 3u) return;
1669             report_gatt_notification(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
1670             return;
1671         case ATT_HANDLE_VALUE_INDICATION:
1672             if (size < 3u) break;
1673             report_gatt_indication(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
1674             gatt_client->send_confirmation = 1;
1675             break;
1676         case ATT_READ_BY_TYPE_RESPONSE:
1677             gatt_client_handle_att_read_by_type_response(gatt_client, packet, size);
1678             break;
1679         case ATT_READ_RESPONSE:
1680             gatt_client_handle_att_read_response(gatt_client, packet, size);
1681             break;
1682         case ATT_FIND_BY_TYPE_VALUE_RESPONSE: {
1683             uint8_t pair_size = 4;
1684             int i;
1685             uint16_t start_group_handle;
1686             uint16_t end_group_handle = 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
1687             for (i = 1u; (i + pair_size) <= size; i += pair_size) {
1688                 start_group_handle = little_endian_read_16(packet, i);
1689                 end_group_handle = little_endian_read_16(packet, i + 2);
1690                 emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle,
1691                                                      gatt_client->uuid128);
1692             }
1693             trigger_next_service_by_uuid_query(gatt_client, end_group_handle);
1694             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1695             break;
1696         }
1697         case ATT_FIND_INFORMATION_REPLY: {
1698             if (size < 2u) break;
1699 
1700             uint8_t pair_size = 4;
1701             if (packet[1u] == 2u) {
1702                 pair_size = 18;
1703             }
1704             uint16_t offset = 2;
1705 
1706             if (size < (pair_size + offset)) break;
1707             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
1708 
1709 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1710             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", gatt_client->gatt_client_state);
1711             if (gatt_client->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
1712                 // iterate over descriptors looking for CCC
1713                 if (pair_size == 4){
1714                     while ((offset + 4) <= size){
1715                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
1716                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
1717                             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
1718                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1719                             log_info("CCC found %x", gatt_client->client_characteristic_configuration_handle);
1720                             break;
1721                         }
1722                         offset += pair_size;
1723                     }
1724                 }
1725                 if (is_query_done(gatt_client, last_descriptor_handle)){
1726 
1727                 } else {
1728                     // next
1729                     gatt_client->start_group_handle = last_descriptor_handle + 1;
1730                     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1731                 }
1732                 break;
1733             }
1734 #endif
1735             report_gatt_all_characteristic_descriptors(gatt_client, &packet[2], size - 2u, pair_size);
1736             trigger_next_characteristic_descriptor_query(gatt_client, last_descriptor_handle);
1737             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1738             break;
1739         }
1740 
1741         case ATT_WRITE_RESPONSE:
1742             gatt_client_handle_att_write_response(gatt_client);
1743             break;
1744 
1745         case ATT_READ_BLOB_RESPONSE: {
1746             uint16_t received_blob_length = size - 1u;
1747             switch (gatt_client->gatt_client_state) {
1748                 case P_W4_READ_BLOB_RESULT:
1749                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1750                                                                received_blob_length, gatt_client->attribute_offset);
1751                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
1752                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1753                     break;
1754                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1755                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle,
1756                                                                &packet[1], received_blob_length,
1757                                                                gatt_client->attribute_offset);
1758                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
1759                                             received_blob_length);
1760                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1761                     break;
1762                 default:
1763                     break;
1764             }
1765             break;
1766         }
1767         case ATT_PREPARE_WRITE_RESPONSE:
1768             switch (gatt_client->gatt_client_state) {
1769                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1770                     gatt_client_handle_transaction_complete(gatt_client);
1771                     if (is_value_valid(gatt_client, packet, size)) {
1772                         emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1773                     } else {
1774                         emit_gatt_complete_event(gatt_client, ATT_ERROR_DATA_MISMATCH);
1775                     }
1776                     break;
1777 
1778                 case P_W4_PREPARE_WRITE_RESULT: {
1779                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1780                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1781                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1782                     break;
1783                 }
1784                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT: {
1785                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1786                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR,
1787                                                      P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1788                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1789                     break;
1790                 }
1791                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT: {
1792                     if (is_value_valid(gatt_client, packet, size)) {
1793                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1794                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE,
1795                                                          P_W2_EXECUTE_PREPARED_WRITE);
1796                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1797                         break;
1798                     }
1799                     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1800                     break;
1801                 }
1802                 default:
1803                     break;
1804             }
1805             break;
1806 
1807         case ATT_EXECUTE_WRITE_RESPONSE:
1808             switch (gatt_client->gatt_client_state) {
1809                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1810                     gatt_client_handle_transaction_complete(gatt_client);
1811                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1812                     break;
1813                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1814                     gatt_client_handle_transaction_complete(gatt_client);
1815                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1816                     break;
1817                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1818                     gatt_client_handle_transaction_complete(gatt_client);
1819                     emit_gatt_complete_event(gatt_client, ATT_ERROR_DATA_MISMATCH);
1820                     break;
1821                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1822                     gatt_client_handle_transaction_complete(gatt_client);
1823                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1824                     break;
1825                 default:
1826                     break;
1827 
1828             }
1829             break;
1830 
1831         case ATT_READ_MULTIPLE_RESPONSE:
1832             switch (gatt_client->gatt_client_state) {
1833                 case P_W4_READ_MULTIPLE_RESPONSE:
1834                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
1835                     gatt_client_handle_transaction_complete(gatt_client);
1836                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1837                     break;
1838                 default:
1839                     break;
1840             }
1841             break;
1842 
1843         case ATT_ERROR_RESPONSE:
1844             if (size < 5u) return;
1845             error_code = packet[4];
1846             switch (error_code) {
1847                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1848                     switch (gatt_client->gatt_client_state) {
1849                         case P_W4_SERVICE_QUERY_RESULT:
1850                         case P_W4_SERVICE_WITH_UUID_RESULT:
1851                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1852                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1853                             gatt_client_handle_transaction_complete(gatt_client);
1854                             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1855                             break;
1856                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1857                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1858                             characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1859                             gatt_client_handle_transaction_complete(gatt_client);
1860                             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1861                             break;
1862                         case P_W4_READ_BY_TYPE_RESPONSE:
1863                             gatt_client_handle_transaction_complete(gatt_client);
1864                             if (gatt_client->start_group_handle == gatt_client->query_start_handle) {
1865                                 emit_gatt_complete_event(gatt_client, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
1866                             } else {
1867                                 emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1868                             }
1869                             break;
1870                         default:
1871                             gatt_client_report_error_if_pending(gatt_client, error_code);
1872                             break;
1873                     }
1874                     break;
1875                 }
1876 
1877 #ifdef ENABLE_GATT_CLIENT_PAIRING
1878 
1879                     case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
1880                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
1881                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
1882 
1883                         // security too low
1884                         if (gatt_client->security_counter > 0) {
1885                             gatt_client_report_error_if_pending(gatt_client, error_code);
1886                             break;
1887                         }
1888                         // start security
1889                         gatt_client->security_counter++;
1890 
1891                         // setup action
1892                         int retry = 1;
1893                         switch (gatt_client->gatt_client_state){
1894                             case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1895                                 gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
1896                                 break;
1897                             case P_W4_READ_BLOB_RESULT:
1898                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1899                                 break;
1900                             case P_W4_READ_BY_TYPE_RESPONSE:
1901                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1902                                 break;
1903                             case P_W4_READ_MULTIPLE_RESPONSE:
1904                                 gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1905                                 break;
1906                             case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1907                                 gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1908                                 break;
1909                             case P_W4_PREPARE_WRITE_RESULT:
1910                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
1911                                 break;
1912                             case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1913                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
1914                                 break;
1915                             case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
1916                                 gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1917                                 break;
1918                             case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1919                                 gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
1920                                 break;
1921                             case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1922                                 gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
1923                                 break;
1924                             case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1925                                 gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1926                                 break;
1927                             case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1928                                 gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1929                                 break;
1930                             case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1931                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1932                                 break;
1933                             case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1934                                 gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
1935                                 break;
1936                             case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1937                                 gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1938                                 break;
1939                             case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1940                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
1941                                 break;
1942                             case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1943                                 gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
1944                                 break;
1945 #ifdef ENABLE_LE_SIGNED_WRITE
1946                             case P_W4_SEND_SINGED_WRITE_DONE:
1947                                 gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1948                                 break;
1949 #endif
1950                             default:
1951                                 log_info("retry not supported for state %x", gatt_client->gatt_client_state);
1952                                 retry = 0;
1953                                 break;
1954                         }
1955 
1956                         if (!retry) {
1957                             gatt_client_report_error_if_pending(gatt_client, error_code);
1958                             break;
1959                         }
1960 
1961                         log_info("security error, start pairing");
1962 
1963                         // start pairing for higher security level
1964                         gatt_client->wait_for_authentication_complete = 1;
1965                         gatt_client->pending_error_code = error_code;
1966                         sm_request_pairing(gatt_client->con_handle);
1967                         break;
1968                     }
1969 #endif
1970 
1971                     // nothing we can do about that
1972                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
1973                 default:
1974                     gatt_client_report_error_if_pending(gatt_client, error_code);
1975                     break;
1976             }
1977             break;
1978 
1979         default:
1980             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
1981             break;
1982     }
1983 }
1984 
1985 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size) {
1986     gatt_client_t *gatt_client;
1987     if (size < 1u) return;
1988 
1989     if (packet_type == HCI_EVENT_PACKET) {
1990         switch (packet[0]) {
1991             case L2CAP_EVENT_CAN_SEND_NOW:
1992                 gatt_client_run();
1993                 break;
1994                 // att_server has negotiated the mtu for this connection, cache if context exists
1995             case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
1996                 if (size < 6u) break;
1997                 gatt_client = gatt_client_get_context_for_handle(handle);
1998                 if (gatt_client == NULL) break;
1999                 gatt_client->mtu = little_endian_read_16(packet, 4);
2000                 break;
2001             default:
2002                 break;
2003         }
2004         return;
2005     }
2006 
2007     if (packet_type != ATT_DATA_PACKET) return;
2008 
2009     // special cases: notifications & indications motivate creating context
2010     switch (packet[0]) {
2011         case ATT_HANDLE_VALUE_NOTIFICATION:
2012         case ATT_HANDLE_VALUE_INDICATION:
2013             gatt_client_provide_context_for_handle(handle, &gatt_client);
2014             break;
2015         default:
2016             gatt_client = gatt_client_get_context_for_handle(handle);
2017             break;
2018     }
2019 
2020     if (gatt_client != NULL) {
2021         gatt_client_handle_att_response(gatt_client, packet, size);
2022         gatt_client_run();
2023     }
2024 }
2025 
2026 #ifdef ENABLE_LE_SIGNED_WRITE
2027 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2028     btstack_linked_list_iterator_t it;
2029     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2030     while (btstack_linked_list_iterator_has_next(&it)){
2031         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2032         if (gatt_client->gatt_client_state == P_W4_CMAC_RESULT){
2033             // store result
2034             (void)memcpy(gatt_client->cmac, hash, 8);
2035             // reverse_64(hash, gatt_client->cmac);
2036             gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
2037             gatt_client_run();
2038             return;
2039         }
2040     }
2041 }
2042 
2043 uint8_t gatt_client_signed_write_without_response(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle, uint16_t message_len, uint8_t * message){
2044     gatt_client_t * gatt_client;
2045     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2046     if (status != ERROR_CODE_SUCCESS){
2047         return status;
2048     }
2049     if (is_ready(gatt_client) == 0){
2050         return GATT_CLIENT_IN_WRONG_STATE;
2051     }
2052 
2053     gatt_client->callback = callback;
2054     gatt_client->attribute_handle = value_handle;
2055     gatt_client->attribute_length = message_len;
2056     gatt_client->attribute_value = message;
2057     gatt_client->gatt_client_state = P_W4_IDENTITY_RESOLVING;
2058     gatt_client_run();
2059     return ERROR_CODE_SUCCESS;
2060 }
2061 #endif
2062 
2063 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2064     gatt_client_t * gatt_client;
2065     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2066     if (status != ERROR_CODE_SUCCESS){
2067         return status;
2068     }
2069 
2070     gatt_client->callback = callback;
2071     gatt_client->start_group_handle = 0x0001;
2072     gatt_client->end_group_handle   = 0xffff;
2073     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
2074     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2075     gatt_client_run();
2076     return ERROR_CODE_SUCCESS;
2077 }
2078 
2079 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2080     gatt_client_t * gatt_client;
2081     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2082     if (status != ERROR_CODE_SUCCESS){
2083         return status;
2084     }
2085 
2086     gatt_client->callback = callback;
2087     gatt_client->start_group_handle = 0x0001;
2088     gatt_client->end_group_handle   = 0xffff;
2089     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
2090     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2091     gatt_client_run();
2092     return ERROR_CODE_SUCCESS;
2093 }
2094 
2095 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2096     gatt_client_t * gatt_client;
2097     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2098     if (status != ERROR_CODE_SUCCESS){
2099         return status;
2100     }
2101 
2102     gatt_client->callback = callback;
2103     gatt_client->start_group_handle = 0x0001;
2104     gatt_client->end_group_handle   = 0xffff;
2105     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2106     gatt_client->uuid16 = uuid16;
2107     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2108     gatt_client_run();
2109     return ERROR_CODE_SUCCESS;
2110 }
2111 
2112 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2113     gatt_client_t * gatt_client;
2114     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2115     if (status != ERROR_CODE_SUCCESS){
2116         return status;
2117     }
2118 
2119     gatt_client->callback = callback;
2120     gatt_client->start_group_handle = 0x0001;
2121     gatt_client->end_group_handle   = 0xffff;
2122     gatt_client->uuid16 = 0;
2123     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2124     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2125     gatt_client_run();
2126     return ERROR_CODE_SUCCESS;
2127 }
2128 
2129 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2130     gatt_client_t * gatt_client;
2131     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2132     if (status != ERROR_CODE_SUCCESS){
2133         return status;
2134     }
2135 
2136     gatt_client->callback = callback;
2137     gatt_client->start_group_handle = service->start_group_handle;
2138     gatt_client->end_group_handle   = service->end_group_handle;
2139     gatt_client->filter_with_uuid = 0;
2140     gatt_client->characteristic_start_handle = 0;
2141     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2142     gatt_client_run();
2143     return ERROR_CODE_SUCCESS;
2144 }
2145 
2146 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){
2147     gatt_client_t * gatt_client;
2148     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2149     if (status != ERROR_CODE_SUCCESS){
2150         return status;
2151     }
2152 
2153     gatt_client->callback = callback;
2154     gatt_client->start_group_handle = service->start_group_handle;
2155     gatt_client->end_group_handle   = service->end_group_handle;
2156     gatt_client->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2157 
2158     gatt_client_run();
2159     return ERROR_CODE_SUCCESS;
2160 }
2161 
2162 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){
2163     gatt_client_t * gatt_client;
2164     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2165     if (status != ERROR_CODE_SUCCESS){
2166         return status;
2167     }
2168 
2169     gatt_client->callback = callback;
2170     gatt_client->start_group_handle = start_handle;
2171     gatt_client->end_group_handle   = end_handle;
2172     gatt_client->filter_with_uuid = 1;
2173     gatt_client->uuid16 = uuid16;
2174     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2175     gatt_client->characteristic_start_handle = 0;
2176     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2177     gatt_client_run();
2178     return ERROR_CODE_SUCCESS;
2179 }
2180 
2181 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, const uint8_t * uuid128){
2182     gatt_client_t * gatt_client;
2183     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2184     if (status != ERROR_CODE_SUCCESS){
2185         return status;
2186     }
2187 
2188     gatt_client->callback = callback;
2189     gatt_client->start_group_handle = start_handle;
2190     gatt_client->end_group_handle   = end_handle;
2191     gatt_client->filter_with_uuid = 1;
2192     gatt_client->uuid16 = 0;
2193     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2194     gatt_client->characteristic_start_handle = 0;
2195     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2196     gatt_client_run();
2197     return ERROR_CODE_SUCCESS;
2198 }
2199 
2200 
2201 uint8_t gatt_client_discover_characteristics_for_service_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service, uint16_t uuid16){
2202     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2203 }
2204 
2205 uint8_t gatt_client_discover_characteristics_for_service_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service, const uint8_t * uuid128){
2206     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2207 }
2208 
2209 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2210     gatt_client_t * gatt_client;
2211     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2212     if (status != ERROR_CODE_SUCCESS){
2213         return status;
2214     }
2215 
2216     if (characteristic->value_handle == characteristic->end_handle){
2217         emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
2218         return ERROR_CODE_SUCCESS;
2219     }
2220     gatt_client->callback = callback;
2221     gatt_client->start_group_handle = characteristic->value_handle + 1u;
2222     gatt_client->end_group_handle   = characteristic->end_handle;
2223     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2224     gatt_client_run();
2225     return ERROR_CODE_SUCCESS;
2226 }
2227 
2228 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){
2229     gatt_client_t * gatt_client;
2230     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2231     if (status != ERROR_CODE_SUCCESS){
2232         return status;
2233     }
2234 
2235     gatt_client->callback = callback;
2236     gatt_client->attribute_handle = value_handle;
2237     gatt_client->attribute_offset = 0;
2238     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2239     gatt_client_run();
2240     return ERROR_CODE_SUCCESS;
2241 }
2242 
2243 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){
2244     gatt_client_t * gatt_client;
2245     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2246     if (status != ERROR_CODE_SUCCESS){
2247         return status;
2248     }
2249 
2250     gatt_client->callback = callback;
2251     gatt_client->start_group_handle = start_handle;
2252     gatt_client->end_group_handle = end_handle;
2253     gatt_client->query_start_handle = start_handle;
2254     gatt_client->query_end_handle = end_handle;
2255     gatt_client->uuid16 = uuid16;
2256     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2257     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2258     gatt_client_run();
2259     return ERROR_CODE_SUCCESS;
2260 }
2261 
2262 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, const uint8_t * uuid128){
2263     gatt_client_t * gatt_client;
2264     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2265     if (status != ERROR_CODE_SUCCESS){
2266         return status;
2267     }
2268 
2269     gatt_client->callback = callback;
2270     gatt_client->start_group_handle = start_handle;
2271     gatt_client->end_group_handle = end_handle;
2272     gatt_client->query_start_handle = start_handle;
2273     gatt_client->query_end_handle = end_handle;
2274     gatt_client->uuid16 = 0;
2275     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2276     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2277     gatt_client_run();
2278     return ERROR_CODE_SUCCESS;
2279 }
2280 
2281 
2282 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2283     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2284 }
2285 
2286 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 value_handle, uint16_t offset){
2287     gatt_client_t * gatt_client;
2288     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2289     if (status != ERROR_CODE_SUCCESS){
2290         return status;
2291     }
2292 
2293     gatt_client->callback = callback;
2294     gatt_client->attribute_handle = value_handle;
2295     gatt_client->attribute_offset = offset;
2296     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
2297     gatt_client_run();
2298     return ERROR_CODE_SUCCESS;
2299 }
2300 
2301 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 value_handle){
2302     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2303 }
2304 
2305 uint8_t gatt_client_read_long_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2306     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2307 }
2308 
2309 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){
2310     gatt_client_t * gatt_client;
2311     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2312     if (status != ERROR_CODE_SUCCESS){
2313         return status;
2314     }
2315 
2316     gatt_client->callback = callback;
2317     gatt_client->read_multiple_handle_count = num_value_handles;
2318     gatt_client->read_multiple_handles = value_handles;
2319     gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2320     gatt_client_run();
2321     return ERROR_CODE_SUCCESS;
2322 }
2323 
2324 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){
2325     gatt_client_t * gatt_client;
2326     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2327     if (status != ERROR_CODE_SUCCESS){
2328         return status;
2329     }
2330 
2331     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2332     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2333 
2334     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2335 }
2336 
2337 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 * value){
2338     gatt_client_t * gatt_client;
2339     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2340     if (status != ERROR_CODE_SUCCESS){
2341         return status;
2342     }
2343 
2344     gatt_client->callback = callback;
2345     gatt_client->attribute_handle = value_handle;
2346     gatt_client->attribute_length = value_length;
2347     gatt_client->attribute_value = value;
2348     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2349     gatt_client_run();
2350     return ERROR_CODE_SUCCESS;
2351 }
2352 
2353 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 * value){
2354     gatt_client_t * gatt_client;
2355     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2356     if (status != ERROR_CODE_SUCCESS){
2357         return status;
2358     }
2359 
2360     gatt_client->callback = callback;
2361     gatt_client->attribute_handle = value_handle;
2362     gatt_client->attribute_length = value_length;
2363     gatt_client->attribute_offset = offset;
2364     gatt_client->attribute_value = value;
2365     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
2366     gatt_client_run();
2367     return ERROR_CODE_SUCCESS;
2368 }
2369 
2370 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){
2371     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2372 }
2373 
2374 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){
2375     gatt_client_t * gatt_client;
2376     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2377     if (status != ERROR_CODE_SUCCESS){
2378         return status;
2379     }
2380 
2381     gatt_client->callback = callback;
2382     gatt_client->attribute_handle = value_handle;
2383     gatt_client->attribute_length = value_length;
2384     gatt_client->attribute_offset = 0;
2385     gatt_client->attribute_value = value;
2386     gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
2387     gatt_client_run();
2388     return ERROR_CODE_SUCCESS;
2389 }
2390 
2391 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){
2392     gatt_client_t * gatt_client;
2393     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2394     if (status != ERROR_CODE_SUCCESS){
2395         return status;
2396     }
2397 
2398     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2399         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2400         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2401         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2402     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2403                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2404         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2405         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2406     }
2407 
2408     gatt_client->callback = callback;
2409     gatt_client->start_group_handle = characteristic->value_handle;
2410     gatt_client->end_group_handle = characteristic->end_handle;
2411     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2412 
2413 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2414     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2415 #else
2416     gatt_client->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2417 #endif
2418     gatt_client_run();
2419     return ERROR_CODE_SUCCESS;
2420 }
2421 
2422 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){
2423     gatt_client_t * gatt_client;
2424     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2425     if (status != ERROR_CODE_SUCCESS){
2426         return status;
2427     }
2428 
2429     gatt_client->callback = callback;
2430     gatt_client->attribute_handle = descriptor_handle;
2431 
2432     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2433     gatt_client_run();
2434     return ERROR_CODE_SUCCESS;
2435 }
2436 
2437 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2438     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2439 }
2440 
2441 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){
2442     gatt_client_t * gatt_client;
2443     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2444     if (status != ERROR_CODE_SUCCESS){
2445         return status;
2446     }
2447 
2448     gatt_client->callback = callback;
2449     gatt_client->attribute_handle = descriptor_handle;
2450     gatt_client->attribute_offset = offset;
2451     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2452     gatt_client_run();
2453     return ERROR_CODE_SUCCESS;
2454 }
2455 
2456 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){
2457     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2458 }
2459 
2460 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){
2461     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2462 }
2463 
2464 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 value_length, uint8_t * value){
2465     gatt_client_t * gatt_client;
2466     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2467     if (status != ERROR_CODE_SUCCESS){
2468         return status;
2469     }
2470 
2471     gatt_client->callback = callback;
2472     gatt_client->attribute_handle = descriptor_handle;
2473     gatt_client->attribute_length = value_length;
2474     gatt_client->attribute_offset = 0;
2475     gatt_client->attribute_value = value;
2476     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2477     gatt_client_run();
2478     return ERROR_CODE_SUCCESS;
2479 }
2480 
2481 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 value_length, uint8_t * value){
2482     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2483 }
2484 
2485 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 value_length, uint8_t * value){
2486     gatt_client_t * gatt_client;
2487     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2488     if (status != ERROR_CODE_SUCCESS){
2489         return status;
2490     }
2491 
2492     gatt_client->callback = callback;
2493     gatt_client->attribute_handle = descriptor_handle;
2494     gatt_client->attribute_length = value_length;
2495     gatt_client->attribute_offset = offset;
2496     gatt_client->attribute_value = value;
2497     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2498     gatt_client_run();
2499     return ERROR_CODE_SUCCESS;
2500 }
2501 
2502 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 value_length, uint8_t * value){
2503     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2504 }
2505 
2506 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 value_length, uint8_t * value){
2507     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2508 }
2509 
2510 /**
2511  * @brief -> gatt complete event
2512  */
2513 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 value_length, uint8_t * value){
2514     gatt_client_t * gatt_client;
2515     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2516     if (status != ERROR_CODE_SUCCESS){
2517         return status;
2518     }
2519 
2520     gatt_client->callback = callback;
2521     gatt_client->attribute_handle = attribute_handle;
2522     gatt_client->attribute_length = value_length;
2523     gatt_client->attribute_offset = offset;
2524     gatt_client->attribute_value = value;
2525     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
2526     gatt_client_run();
2527     return ERROR_CODE_SUCCESS;
2528 }
2529 
2530 /**
2531  * @brief -> gatt complete event
2532  */
2533 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2534     gatt_client_t * gatt_client;
2535     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2536     if (status != ERROR_CODE_SUCCESS){
2537         return status;
2538     }
2539 
2540     gatt_client->callback = callback;
2541     gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
2542     gatt_client_run();
2543     return ERROR_CODE_SUCCESS;
2544 }
2545 
2546 /**
2547  * @brief -> gatt complete event
2548  */
2549 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2550     gatt_client_t * gatt_client;
2551     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2552     if (status != ERROR_CODE_SUCCESS){
2553         return status;
2554     }
2555 
2556     gatt_client->callback = callback;
2557     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
2558     gatt_client_run();
2559     return ERROR_CODE_SUCCESS;
2560 }
2561 
2562 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
2563     service->start_group_handle = little_endian_read_16(packet, offset);
2564     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2565     reverse_128(&packet[offset + 4], service->uuid128);
2566     if (uuid_has_bluetooth_prefix(service->uuid128)){
2567         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2568     } else {
2569         service->uuid16 = 0;
2570     }
2571 }
2572 
2573 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2574     characteristic->start_handle = little_endian_read_16(packet, offset);
2575     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2576     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2577     characteristic->properties = little_endian_read_16(packet, offset + 6);
2578     reverse_128(&packet[offset+8], characteristic->uuid128);
2579     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2580         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2581     } else {
2582         characteristic->uuid16 = 0;
2583     }
2584 }
2585 
2586 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2587     descriptor->handle = little_endian_read_16(packet, offset);
2588     reverse_128(&packet[offset+2], descriptor->uuid128);
2589     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2590         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2591     } else {
2592         descriptor->uuid16 = 0;
2593     }
2594 }
2595 
2596 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2597     gatt_client_t * gatt_client;
2598     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2599     if (status != ERROR_CODE_SUCCESS){
2600         return;
2601     }
2602     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2603         gatt_client->callback = callback;
2604         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
2605         gatt_client_run();
2606     }
2607 }
2608 
2609 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2610     gatt_client_t * gatt_client;
2611     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2612     if (status != ERROR_CODE_SUCCESS){
2613         return status;
2614     }
2615     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
2616     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2617     if (added){
2618         return ERROR_CODE_SUCCESS;
2619     } else {
2620         return ERROR_CODE_COMMAND_DISALLOWED;
2621     }
2622 }
2623 
2624 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2625     gatt_client_t * gatt_client;
2626     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2627     if (status != ERROR_CODE_SUCCESS){
2628         return status;
2629     }
2630     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
2631     gatt_client_notify_can_send_query(gatt_client);
2632     if (added){
2633         return ERROR_CODE_SUCCESS;
2634     } else {
2635         return ERROR_CODE_COMMAND_DISALLOWED;
2636     }
2637 }
2638 
2639 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2640     gatt_client_t * gatt_client;
2641     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2642     if (status != ERROR_CODE_SUCCESS){
2643         return status;
2644     }
2645     if (gatt_client->write_without_response_callback != NULL){
2646         return GATT_CLIENT_IN_WRONG_STATE;
2647     }
2648     gatt_client->write_without_response_callback = callback;
2649     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2650     return ERROR_CODE_SUCCESS;
2651 }
2652 
2653 #ifdef ENABLE_GATT_OVER_CLASSIC
2654 
2655 #include "hci_event.h"
2656 
2657 // single active SDP query
2658 static gatt_client_t * gatt_client_classic_active_sdp_query;
2659 
2660 // macos protocol descriptor list requires 16 bytes
2661 static uint8_t gatt_client_classic_sdp_buffer[32];
2662 
2663 static const hci_event_t gatt_client_connected = {
2664         GATT_EVENT_CONNECTED, 0, "1BH"
2665 };
2666 
2667 static const hci_event_t gatt_client_disconnected = {
2668         GATT_EVENT_DISCONNECTED, 0, "H"
2669 };
2670 
2671 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
2672     btstack_linked_item_t *it;
2673     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2674         gatt_client_t * gatt_client = (gatt_client_t *) it;
2675         if (memcmp(gatt_client->addr, addr, 6) == 0){
2676             return gatt_client;
2677         }
2678     }
2679     return NULL;
2680 }
2681 
2682 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
2683     btstack_linked_item_t *it;
2684     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2685         gatt_client_t * gatt_client = (gatt_client_t *) it;
2686         if (gatt_client->l2cap_cid == l2cap_cid){
2687             return gatt_client;
2688         }
2689     }
2690     return NULL;
2691 }
2692 
2693 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
2694     bd_addr_t addr;
2695     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
2696     memcpy(addr, gatt_client->addr, 6);
2697     hci_con_handle_t con_handle = gatt_client->con_handle;
2698     btstack_packet_handler_t callback = gatt_client->callback;
2699     if (status != ERROR_CODE_SUCCESS){
2700         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2701         btstack_memory_gatt_client_free(gatt_client);
2702     }
2703     uint8_t buffer[20];
2704     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr,
2705                                                                 con_handle);
2706     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2707 }
2708 
2709 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
2710 
2711     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
2712     gatt_client_timeout_stop(gatt_client);
2713 
2714     hci_con_handle_t con_handle = gatt_client->con_handle;
2715     btstack_packet_handler_t callback = gatt_client->callback;
2716     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2717     btstack_memory_gatt_client_free(gatt_client);
2718 
2719     uint8_t buffer[20];
2720     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
2721     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2722 }
2723 
2724 static void gatt_client_l2cap_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2725     gatt_client_t * gatt_client = NULL;
2726     uint8_t status;
2727     switch (packet_type){
2728         case HCI_EVENT_PACKET:
2729             switch (hci_event_packet_get_type(packet)) {
2730                 case L2CAP_EVENT_CHANNEL_OPENED:
2731                     status = l2cap_event_channel_opened_get_status(packet);
2732                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_opened_get_local_cid(packet));
2733                     btstack_assert(gatt_client != NULL);
2734                     // if status != 0, gatt_client will be discarded
2735                     gatt_client->gatt_client_state = P_READY;
2736                     gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2737                     gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2738                     gatt_client_classic_handle_connected(gatt_client, status);
2739                     break;
2740                 case L2CAP_EVENT_CHANNEL_CLOSED:
2741                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2742                     gatt_client_classic_handle_disconnected(gatt_client);
2743                     break;
2744                 default:
2745                     break;
2746             }
2747             break;
2748         case L2CAP_DATA_PACKET:
2749             gatt_client = gatt_client_get_context_for_l2cap_cid(channel);
2750             btstack_assert(gatt_client != NULL);
2751             gatt_client_handle_att_response(gatt_client, packet, size);
2752             gatt_client_run();
2753             break;
2754         default:
2755             break;
2756     }
2757 }
2758 
2759 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
2760     des_iterator_t des_list_it;
2761     des_iterator_t prot_it;
2762 
2763     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
2764         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
2765         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
2766             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
2767                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
2768                     for (des_iterator_init(&des_list_it, gatt_client_classic_sdp_buffer); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
2769                         uint8_t       *des_element;
2770                         uint8_t       *element;
2771                         uint32_t       uuid;
2772 
2773                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
2774 
2775                         des_element = des_iterator_get_element(&des_list_it);
2776                         des_iterator_init(&prot_it, des_element);
2777                         element = des_iterator_get_element(&prot_it);
2778 
2779                         if (de_get_element_type(element) != DE_UUID) continue;
2780 
2781                         uuid = de_get_uuid32(element);
2782                         des_iterator_next(&prot_it);
2783                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
2784                         switch (uuid){
2785                             case BLUETOOTH_PROTOCOL_L2CAP:
2786                                 if (!des_iterator_has_more(&prot_it)) continue;
2787                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
2788                                 break;
2789                             default:
2790                                 break;
2791                         }
2792                     }
2793                     break;
2794 
2795                 default:
2796                     break;
2797             }
2798         }
2799     }
2800 }
2801 
2802 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2803     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
2804     btstack_assert(gatt_client != NULL);
2805     uint8_t status;
2806 
2807     // TODO: handle sdp events, get l2cap psm
2808     switch (hci_event_packet_get_type(packet)){
2809         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
2810             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
2811             // TODO:
2812             return;
2813         case SDP_EVENT_QUERY_COMPLETE:
2814             status = sdp_event_query_complete_get_status(packet);
2815             gatt_client_classic_active_sdp_query = NULL;
2816             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
2817             if (status != ERROR_CODE_SUCCESS) break;
2818             if (gatt_client->l2cap_psm == 0) {
2819                 status = SDP_SERVICE_NOT_FOUND;
2820                 break;
2821             }
2822             break;
2823         default:
2824             btstack_assert(false);
2825             return;
2826     }
2827 
2828     // done
2829     if (status == ERROR_CODE_SUCCESS){
2830         gatt_client->gatt_client_state = P_W4_L2CAP_CONNECTION;
2831         status = l2cap_create_channel(gatt_client_l2cap_handler, gatt_client->addr, gatt_client->l2cap_psm, 0xffff,
2832                              &gatt_client->l2cap_cid);
2833     }
2834     if (status != ERROR_CODE_SUCCESS) {
2835         gatt_client_classic_handle_connected(gatt_client, status);
2836     }
2837 }
2838 
2839 static void gatt_client_classic_sdp_start(void * context){
2840     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
2841     gatt_client_classic_active_sdp_query->gatt_client_state = P_W4_SDP_QUERY;
2842     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
2843 }
2844 
2845 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
2846     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
2847     if (gatt_client != NULL){
2848         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
2849     }
2850     gatt_client = btstack_memory_gatt_client_get();
2851     if (gatt_client == NULL){
2852         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
2853     }
2854     // init state
2855     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
2856     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
2857     memcpy(gatt_client->addr, addr, 6);
2858     gatt_client->mtu = ATT_DEFAULT_MTU;
2859     gatt_client->security_level = LEVEL_0;
2860     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
2861     gatt_client->gatt_client_state = P_W2_SDP_QUERY;
2862     gatt_client->sdp_query_request.callback = &gatt_client_classic_sdp_start;
2863     gatt_client->sdp_query_request.context = gatt_client;
2864     gatt_client->callback = callback;
2865 #ifdef ENABLE_GATT_OVER_EATT
2866     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
2867 #endif
2868     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
2869     sdp_client_register_query_callback(&gatt_client->sdp_query_request);
2870     return ERROR_CODE_SUCCESS;
2871 }
2872 
2873 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2874     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
2875     if (gatt_client == NULL){
2876         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2877     }
2878     gatt_client->callback = callback;
2879     return l2cap_disconnect(gatt_client->l2cap_cid);
2880 }
2881 #endif
2882 
2883 #ifdef ENABLE_GATT_OVER_EATT
2884 
2885 #define MAX_NR_EATT_CHANNELS 5
2886 static void gatt_client_le_enhanced_failed(gatt_client_t * gatt_client, uint8_t status){
2887     // TODO: emit failed
2888 }
2889 
2890 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
2891     gatt_client_t *gatt_client = NULL;
2892     hci_con_handle_t con_handle;
2893     uint8_t status;
2894     gatt_client_characteristic_t characteristic;
2895     switch (packet_type) {
2896         case HCI_EVENT_PACKET:
2897             switch (hci_event_packet_get_type(packet)) {
2898                 log_info("HCI Event 0x%02x", hci_event_packet_get_type(packet));
2899                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
2900                     log_info("GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT");
2901                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
2902                     gatt_client = gatt_client_get_context_for_handle(con_handle);
2903                     btstack_assert(gatt_client != NULL);
2904                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_VALUE);
2905                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
2906                         uint8_t server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
2907                         if ((server_supported_features & 1) != 0) {
2908                             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
2909                             break;
2910                         }
2911                     }
2912                     gatt_client_le_enhanced_failed(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
2913                     break;
2914                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
2915                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
2916                     gatt_client = gatt_client_get_context_for_handle(con_handle);
2917                     btstack_assert(gatt_client != NULL);
2918                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_CHARACTERISTIC);
2919                     log_info("GATT_EVENT_CHARACTERISTIC_QUERY_RESULT value handle 0x%04x", characteristic.value_handle);
2920                     if (characteristic.uuid16 == ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES){
2921                         gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
2922                         gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
2923                         log_info("GATT_EVENT_CHARACTERISTIC_QUERY_RESULT - ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES");
2924                     }
2925                     break;
2926                 case GATT_EVENT_QUERY_COMPLETE:
2927                     con_handle = gatt_event_query_complete_get_handle(packet);
2928                     gatt_client = gatt_client_get_context_for_handle(con_handle);
2929                     btstack_assert(gatt_client != NULL);
2930                     break;
2931                 default:
2932                     break;
2933             }
2934             break;
2935         default:
2936             break;
2937     }
2938 }
2939 
2940 static bool gatt_client_eatt_handle_can_send_query(gatt_client_t * gatt_client){
2941     uint8_t status = ERROR_CODE_SUCCESS;
2942     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
2943     switch (gatt_client->eatt_state){
2944         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
2945             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_VALUE;
2946             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
2947                                                                          gatt_client->con_handle, 0x0001, 0xffff,
2948                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
2949             btstack_assert(status == ERROR_CODE_SUCCESS);
2950             return true;
2951         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
2952             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_CHARACTERISTIC;
2953             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
2954                                                                                      gatt_client->con_handle, 0x0001,
2955                                                                                      0xffff, ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
2956             btstack_assert(status == ERROR_CODE_SUCCESS);
2957             return true;
2958         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
2959             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
2960             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
2961                                                                gatt_client->gatt_client_supported_features_handle, 1,
2962                                                                &gatt_client_supported_features);
2963             btstack_assert(status == ERROR_CODE_SUCCESS);
2964             return true;
2965         default:
2966             break;
2967     }
2968     return false;
2969 }
2970 
2971 uint8_t gatt_client_le_enhanced_connect(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint8_t num_channels, uint8_t * storage_buffer, uint16_t storage_size) {
2972     gatt_client_t * gatt_client;
2973     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2974     if (status != ERROR_CODE_SUCCESS){
2975         return status;
2976     }
2977 
2978     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
2979         return ERROR_CODE_COMMAND_DISALLOWED;
2980     }
2981 
2982     gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
2983     gatt_client_notify_can_send_query(gatt_client);
2984 
2985     return ERROR_CODE_SUCCESS;
2986 }
2987 
2988 #endif
2989 
2990 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2991 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2992     gatt_client_att_packet_handler(packet_type, handle, packet, size);
2993 }
2994 
2995 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
2996     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
2997     return status;
2998 }
2999 #endif
3000