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