xref: /btstack/src/ble/gatt_client.c (revision 7045d3c0508e74262a4882ca3c46d45a91a9ca79)
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 att_status;
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                         att_status = ATT_ERROR_SUCCESS;
1773                     } else {
1774                         att_status = ATT_ERROR_DATA_MISMATCH;
1775                     }
1776                     emit_gatt_complete_event(gatt_client, att_status);
1777                     break;
1778 
1779                 case P_W4_PREPARE_WRITE_RESULT: {
1780                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1781                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1782                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1783                     break;
1784                 }
1785                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT: {
1786                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1787                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR,
1788                                                      P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1789                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1790                     break;
1791                 }
1792                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT: {
1793                     if (is_value_valid(gatt_client, packet, size)) {
1794                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1795                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE,
1796                                                          P_W2_EXECUTE_PREPARED_WRITE);
1797                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1798                         break;
1799                     }
1800                     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1801                     break;
1802                 }
1803                 default:
1804                     break;
1805             }
1806             break;
1807 
1808         case ATT_EXECUTE_WRITE_RESPONSE:
1809             switch (gatt_client->gatt_client_state) {
1810                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1811                     gatt_client_handle_transaction_complete(gatt_client);
1812                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1813                     break;
1814                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1815                     gatt_client_handle_transaction_complete(gatt_client);
1816                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1817                     break;
1818                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1819                     gatt_client_handle_transaction_complete(gatt_client);
1820                     emit_gatt_complete_event(gatt_client, ATT_ERROR_DATA_MISMATCH);
1821                     break;
1822                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1823                     gatt_client_handle_transaction_complete(gatt_client);
1824                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1825                     break;
1826                 default:
1827                     break;
1828 
1829             }
1830             break;
1831 
1832         case ATT_READ_MULTIPLE_RESPONSE:
1833             switch (gatt_client->gatt_client_state) {
1834                 case P_W4_READ_MULTIPLE_RESPONSE:
1835                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
1836                     gatt_client_handle_transaction_complete(gatt_client);
1837                     emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1838                     break;
1839                 default:
1840                     break;
1841             }
1842             break;
1843 
1844         case ATT_ERROR_RESPONSE:
1845             if (size < 5u) return;
1846             att_status = packet[4];
1847             switch (att_status) {
1848                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1849                     switch (gatt_client->gatt_client_state) {
1850                         case P_W4_SERVICE_QUERY_RESULT:
1851                         case P_W4_SERVICE_WITH_UUID_RESULT:
1852                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1853                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1854                             gatt_client_handle_transaction_complete(gatt_client);
1855                             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1856                             break;
1857                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1858                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1859                             characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1860                             gatt_client_handle_transaction_complete(gatt_client);
1861                             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1862                             break;
1863                         case P_W4_READ_BY_TYPE_RESPONSE:
1864                             gatt_client_handle_transaction_complete(gatt_client);
1865                             if (gatt_client->start_group_handle == gatt_client->query_start_handle) {
1866                                 att_status = ATT_ERROR_ATTRIBUTE_NOT_FOUND;
1867                             } else {
1868                                 att_status = ATT_ERROR_SUCCESS;
1869                             }
1870                             emit_gatt_complete_event(gatt_client, att_status);
1871                             break;
1872                         default:
1873                             gatt_client_report_error_if_pending(gatt_client, att_status);
1874                             break;
1875                     }
1876                     break;
1877                 }
1878 
1879 #ifdef ENABLE_GATT_CLIENT_PAIRING
1880 
1881                     case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
1882                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
1883                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
1884 
1885                         // security too low
1886                         if (gatt_client->security_counter > 0) {
1887                             gatt_client_report_error_if_pending(gatt_client, att_status);
1888                             break;
1889                         }
1890                         // start security
1891                         gatt_client->security_counter++;
1892 
1893                         // setup action
1894                         int retry = 1;
1895                         switch (gatt_client->gatt_client_state){
1896                             case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1897                                 gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
1898                                 break;
1899                             case P_W4_READ_BLOB_RESULT:
1900                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1901                                 break;
1902                             case P_W4_READ_BY_TYPE_RESPONSE:
1903                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
1904                                 break;
1905                             case P_W4_READ_MULTIPLE_RESPONSE:
1906                                 gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
1907                                 break;
1908                             case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1909                                 gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
1910                                 break;
1911                             case P_W4_PREPARE_WRITE_RESULT:
1912                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
1913                                 break;
1914                             case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1915                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
1916                                 break;
1917                             case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
1918                                 gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
1919                                 break;
1920                             case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1921                                 gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
1922                                 break;
1923                             case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1924                                 gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
1925                                 break;
1926                             case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1927                                 gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1928                                 break;
1929                             case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1930                                 gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
1931                                 break;
1932                             case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1933                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
1934                                 break;
1935                             case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1936                                 gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
1937                                 break;
1938                             case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1939                                 gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1940                                 break;
1941                             case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1942                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
1943                                 break;
1944                             case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1945                                 gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
1946                                 break;
1947 #ifdef ENABLE_LE_SIGNED_WRITE
1948                             case P_W4_SEND_SINGED_WRITE_DONE:
1949                                 gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
1950                                 break;
1951 #endif
1952                             default:
1953                                 log_info("retry not supported for state %x", gatt_client->gatt_client_state);
1954                                 retry = 0;
1955                                 break;
1956                         }
1957 
1958                         if (!retry) {
1959                             gatt_client_report_error_if_pending(gatt_client, att_status);
1960                             break;
1961                         }
1962 
1963                         log_info("security error, start pairing");
1964 
1965                         // start pairing for higher security level
1966                         gatt_client->wait_for_authentication_complete = 1;
1967                         gatt_client->pending_error_code = att_status;
1968                         sm_request_pairing(gatt_client->con_handle);
1969                         break;
1970                     }
1971 #endif
1972 
1973                     // nothing we can do about that
1974                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
1975                 default:
1976                     gatt_client_report_error_if_pending(gatt_client, att_status);
1977                     break;
1978             }
1979             break;
1980 
1981         default:
1982             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
1983             break;
1984     }
1985 }
1986 
1987 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size) {
1988     gatt_client_t *gatt_client;
1989     if (size < 1u) return;
1990 
1991     if (packet_type == HCI_EVENT_PACKET) {
1992         switch (packet[0]) {
1993             case L2CAP_EVENT_CAN_SEND_NOW:
1994                 gatt_client_run();
1995                 break;
1996                 // att_server has negotiated the mtu for this connection, cache if context exists
1997             case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
1998                 if (size < 6u) break;
1999                 gatt_client = gatt_client_get_context_for_handle(handle);
2000                 if (gatt_client == NULL) break;
2001                 gatt_client->mtu = little_endian_read_16(packet, 4);
2002                 break;
2003             default:
2004                 break;
2005         }
2006         return;
2007     }
2008 
2009     if (packet_type != ATT_DATA_PACKET) return;
2010 
2011     // special cases: notifications & indications motivate creating context
2012     switch (packet[0]) {
2013         case ATT_HANDLE_VALUE_NOTIFICATION:
2014         case ATT_HANDLE_VALUE_INDICATION:
2015             gatt_client_provide_context_for_handle(handle, &gatt_client);
2016             break;
2017         default:
2018             gatt_client = gatt_client_get_context_for_handle(handle);
2019             break;
2020     }
2021 
2022     if (gatt_client != NULL) {
2023         gatt_client_handle_att_response(gatt_client, packet, size);
2024         gatt_client_run();
2025     }
2026 }
2027 
2028 #ifdef ENABLE_LE_SIGNED_WRITE
2029 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2030     btstack_linked_list_iterator_t it;
2031     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2032     while (btstack_linked_list_iterator_has_next(&it)){
2033         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2034         if (gatt_client->gatt_client_state == P_W4_CMAC_RESULT){
2035             // store result
2036             (void)memcpy(gatt_client->cmac, hash, 8);
2037             // reverse_64(hash, gatt_client->cmac);
2038             gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
2039             gatt_client_run();
2040             return;
2041         }
2042     }
2043 }
2044 
2045 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){
2046     gatt_client_t * gatt_client;
2047     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2048     if (status != ERROR_CODE_SUCCESS){
2049         return status;
2050     }
2051     if (is_ready(gatt_client) == 0){
2052         return GATT_CLIENT_IN_WRONG_STATE;
2053     }
2054 
2055     gatt_client->callback = callback;
2056     gatt_client->attribute_handle = value_handle;
2057     gatt_client->attribute_length = message_len;
2058     gatt_client->attribute_value = message;
2059     gatt_client->gatt_client_state = P_W4_IDENTITY_RESOLVING;
2060     gatt_client_run();
2061     return ERROR_CODE_SUCCESS;
2062 }
2063 #endif
2064 
2065 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2066     gatt_client_t * gatt_client;
2067     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2068     if (status != ERROR_CODE_SUCCESS){
2069         return status;
2070     }
2071 
2072     gatt_client->callback = callback;
2073     gatt_client->start_group_handle = 0x0001;
2074     gatt_client->end_group_handle   = 0xffff;
2075     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
2076     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2077     gatt_client_run();
2078     return ERROR_CODE_SUCCESS;
2079 }
2080 
2081 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2082     gatt_client_t * gatt_client;
2083     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2084     if (status != ERROR_CODE_SUCCESS){
2085         return status;
2086     }
2087 
2088     gatt_client->callback = callback;
2089     gatt_client->start_group_handle = 0x0001;
2090     gatt_client->end_group_handle   = 0xffff;
2091     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_QUERY;
2092     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2093     gatt_client_run();
2094     return ERROR_CODE_SUCCESS;
2095 }
2096 
2097 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2098     gatt_client_t * gatt_client;
2099     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2100     if (status != ERROR_CODE_SUCCESS){
2101         return status;
2102     }
2103 
2104     gatt_client->callback = callback;
2105     gatt_client->start_group_handle = 0x0001;
2106     gatt_client->end_group_handle   = 0xffff;
2107     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2108     gatt_client->uuid16 = uuid16;
2109     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2110     gatt_client_run();
2111     return ERROR_CODE_SUCCESS;
2112 }
2113 
2114 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2115     gatt_client_t * gatt_client;
2116     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2117     if (status != ERROR_CODE_SUCCESS){
2118         return status;
2119     }
2120 
2121     gatt_client->callback = callback;
2122     gatt_client->start_group_handle = 0x0001;
2123     gatt_client->end_group_handle   = 0xffff;
2124     gatt_client->uuid16 = 0;
2125     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2126     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2127     gatt_client_run();
2128     return ERROR_CODE_SUCCESS;
2129 }
2130 
2131 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2132     gatt_client_t * gatt_client;
2133     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2134     if (status != ERROR_CODE_SUCCESS){
2135         return status;
2136     }
2137 
2138     gatt_client->callback = callback;
2139     gatt_client->start_group_handle = service->start_group_handle;
2140     gatt_client->end_group_handle   = service->end_group_handle;
2141     gatt_client->filter_with_uuid = 0;
2142     gatt_client->characteristic_start_handle = 0;
2143     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2144     gatt_client_run();
2145     return ERROR_CODE_SUCCESS;
2146 }
2147 
2148 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){
2149     gatt_client_t * gatt_client;
2150     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2151     if (status != ERROR_CODE_SUCCESS){
2152         return status;
2153     }
2154 
2155     gatt_client->callback = callback;
2156     gatt_client->start_group_handle = service->start_group_handle;
2157     gatt_client->end_group_handle   = service->end_group_handle;
2158     gatt_client->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2159 
2160     gatt_client_run();
2161     return ERROR_CODE_SUCCESS;
2162 }
2163 
2164 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){
2165     gatt_client_t * gatt_client;
2166     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2167     if (status != ERROR_CODE_SUCCESS){
2168         return status;
2169     }
2170 
2171     gatt_client->callback = callback;
2172     gatt_client->start_group_handle = start_handle;
2173     gatt_client->end_group_handle   = end_handle;
2174     gatt_client->filter_with_uuid = 1;
2175     gatt_client->uuid16 = uuid16;
2176     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2177     gatt_client->characteristic_start_handle = 0;
2178     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2179     gatt_client_run();
2180     return ERROR_CODE_SUCCESS;
2181 }
2182 
2183 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){
2184     gatt_client_t * gatt_client;
2185     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2186     if (status != ERROR_CODE_SUCCESS){
2187         return status;
2188     }
2189 
2190     gatt_client->callback = callback;
2191     gatt_client->start_group_handle = start_handle;
2192     gatt_client->end_group_handle   = end_handle;
2193     gatt_client->filter_with_uuid = 1;
2194     gatt_client->uuid16 = 0;
2195     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2196     gatt_client->characteristic_start_handle = 0;
2197     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2198     gatt_client_run();
2199     return ERROR_CODE_SUCCESS;
2200 }
2201 
2202 
2203 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){
2204     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2205 }
2206 
2207 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){
2208     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2209 }
2210 
2211 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2212     gatt_client_t * gatt_client;
2213     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2214     if (status != ERROR_CODE_SUCCESS){
2215         return status;
2216     }
2217 
2218     if (characteristic->value_handle == characteristic->end_handle){
2219         return ERROR_CODE_SUCCESS;
2220     }
2221     gatt_client->callback = callback;
2222     gatt_client->start_group_handle = characteristic->value_handle + 1u;
2223     gatt_client->end_group_handle   = characteristic->end_handle;
2224     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2225     gatt_client_run();
2226     return ERROR_CODE_SUCCESS;
2227 }
2228 
2229 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){
2230     gatt_client_t * gatt_client;
2231     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2232     if (status != ERROR_CODE_SUCCESS){
2233         return status;
2234     }
2235 
2236     gatt_client->callback = callback;
2237     gatt_client->attribute_handle = value_handle;
2238     gatt_client->attribute_offset = 0;
2239     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2240     gatt_client_run();
2241     return ERROR_CODE_SUCCESS;
2242 }
2243 
2244 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){
2245     gatt_client_t * gatt_client;
2246     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2247     if (status != ERROR_CODE_SUCCESS){
2248         return status;
2249     }
2250 
2251     gatt_client->callback = callback;
2252     gatt_client->start_group_handle = start_handle;
2253     gatt_client->end_group_handle = end_handle;
2254     gatt_client->query_start_handle = start_handle;
2255     gatt_client->query_end_handle = end_handle;
2256     gatt_client->uuid16 = uuid16;
2257     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2258     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2259     gatt_client_run();
2260     return ERROR_CODE_SUCCESS;
2261 }
2262 
2263 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){
2264     gatt_client_t * gatt_client;
2265     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2266     if (status != ERROR_CODE_SUCCESS){
2267         return status;
2268     }
2269 
2270     gatt_client->callback = callback;
2271     gatt_client->start_group_handle = start_handle;
2272     gatt_client->end_group_handle = end_handle;
2273     gatt_client->query_start_handle = start_handle;
2274     gatt_client->query_end_handle = end_handle;
2275     gatt_client->uuid16 = 0;
2276     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2277     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2278     gatt_client_run();
2279     return ERROR_CODE_SUCCESS;
2280 }
2281 
2282 
2283 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2284     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2285 }
2286 
2287 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){
2288     gatt_client_t * gatt_client;
2289     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2290     if (status != ERROR_CODE_SUCCESS){
2291         return status;
2292     }
2293 
2294     gatt_client->callback = callback;
2295     gatt_client->attribute_handle = value_handle;
2296     gatt_client->attribute_offset = offset;
2297     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
2298     gatt_client_run();
2299     return ERROR_CODE_SUCCESS;
2300 }
2301 
2302 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){
2303     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2304 }
2305 
2306 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){
2307     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2308 }
2309 
2310 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){
2311     gatt_client_t * gatt_client;
2312     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2313     if (status != ERROR_CODE_SUCCESS){
2314         return status;
2315     }
2316 
2317     gatt_client->callback = callback;
2318     gatt_client->read_multiple_handle_count = num_value_handles;
2319     gatt_client->read_multiple_handles = value_handles;
2320     gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2321     gatt_client_run();
2322     return ERROR_CODE_SUCCESS;
2323 }
2324 
2325 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){
2326     gatt_client_t * gatt_client;
2327     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2328     if (status != ERROR_CODE_SUCCESS){
2329         return status;
2330     }
2331 
2332     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2333     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2334 
2335     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2336 }
2337 
2338 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){
2339     gatt_client_t * gatt_client;
2340     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2341     if (status != ERROR_CODE_SUCCESS){
2342         return status;
2343     }
2344 
2345     gatt_client->callback = callback;
2346     gatt_client->attribute_handle = value_handle;
2347     gatt_client->attribute_length = value_length;
2348     gatt_client->attribute_value = value;
2349     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2350     gatt_client_run();
2351     return ERROR_CODE_SUCCESS;
2352 }
2353 
2354 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){
2355     gatt_client_t * gatt_client;
2356     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2357     if (status != ERROR_CODE_SUCCESS){
2358         return status;
2359     }
2360 
2361     gatt_client->callback = callback;
2362     gatt_client->attribute_handle = value_handle;
2363     gatt_client->attribute_length = value_length;
2364     gatt_client->attribute_offset = offset;
2365     gatt_client->attribute_value = value;
2366     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
2367     gatt_client_run();
2368     return ERROR_CODE_SUCCESS;
2369 }
2370 
2371 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){
2372     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2373 }
2374 
2375 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){
2376     gatt_client_t * gatt_client;
2377     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2378     if (status != ERROR_CODE_SUCCESS){
2379         return status;
2380     }
2381 
2382     gatt_client->callback = callback;
2383     gatt_client->attribute_handle = value_handle;
2384     gatt_client->attribute_length = value_length;
2385     gatt_client->attribute_offset = 0;
2386     gatt_client->attribute_value = value;
2387     gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
2388     gatt_client_run();
2389     return ERROR_CODE_SUCCESS;
2390 }
2391 
2392 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){
2393     gatt_client_t * gatt_client;
2394     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2395     if (status != ERROR_CODE_SUCCESS){
2396         return status;
2397     }
2398 
2399     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2400         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2401         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2402         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2403     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2404                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2405         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2406         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2407     }
2408 
2409     gatt_client->callback = callback;
2410     gatt_client->start_group_handle = characteristic->value_handle;
2411     gatt_client->end_group_handle = characteristic->end_handle;
2412     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2413 
2414 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2415     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2416 #else
2417     gatt_client->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2418 #endif
2419     gatt_client_run();
2420     return ERROR_CODE_SUCCESS;
2421 }
2422 
2423 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){
2424     gatt_client_t * gatt_client;
2425     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2426     if (status != ERROR_CODE_SUCCESS){
2427         return status;
2428     }
2429 
2430     gatt_client->callback = callback;
2431     gatt_client->attribute_handle = descriptor_handle;
2432 
2433     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2434     gatt_client_run();
2435     return ERROR_CODE_SUCCESS;
2436 }
2437 
2438 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2439     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2440 }
2441 
2442 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){
2443     gatt_client_t * gatt_client;
2444     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2445     if (status != ERROR_CODE_SUCCESS){
2446         return status;
2447     }
2448 
2449     gatt_client->callback = callback;
2450     gatt_client->attribute_handle = descriptor_handle;
2451     gatt_client->attribute_offset = offset;
2452     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2453     gatt_client_run();
2454     return ERROR_CODE_SUCCESS;
2455 }
2456 
2457 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){
2458     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2459 }
2460 
2461 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){
2462     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2463 }
2464 
2465 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){
2466     gatt_client_t * gatt_client;
2467     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2468     if (status != ERROR_CODE_SUCCESS){
2469         return status;
2470     }
2471 
2472     gatt_client->callback = callback;
2473     gatt_client->attribute_handle = descriptor_handle;
2474     gatt_client->attribute_length = value_length;
2475     gatt_client->attribute_offset = 0;
2476     gatt_client->attribute_value = value;
2477     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2478     gatt_client_run();
2479     return ERROR_CODE_SUCCESS;
2480 }
2481 
2482 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){
2483     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2484 }
2485 
2486 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){
2487     gatt_client_t * gatt_client;
2488     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2489     if (status != ERROR_CODE_SUCCESS){
2490         return status;
2491     }
2492 
2493     gatt_client->callback = callback;
2494     gatt_client->attribute_handle = descriptor_handle;
2495     gatt_client->attribute_length = value_length;
2496     gatt_client->attribute_offset = offset;
2497     gatt_client->attribute_value = value;
2498     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2499     gatt_client_run();
2500     return ERROR_CODE_SUCCESS;
2501 }
2502 
2503 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){
2504     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2505 }
2506 
2507 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){
2508     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2509 }
2510 
2511 /**
2512  * @brief -> gatt complete event
2513  */
2514 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){
2515     gatt_client_t * gatt_client;
2516     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2517     if (status != ERROR_CODE_SUCCESS){
2518         return status;
2519     }
2520 
2521     gatt_client->callback = callback;
2522     gatt_client->attribute_handle = attribute_handle;
2523     gatt_client->attribute_length = value_length;
2524     gatt_client->attribute_offset = offset;
2525     gatt_client->attribute_value = value;
2526     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
2527     gatt_client_run();
2528     return ERROR_CODE_SUCCESS;
2529 }
2530 
2531 /**
2532  * @brief -> gatt complete event
2533  */
2534 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2535     gatt_client_t * gatt_client;
2536     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2537     if (status != ERROR_CODE_SUCCESS){
2538         return status;
2539     }
2540 
2541     gatt_client->callback = callback;
2542     gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
2543     gatt_client_run();
2544     return ERROR_CODE_SUCCESS;
2545 }
2546 
2547 /**
2548  * @brief -> gatt complete event
2549  */
2550 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2551     gatt_client_t * gatt_client;
2552     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2553     if (status != ERROR_CODE_SUCCESS){
2554         return status;
2555     }
2556 
2557     gatt_client->callback = callback;
2558     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
2559     gatt_client_run();
2560     return ERROR_CODE_SUCCESS;
2561 }
2562 
2563 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
2564     service->start_group_handle = little_endian_read_16(packet, offset);
2565     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2566     reverse_128(&packet[offset + 4], service->uuid128);
2567     if (uuid_has_bluetooth_prefix(service->uuid128)){
2568         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2569     } else {
2570         service->uuid16 = 0;
2571     }
2572 }
2573 
2574 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2575     characteristic->start_handle = little_endian_read_16(packet, offset);
2576     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2577     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2578     characteristic->properties = little_endian_read_16(packet, offset + 6);
2579     reverse_128(&packet[offset+8], characteristic->uuid128);
2580     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2581         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2582     } else {
2583         characteristic->uuid16 = 0;
2584     }
2585 }
2586 
2587 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2588     descriptor->handle = little_endian_read_16(packet, offset);
2589     reverse_128(&packet[offset+2], descriptor->uuid128);
2590     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2591         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2592     } else {
2593         descriptor->uuid16 = 0;
2594     }
2595 }
2596 
2597 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2598     gatt_client_t * gatt_client;
2599     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2600     if (status != ERROR_CODE_SUCCESS){
2601         return;
2602     }
2603     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2604         gatt_client->callback = callback;
2605         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
2606         gatt_client_run();
2607     }
2608 }
2609 
2610 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2611     gatt_client_t * gatt_client;
2612     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2613     if (status != ERROR_CODE_SUCCESS){
2614         return status;
2615     }
2616     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
2617     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2618     if (added){
2619         return ERROR_CODE_SUCCESS;
2620     } else {
2621         return ERROR_CODE_COMMAND_DISALLOWED;
2622     }
2623 }
2624 
2625 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2626     gatt_client_t * gatt_client;
2627     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2628     if (status != ERROR_CODE_SUCCESS){
2629         return status;
2630     }
2631     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
2632     gatt_client_notify_can_send_query(gatt_client);
2633     if (added){
2634         return ERROR_CODE_SUCCESS;
2635     } else {
2636         return ERROR_CODE_COMMAND_DISALLOWED;
2637     }
2638 }
2639 
2640 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2641     gatt_client_t * gatt_client;
2642     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2643     if (status != ERROR_CODE_SUCCESS){
2644         return status;
2645     }
2646     if (gatt_client->write_without_response_callback != NULL){
2647         return GATT_CLIENT_IN_WRONG_STATE;
2648     }
2649     gatt_client->write_without_response_callback = callback;
2650     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2651     return ERROR_CODE_SUCCESS;
2652 }
2653 
2654 #ifdef ENABLE_GATT_OVER_CLASSIC
2655 
2656 #include "hci_event.h"
2657 
2658 // single active SDP query
2659 static gatt_client_t * gatt_client_classic_active_sdp_query;
2660 
2661 // macos protocol descriptor list requires 16 bytes
2662 static uint8_t gatt_client_classic_sdp_buffer[32];
2663 
2664 static const hci_event_t gatt_client_connected = {
2665         GATT_EVENT_CONNECTED, 0, "1BH"
2666 };
2667 
2668 static const hci_event_t gatt_client_disconnected = {
2669         GATT_EVENT_DISCONNECTED, 0, "H"
2670 };
2671 
2672 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
2673     btstack_linked_item_t *it;
2674     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2675         gatt_client_t * gatt_client = (gatt_client_t *) it;
2676         if (memcmp(gatt_client->addr, addr, 6) == 0){
2677             return gatt_client;
2678         }
2679     }
2680     return NULL;
2681 }
2682 
2683 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
2684     btstack_linked_item_t *it;
2685     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2686         gatt_client_t * gatt_client = (gatt_client_t *) it;
2687         if (gatt_client->l2cap_cid == l2cap_cid){
2688             return gatt_client;
2689         }
2690     }
2691     return NULL;
2692 }
2693 
2694 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
2695     bd_addr_t addr;
2696     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
2697     memcpy(addr, gatt_client->addr, 6);
2698     hci_con_handle_t con_handle = gatt_client->con_handle;
2699     btstack_packet_handler_t callback = gatt_client->callback;
2700     if (status != ERROR_CODE_SUCCESS){
2701         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2702         btstack_memory_gatt_client_free(gatt_client);
2703     }
2704     uint8_t buffer[20];
2705     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr,
2706                                                                 con_handle);
2707     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2708 }
2709 
2710 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
2711 
2712     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
2713     gatt_client_timeout_stop(gatt_client);
2714 
2715     hci_con_handle_t con_handle = gatt_client->con_handle;
2716     btstack_packet_handler_t callback = gatt_client->callback;
2717     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2718     btstack_memory_gatt_client_free(gatt_client);
2719 
2720     uint8_t buffer[20];
2721     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
2722     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2723 }
2724 
2725 static void gatt_client_l2cap_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2726     gatt_client_t * gatt_client = NULL;
2727     uint8_t status;
2728     switch (packet_type){
2729         case HCI_EVENT_PACKET:
2730             switch (hci_event_packet_get_type(packet)) {
2731                 case L2CAP_EVENT_CHANNEL_OPENED:
2732                     status = l2cap_event_channel_opened_get_status(packet);
2733                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_opened_get_local_cid(packet));
2734                     btstack_assert(gatt_client != NULL);
2735                     // if status != 0, gatt_client will be discarded
2736                     gatt_client->gatt_client_state = P_READY;
2737                     gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2738                     gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2739                     gatt_client_classic_handle_connected(gatt_client, status);
2740                     break;
2741                 case L2CAP_EVENT_CHANNEL_CLOSED:
2742                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2743                     gatt_client_classic_handle_disconnected(gatt_client);
2744                     break;
2745                 default:
2746                     break;
2747             }
2748             break;
2749         case L2CAP_DATA_PACKET:
2750             gatt_client = gatt_client_get_context_for_l2cap_cid(channel);
2751             btstack_assert(gatt_client != NULL);
2752             gatt_client_handle_att_response(gatt_client, packet, size);
2753             gatt_client_run();
2754             break;
2755         default:
2756             break;
2757     }
2758 }
2759 
2760 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
2761     des_iterator_t des_list_it;
2762     des_iterator_t prot_it;
2763 
2764     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
2765         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
2766         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
2767             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
2768                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
2769                     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)) {
2770                         uint8_t       *des_element;
2771                         uint8_t       *element;
2772                         uint32_t       uuid;
2773 
2774                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
2775 
2776                         des_element = des_iterator_get_element(&des_list_it);
2777                         des_iterator_init(&prot_it, des_element);
2778                         element = des_iterator_get_element(&prot_it);
2779 
2780                         if (de_get_element_type(element) != DE_UUID) continue;
2781 
2782                         uuid = de_get_uuid32(element);
2783                         des_iterator_next(&prot_it);
2784                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
2785                         switch (uuid){
2786                             case BLUETOOTH_PROTOCOL_L2CAP:
2787                                 if (!des_iterator_has_more(&prot_it)) continue;
2788                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
2789                                 break;
2790                             default:
2791                                 break;
2792                         }
2793                     }
2794                     break;
2795 
2796                 default:
2797                     break;
2798             }
2799         }
2800     }
2801 }
2802 
2803 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2804     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
2805     btstack_assert(gatt_client != NULL);
2806     uint8_t status;
2807 
2808     // TODO: handle sdp events, get l2cap psm
2809     switch (hci_event_packet_get_type(packet)){
2810         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
2811             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
2812             // TODO:
2813             return;
2814         case SDP_EVENT_QUERY_COMPLETE:
2815             status = sdp_event_query_complete_get_status(packet);
2816             gatt_client_classic_active_sdp_query = NULL;
2817             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
2818             if (status != ERROR_CODE_SUCCESS) break;
2819             if (gatt_client->l2cap_psm == 0) {
2820                 status = SDP_SERVICE_NOT_FOUND;
2821                 break;
2822             }
2823             break;
2824         default:
2825             btstack_assert(false);
2826             return;
2827     }
2828 
2829     // done
2830     if (status == ERROR_CODE_SUCCESS){
2831         gatt_client->gatt_client_state = P_W4_L2CAP_CONNECTION;
2832         status = l2cap_create_channel(gatt_client_l2cap_handler, gatt_client->addr, gatt_client->l2cap_psm, 0xffff,
2833                              &gatt_client->l2cap_cid);
2834     }
2835     if (status != ERROR_CODE_SUCCESS) {
2836         gatt_client_classic_handle_connected(gatt_client, status);
2837     }
2838 }
2839 
2840 static void gatt_client_classic_sdp_start(void * context){
2841     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
2842     gatt_client_classic_active_sdp_query->gatt_client_state = P_W4_SDP_QUERY;
2843     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
2844 }
2845 
2846 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
2847     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
2848     if (gatt_client != NULL){
2849         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
2850     }
2851     gatt_client = btstack_memory_gatt_client_get();
2852     if (gatt_client == NULL){
2853         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
2854     }
2855     // init state
2856     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
2857     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
2858     memcpy(gatt_client->addr, addr, 6);
2859     gatt_client->mtu = ATT_DEFAULT_MTU;
2860     gatt_client->security_level = LEVEL_0;
2861     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
2862     gatt_client->gatt_client_state = P_W2_SDP_QUERY;
2863     gatt_client->sdp_query_request.callback = &gatt_client_classic_sdp_start;
2864     gatt_client->sdp_query_request.context = gatt_client;
2865     gatt_client->callback = callback;
2866 #ifdef ENABLE_GATT_OVER_EATT
2867     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
2868 #endif
2869     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
2870     sdp_client_register_query_callback(&gatt_client->sdp_query_request);
2871     return ERROR_CODE_SUCCESS;
2872 }
2873 
2874 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2875     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
2876     if (gatt_client == NULL){
2877         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2878     }
2879     gatt_client->callback = callback;
2880     return l2cap_disconnect(gatt_client->l2cap_cid);
2881 }
2882 #endif
2883 
2884 #ifdef ENABLE_GATT_OVER_EATT
2885 
2886 #define MAX_NR_EATT_CHANNELS 5
2887 static void gatt_client_le_enhanced_failed(gatt_client_t * gatt_client, uint8_t status){
2888     // TODO: emit failed
2889 }
2890 
2891 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
2892     gatt_client_t *gatt_client = NULL;
2893     hci_con_handle_t con_handle;
2894     uint8_t status;
2895     gatt_client_characteristic_t characteristic;
2896     switch (packet_type) {
2897         case HCI_EVENT_PACKET:
2898             switch (hci_event_packet_get_type(packet)) {
2899                 log_info("HCI Event 0x%02x", hci_event_packet_get_type(packet));
2900                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
2901                     log_info("GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT");
2902                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
2903                     gatt_client = gatt_client_get_context_for_handle(con_handle);
2904                     btstack_assert(gatt_client != NULL);
2905                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_VALUE);
2906                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
2907                         uint8_t server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
2908                         if ((server_supported_features & 1) != 0) {
2909                             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
2910                             break;
2911                         }
2912                     }
2913                     gatt_client_le_enhanced_failed(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
2914                     break;
2915                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
2916                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
2917                     gatt_client = gatt_client_get_context_for_handle(con_handle);
2918                     btstack_assert(gatt_client != NULL);
2919                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_CHARACTERISTIC);
2920                     log_info("GATT_EVENT_CHARACTERISTIC_QUERY_RESULT value handle 0x%04x", characteristic.value_handle);
2921                     if (characteristic.uuid16 == ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES){
2922                         gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
2923                         gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
2924                         log_info("GATT_EVENT_CHARACTERISTIC_QUERY_RESULT - ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES");
2925                     }
2926                     break;
2927                 case GATT_EVENT_QUERY_COMPLETE:
2928                     con_handle = gatt_event_query_complete_get_handle(packet);
2929                     gatt_client = gatt_client_get_context_for_handle(con_handle);
2930                     btstack_assert(gatt_client != NULL);
2931                     break;
2932                 default:
2933                     break;
2934             }
2935             break;
2936         default:
2937             break;
2938     }
2939 }
2940 
2941 static bool gatt_client_eatt_handle_can_send_query(gatt_client_t * gatt_client){
2942     uint8_t status = ERROR_CODE_SUCCESS;
2943     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
2944     switch (gatt_client->eatt_state){
2945         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
2946             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_VALUE;
2947             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
2948                                                                          gatt_client->con_handle, 0x0001, 0xffff,
2949                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
2950             btstack_assert(status == ERROR_CODE_SUCCESS);
2951             return true;
2952         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
2953             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_CHARACTERISTIC;
2954             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
2955                                                                                      gatt_client->con_handle, 0x0001,
2956                                                                                      0xffff, ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
2957             btstack_assert(status == ERROR_CODE_SUCCESS);
2958             return true;
2959         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
2960             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
2961             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
2962                                                                gatt_client->gatt_client_supported_features_handle, 1,
2963                                                                &gatt_client_supported_features);
2964             btstack_assert(status == ERROR_CODE_SUCCESS);
2965             return true;
2966         default:
2967             break;
2968     }
2969     return false;
2970 }
2971 
2972 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) {
2973     gatt_client_t * gatt_client;
2974     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2975     if (status != ERROR_CODE_SUCCESS){
2976         return status;
2977     }
2978 
2979     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
2980         return ERROR_CODE_COMMAND_DISALLOWED;
2981     }
2982 
2983     gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
2984     gatt_client_notify_can_send_query(gatt_client);
2985 
2986     return ERROR_CODE_SUCCESS;
2987 }
2988 
2989 #endif
2990 
2991 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2992 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2993     gatt_client_att_packet_handler(packet_type, handle, packet, size);
2994 }
2995 
2996 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
2997     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
2998     return status;
2999 }
3000 #endif
3001