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