xref: /btstack/src/ble/gatt_client.c (revision 691e02c222a09eb9f83a8342e8667a1e8850748c)
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 parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1052 #define LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE 10
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, attribute_handle);
1075     little_endian_store_16(packet, 6, offset);
1076     little_endian_store_16(packet, 8, length);
1077     return packet;
1078 }
1079 
1080 #if (LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE > CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE)
1081 #define REPORT_PREBUFFER_HEADER LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE
1082 #else
1083 #define REPORT_PREBUFFER_HEADER CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE
1084 #endif
1085 
1086 ///
1087 static void report_gatt_services(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
1088     if (size < 2) return;
1089     uint8_t attr_length = packet[1];
1090     uint8_t uuid_length = attr_length - 4u;
1091 
1092     int i;
1093     for (i = 2; (i+attr_length) <= size; i += attr_length){
1094         uint16_t start_group_handle = little_endian_read_16(packet,i);
1095         uint16_t end_group_handle   = little_endian_read_16(packet,i+2);
1096         uint8_t  uuid128[16];
1097         uint16_t uuid16 = 0;
1098 
1099         if (uuid_length == 2u){
1100             uuid16 = little_endian_read_16(packet, i+4);
1101             uuid_add_bluetooth_prefix((uint8_t*) &uuid128, uuid16);
1102         } else if (uuid_length == 16u) {
1103             reverse_128(&packet[i+4], uuid128);
1104         } else {
1105             return;
1106         }
1107         emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle, uuid128);
1108     }
1109 }
1110 
1111 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){
1112     uint8_t uuid128[16];
1113     uint16_t uuid16 = 0;
1114     if (uuid_length == 2u){
1115         uuid16 = little_endian_read_16(uuid, 0);
1116         uuid_add_bluetooth_prefix((uint8_t*) uuid128, uuid16);
1117     } else if (uuid_length == 16u){
1118         reverse_128(uuid, uuid128);
1119     } else {
1120         return;
1121     }
1122 
1123     if (gatt_client->filter_with_uuid && (memcmp(gatt_client->uuid128, uuid128, 16) != 0)) return;
1124 
1125     gatt_client->characteristic_properties = properties;
1126     gatt_client->characteristic_start_handle = start_handle;
1127     gatt_client->attribute_handle = value_handle;
1128 
1129     if (gatt_client->filter_with_uuid) return;
1130 
1131     gatt_client->uuid16 = uuid16;
1132     (void)memcpy(gatt_client->uuid128, uuid128, 16);
1133 }
1134 
1135 static void report_gatt_characteristic_end_found(gatt_client_t * gatt_client, uint16_t end_handle){
1136     // TODO: stop searching if filter and uuid found
1137 
1138     if (!gatt_client->characteristic_start_handle) return;
1139 
1140     emit_gatt_characteristic_query_result_event(gatt_client, gatt_client->characteristic_start_handle, gatt_client->attribute_handle,
1141                                                 end_handle, gatt_client->characteristic_properties, gatt_client->uuid128);
1142 
1143     gatt_client->characteristic_start_handle = 0;
1144 }
1145 
1146 
1147 static void report_gatt_characteristics(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
1148     if (size < 2u) return;
1149     uint8_t attr_length = packet[1];
1150     if ((attr_length != 7u) && (attr_length != 21u)) return;
1151     uint8_t uuid_length = attr_length - 5u;
1152     int i;
1153     for (i = 2u; (i + attr_length) <= size; i += attr_length){
1154         uint16_t start_handle = little_endian_read_16(packet, i);
1155         uint8_t  properties = packet[i+2];
1156         uint16_t value_handle = little_endian_read_16(packet, i+3);
1157         report_gatt_characteristic_end_found(gatt_client, start_handle - 1u);
1158         report_gatt_characteristic_start_found(gatt_client, start_handle, properties, value_handle, &packet[i + 5],
1159                                                uuid_length);
1160     }
1161 }
1162 
1163 static void report_gatt_included_service_uuid16(gatt_client_t * gatt_client, uint16_t include_handle, uint16_t uuid16){
1164     uint8_t normalized_uuid128[16];
1165     uuid_add_bluetooth_prefix(normalized_uuid128, uuid16);
1166     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
1167                                                   gatt_client->query_end_handle, normalized_uuid128);
1168 }
1169 
1170 static void report_gatt_included_service_uuid128(gatt_client_t * gatt_client, uint16_t include_handle, const uint8_t * uuid128){
1171     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
1172                                                   gatt_client->query_end_handle, uuid128);
1173 }
1174 
1175 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1176 static void report_gatt_notification(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
1177 	if (!gatt_client_accept_server_message(gatt_client)) return;
1178     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_NOTIFICATION, value_handle,
1179                                                          value, length);
1180     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1181 }
1182 
1183 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1184 static void report_gatt_indication(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
1185 	if (!gatt_client_accept_server_message(gatt_client)) return;
1186 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
1187     // Directly Handle GATT Service Changed and Database Hash indications
1188     if (value_handle == gatt_client->gatt_service_database_hash_value_handle){
1189         gatt_client_service_emit_database_hash(gatt_client, value, length);
1190     }
1191     if (value_handle == gatt_client->gatt_service_changed_value_handle){
1192         gatt_client_service_emit_service_changed(gatt_client, value, length);
1193     }
1194 #endif
1195     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_INDICATION, value_handle,
1196                                                          value, length);
1197     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1198 }
1199 
1200 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1201 static void report_gatt_characteristic_value(gatt_client_t * gatt_client, uint16_t attribute_handle, uint8_t * value, uint16_t length){
1202     uint8_t * packet = setup_characteristic_value_packet(
1203             gatt_client, GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT, attribute_handle, value, length);
1204     emit_event_new(gatt_client->callback, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1205 }
1206 
1207 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1208 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){
1209     uint8_t * packet = setup_long_characteristic_value_packet(gatt_client,
1210                                                               GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT,
1211                                                               attribute_handle, value_offset,
1212                                                               blob, blob_length);
1213     emit_event_new(gatt_client->callback, packet, blob_length + LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE);
1214 }
1215 
1216 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){
1217     UNUSED(value_offset);
1218     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT,
1219                                                          descriptor_handle, value,
1220                                                          value_length);
1221     emit_event_new(gatt_client->callback, packet, value_length + 8u);
1222 }
1223 
1224 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){
1225     uint8_t * packet = setup_long_characteristic_value_packet(gatt_client,
1226                                                               GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT,
1227                                                               descriptor_handle, value_offset,
1228                                                               blob, blob_length);
1229     emit_event_new(gatt_client->callback, packet, blob_length + LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE);
1230 }
1231 
1232 static void report_gatt_all_characteristic_descriptors(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size, uint16_t pair_size){
1233     int i;
1234     for (i = 0u; (i + pair_size) <= size; i += pair_size){
1235         uint16_t descriptor_handle = little_endian_read_16(packet,i);
1236         uint8_t uuid128[16];
1237         uint16_t uuid16 = 0;
1238         if (pair_size == 4u){
1239             uuid16 = little_endian_read_16(packet,i+2);
1240             uuid_add_bluetooth_prefix(uuid128, uuid16);
1241         } else {
1242             reverse_128(&packet[i+2], uuid128);
1243         }
1244         emit_gatt_all_characteristic_descriptors_result_event(gatt_client, descriptor_handle, uuid128);
1245     }
1246 
1247 }
1248 
1249 static bool is_query_done(gatt_client_t * gatt_client, uint16_t last_result_handle){
1250     return last_result_handle >= gatt_client->end_group_handle;
1251 }
1252 
1253 static void trigger_next_query(gatt_client_t * gatt_client, uint16_t last_result_handle, gatt_client_state_t next_query_state){
1254     if (is_query_done(gatt_client, last_result_handle)){
1255         gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1256         return;
1257     }
1258     // next
1259     gatt_client->start_group_handle = last_result_handle + 1u;
1260     gatt_client->state = next_query_state;
1261 }
1262 
1263 static void trigger_next_included_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1264     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_INCLUDED_SERVICE_QUERY);
1265 }
1266 
1267 static void trigger_next_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1268     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_QUERY);
1269 }
1270 
1271 static void trigger_next_service_by_uuid_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1272     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_WITH_UUID_QUERY);
1273 }
1274 
1275 static void trigger_next_characteristic_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1276     if (is_query_done(gatt_client, last_result_handle)){
1277         // report last characteristic
1278         report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1279     }
1280     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY);
1281 }
1282 
1283 static void trigger_next_characteristic_descriptor_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1284     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY);
1285 }
1286 
1287 static void trigger_next_read_by_type_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1288     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_READ_BY_TYPE_REQUEST);
1289 }
1290 
1291 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){
1292     gatt_client->attribute_offset += write_blob_length(gatt_client);
1293     uint16_t next_blob_length =  write_blob_length(gatt_client);
1294 
1295     if (next_blob_length == 0u){
1296         gatt_client->state = done_state;
1297         return;
1298     }
1299     gatt_client->state = next_query_state;
1300 }
1301 
1302 static void trigger_next_blob_query(gatt_client_t * gatt_client, gatt_client_state_t next_query_state, uint16_t received_blob_length){
1303 
1304     uint16_t max_blob_length = gatt_client->mtu - 1u;
1305     if (received_blob_length < max_blob_length){
1306         gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1307         return;
1308     }
1309 
1310     gatt_client->attribute_offset += received_blob_length;
1311     gatt_client->state = next_query_state;
1312 }
1313 
1314 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){
1315     notification->callback = callback;
1316     notification->con_handle = con_handle;
1317     if (characteristic == NULL){
1318         notification->attribute_handle = GATT_CLIENT_ANY_VALUE_HANDLE;
1319     } else {
1320         notification->attribute_handle = characteristic->value_handle;
1321     }
1322     btstack_linked_list_add(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
1323 }
1324 
1325 void gatt_client_stop_listening_for_characteristic_value_updates(gatt_client_notification_t * notification){
1326     btstack_linked_list_remove(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
1327 }
1328 
1329 static bool is_value_valid(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size){
1330     uint16_t attribute_handle = little_endian_read_16(packet, 1);
1331     uint16_t value_offset = little_endian_read_16(packet, 3);
1332 
1333     if (gatt_client->attribute_handle != attribute_handle) return false;
1334     if (gatt_client->attribute_offset != value_offset) return false;
1335     return memcmp(&gatt_client->attribute_value[gatt_client->attribute_offset], &packet[5], size - 5u) == 0u;
1336 }
1337 
1338 #ifdef ENABLE_LE_SIGNED_WRITE
1339 static void gatt_client_run_for_client_start_signed_write(gatt_client_t *gatt_client) {
1340     sm_key_t csrk;
1341     le_device_db_local_csrk_get(gatt_client->le_device_index, csrk);
1342     uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1343     gatt_client->state = P_W4_CMAC_RESULT;
1344     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);
1345 }
1346 #endif
1347 
1348 // returns true if packet was sent
1349 static bool gatt_client_run_for_gatt_client(gatt_client_t * gatt_client){
1350 
1351     // wait until re-encryption is complete
1352     if (gap_reconnect_security_setup_active(gatt_client->con_handle)) return false;
1353 
1354     // wait until re-encryption is complete
1355     if (gatt_client->reencryption_active) return false;
1356 
1357     // wait until pairing complete (either reactive authentication or due to required security level)
1358     if (gatt_client->wait_for_authentication_complete) return false;
1359 
1360     bool client_request_pending = gatt_client->state != P_READY;
1361 
1362     // verify security level for Mandatory Authentication over LE
1363     bool check_security;
1364     switch (gatt_client->bearer_type){
1365         case ATT_BEARER_UNENHANCED_LE:
1366             check_security = true;
1367             break;
1368         default:
1369             check_security = false;
1370             break;
1371     }
1372     if (client_request_pending && (gatt_client_required_security_level > gatt_client->security_level) && check_security){
1373         log_info("Trigger pairing, current security level %u, required %u\n", gatt_client->security_level, gatt_client_required_security_level);
1374         gatt_client->wait_for_authentication_complete = true;
1375         // set att error code for pairing failure based on required level
1376         switch (gatt_client_required_security_level){
1377             case LEVEL_4:
1378             case LEVEL_3:
1379                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
1380                 break;
1381             default:
1382                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_ENCRYPTION;
1383                 break;
1384         }
1385         sm_request_pairing(gatt_client->con_handle);
1386         // sm probably just sent a pdu
1387         return true;
1388     }
1389 
1390     switch (gatt_client->mtu_state) {
1391         case SEND_MTU_EXCHANGE:
1392             gatt_client->mtu_state = SENT_MTU_EXCHANGE;
1393             att_exchange_mtu_request(gatt_client);
1394             return true;
1395         case SENT_MTU_EXCHANGE:
1396             return false;
1397         default:
1398             break;
1399     }
1400 
1401     if (gatt_client->send_confirmation){
1402         gatt_client->send_confirmation = false;
1403         att_confirmation(gatt_client);
1404         return true;
1405     }
1406 
1407     // check MTU for writes
1408     switch (gatt_client->state){
1409         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1410         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1411             if (gatt_client->attribute_length <= (gatt_client->mtu - 3u)) break;
1412             log_error("gatt_client_run: value len %u > MTU %u - 3\n", gatt_client->attribute_length,gatt_client->mtu);
1413             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH);
1414             return false;
1415         default:
1416             break;
1417     }
1418 
1419     bool packet_sent = true;
1420     bool done = true;
1421     switch (gatt_client->state){
1422         case P_W2_SEND_SERVICE_QUERY:
1423             gatt_client->state = P_W4_SERVICE_QUERY_RESULT;
1424             send_gatt_services_request(gatt_client);
1425             break;
1426 
1427         case P_W2_SEND_SERVICE_WITH_UUID_QUERY:
1428             gatt_client->state = P_W4_SERVICE_WITH_UUID_RESULT;
1429             send_gatt_services_by_uuid_request(gatt_client);
1430             break;
1431 
1432         case P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY:
1433             gatt_client->state = P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT;
1434             send_gatt_characteristic_request(gatt_client);
1435             break;
1436 
1437         case P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY:
1438             gatt_client->state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1439             send_gatt_characteristic_request(gatt_client);
1440             break;
1441 
1442         case P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY:
1443             gatt_client->state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1444             send_gatt_characteristic_descriptor_request(gatt_client);
1445             break;
1446 
1447         case P_W2_SEND_INCLUDED_SERVICE_QUERY:
1448             gatt_client->state = P_W4_INCLUDED_SERVICE_QUERY_RESULT;
1449             send_gatt_included_service_request(gatt_client);
1450             break;
1451 
1452         case P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY:
1453             gatt_client->state = P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT;
1454             send_gatt_included_service_uuid_request(gatt_client);
1455             break;
1456 
1457         case P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY:
1458             gatt_client->state = P_W4_READ_CHARACTERISTIC_VALUE_RESULT;
1459             send_gatt_read_characteristic_value_request(gatt_client);
1460             break;
1461 
1462         case P_W2_SEND_READ_BLOB_QUERY:
1463             gatt_client->state = P_W4_READ_BLOB_RESULT;
1464             send_gatt_read_blob_request(gatt_client);
1465             break;
1466 
1467         case P_W2_SEND_READ_BY_TYPE_REQUEST:
1468             gatt_client->state = P_W4_READ_BY_TYPE_RESPONSE;
1469             send_gatt_read_by_type_request(gatt_client);
1470             break;
1471 
1472         case P_W2_SEND_READ_MULTIPLE_REQUEST:
1473             gatt_client->state = P_W4_READ_MULTIPLE_RESPONSE;
1474             send_gatt_read_multiple_request(gatt_client);
1475             break;
1476 
1477 #ifdef ENABLE_GATT_OVER_EATT
1478         case P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST:
1479             gatt_client->state = P_W4_READ_MULTIPLE_VARIABLE_RESPONSE;
1480             send_gatt_read_multiple_variable_request(gatt_client);
1481             break;
1482 #endif
1483 
1484         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1485             gatt_client->state = P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT;
1486             send_gatt_write_attribute_value_request(gatt_client);
1487             break;
1488 
1489         case P_W2_PREPARE_WRITE:
1490             gatt_client->state = P_W4_PREPARE_WRITE_RESULT;
1491             send_gatt_prepare_write_request(gatt_client);
1492             break;
1493 
1494         case P_W2_PREPARE_WRITE_SINGLE:
1495             gatt_client->state = P_W4_PREPARE_WRITE_SINGLE_RESULT;
1496             send_gatt_prepare_write_request(gatt_client);
1497             break;
1498 
1499         case P_W2_PREPARE_RELIABLE_WRITE:
1500             gatt_client->state = P_W4_PREPARE_RELIABLE_WRITE_RESULT;
1501             send_gatt_prepare_write_request(gatt_client);
1502             break;
1503 
1504         case P_W2_EXECUTE_PREPARED_WRITE:
1505             gatt_client->state = P_W4_EXECUTE_PREPARED_WRITE_RESULT;
1506             send_gatt_execute_write_request(gatt_client);
1507             break;
1508 
1509         case P_W2_CANCEL_PREPARED_WRITE:
1510             gatt_client->state = P_W4_CANCEL_PREPARED_WRITE_RESULT;
1511             send_gatt_cancel_prepared_write_request(gatt_client);
1512             break;
1513 
1514         case P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH:
1515             gatt_client->state = P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT;
1516             send_gatt_cancel_prepared_write_request(gatt_client);
1517             break;
1518 
1519 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1520         case P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1521             // use Find Information
1522             gatt_client->gatt_client_state = P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1523             send_gatt_characteristic_descriptor_request(gatt_client);
1524 #else
1525         case P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1526             // Use Read By Type
1527             gatt_client->state = P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1528             send_gatt_read_client_characteristic_configuration_request(gatt_client);
1529 #endif
1530             break;
1531 
1532         case P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY:
1533             gatt_client->state = P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT;
1534             send_gatt_read_characteristic_descriptor_request(gatt_client);
1535             break;
1536 
1537         case P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY:
1538             gatt_client->state = P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT;
1539             send_gatt_read_blob_request(gatt_client);
1540             break;
1541 
1542         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1543             gatt_client->state = P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1544             send_gatt_write_attribute_value_request(gatt_client);
1545             break;
1546 
1547         case P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:
1548             gatt_client->state = P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT;
1549             send_gatt_write_client_characteristic_configuration_request(gatt_client);
1550             break;
1551 
1552         case P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR:
1553             gatt_client->state = P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1554             send_gatt_prepare_write_request(gatt_client);
1555             break;
1556 
1557         case P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR:
1558             gatt_client->state = P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1559             send_gatt_execute_write_request(gatt_client);
1560             break;
1561 
1562 #ifdef ENABLE_LE_SIGNED_WRITE
1563         case P_W4_IDENTITY_RESOLVING:
1564             log_info("P_W4_IDENTITY_RESOLVING - state %x", sm_identity_resolving_state(gatt_client->con_handle));
1565             switch (sm_identity_resolving_state(gatt_client->con_handle)){
1566                 case IRK_LOOKUP_SUCCEEDED:
1567                     gatt_client->le_device_index = sm_le_device_index(gatt_client->con_handle);
1568                     gatt_client->state = P_W4_CMAC_READY;
1569                     if (sm_cmac_ready()){
1570                         gatt_client_run_for_client_start_signed_write(gatt_client);
1571                     }
1572                     break;
1573                 case IRK_LOOKUP_FAILED:
1574                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1575                     break;
1576                 default:
1577                     break;
1578             }
1579             packet_sent = false;
1580             break;
1581 
1582         case P_W4_CMAC_READY:
1583             if (sm_cmac_ready()){
1584                 gatt_client_run_for_client_start_signed_write(gatt_client);
1585             }
1586             packet_sent = false;
1587             break;
1588 
1589         case P_W2_SEND_SIGNED_WRITE: {
1590             gatt_client->state = P_W4_SEND_SIGNED_WRITE_DONE;
1591             // bump local signing counter
1592             uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1593             le_device_db_local_counter_set(gatt_client->le_device_index, sign_counter + 1);
1594             // send signed write command
1595             send_gatt_signed_write_request(gatt_client, sign_counter);
1596             // finally, notifiy client that write is complete
1597             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1598             break;
1599         }
1600 #endif
1601         default:
1602             done = false;
1603             break;
1604     }
1605 
1606     if (done){
1607         return packet_sent;
1608     }
1609 
1610     // write without response callback
1611     btstack_context_callback_registration_t * callback =
1612             (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->write_without_response_requests);
1613     if (callback != NULL){
1614         (*callback->callback)(callback->context);
1615         return true;
1616     }
1617 
1618     // requested can send now old
1619     if (gatt_client->write_without_response_callback != NULL){
1620         btstack_packet_handler_t packet_handler = gatt_client->write_without_response_callback;
1621         gatt_client->write_without_response_callback = NULL;
1622         uint8_t event[4];
1623         event[0] = GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE;
1624         event[1] = sizeof(event) - 2u;
1625         little_endian_store_16(event, 2, gatt_client->con_handle);
1626         packet_handler(HCI_EVENT_PACKET, gatt_client->con_handle, event, sizeof(event));
1627         return true; // to trigger requeueing (even if higher layer didn't sent)
1628     }
1629 
1630     return false;
1631 }
1632 
1633 static void gatt_client_run(void){
1634     btstack_linked_item_t *it;
1635     bool packet_sent;
1636 #ifdef ENABLE_GATT_OVER_EATT
1637     btstack_linked_list_iterator_t it_eatt;
1638 #endif
1639     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
1640         gatt_client_t * gatt_client = (gatt_client_t *) it;
1641         switch (gatt_client->bearer_type){
1642             case ATT_BEARER_UNENHANCED_LE:
1643 #ifdef ENABLE_GATT_OVER_EATT
1644                 btstack_linked_list_iterator_init(&it_eatt, &gatt_client->eatt_clients);
1645                 while (btstack_linked_list_iterator_has_next(&it_eatt)) {
1646                     gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it_eatt);
1647                     if (eatt_client->state != P_READY){
1648                         if (att_dispatch_client_can_send_now(gatt_client->con_handle)){
1649                             gatt_client_run_for_gatt_client(eatt_client);
1650                         }
1651                     }
1652                 }
1653 #endif
1654                 if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) {
1655                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1656                     return;
1657                 }
1658                 packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1659                 if (packet_sent){
1660                     // request new permission
1661                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1662                     // requeue client for fairness and exit
1663                     // note: iterator has become invalid
1664                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1665                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1666                     return;
1667                 }
1668                 break;
1669 #ifdef ENABLE_GATT_OVER_CLASSIC
1670             case ATT_BEARER_UNENHANCED_CLASSIC:
1671                 if (gatt_client->con_handle == HCI_CON_HANDLE_INVALID) {
1672                     continue;
1673                 }
1674 
1675                 // handle GATT over BR/EDR
1676                 if (att_dispatch_client_can_send_now(gatt_client->con_handle) == false) {
1677                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1678                     return;
1679                 }
1680                 packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1681                 if (packet_sent){
1682                     // request new permission
1683                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1684                     // requeue client for fairness and exit
1685                     // note: iterator has become invalid
1686                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1687                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1688                     return;
1689                 }
1690                 break;
1691 #endif
1692             default:
1693                 btstack_unreachable();
1694                 break;
1695         }
1696 
1697 
1698     }
1699 }
1700 
1701 // emit complete event, used to avoid emitting event from API call
1702 static void gatt_client_emit_events(void * context){
1703     UNUSED(context);
1704     btstack_linked_item_t *it;
1705     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next) {
1706         gatt_client_t *gatt_client = (gatt_client_t *) it;
1707         if (gatt_client->state == P_W2_EMIT_QUERY_COMPLETE_EVENT){
1708             gatt_client->state = P_READY;
1709             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1710         }
1711     }
1712 }
1713 
1714 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code) {
1715     if (is_ready(gatt_client)) return;
1716     gatt_client_handle_transaction_complete(gatt_client, att_error_code);
1717 }
1718 
1719 static void gatt_client_handle_reencryption_complete(const uint8_t * packet){
1720     hci_con_handle_t con_handle = sm_event_reencryption_complete_get_handle(packet);
1721     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1722     if (gatt_client == NULL) return;
1723 
1724     // update security level
1725     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1726 
1727     gatt_client->reencryption_result = sm_event_reencryption_complete_get_status(packet);
1728     gatt_client->reencryption_active = false;
1729     gatt_client->wait_for_authentication_complete = false;
1730 
1731     if (gatt_client->state == P_READY) return;
1732 
1733     switch (sm_event_reencryption_complete_get_status(packet)){
1734         case ERROR_CODE_SUCCESS:
1735             log_info("re-encryption success, retry operation");
1736             break;
1737         case ERROR_CODE_AUTHENTICATION_FAILURE:
1738         case ERROR_CODE_PIN_OR_KEY_MISSING:
1739 #if defined(ENABLE_GATT_CLIENT_PAIRING) && !defined(ENABLE_LE_PROACTIVE_AUTHENTICATION)
1740             if (gatt_client_required_security_level == LEVEL_0) {
1741                 // re-encryption failed for reactive authentication with pairing and we have a pending client request
1742                 // => try to resolve it by deleting bonding information if we started pairing before
1743                 // delete bonding information
1744                 int le_device_db_index = sm_le_device_index(gatt_client->con_handle);
1745                 btstack_assert(le_device_db_index >= 0);
1746                 log_info("reactive auth with pairing: delete bonding and start pairing");
1747 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1748                 hci_remove_le_device_db_entry_from_resolving_list((uint16_t) le_device_db_index);
1749 #endif
1750                 le_device_db_remove(le_device_db_index);
1751                 // trigger pairing again
1752                 sm_request_pairing(gatt_client->con_handle);
1753                 break;
1754             }
1755 #endif
1756             // report bonding information missing
1757             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1758             break;
1759         default:
1760             // report bonding information missing
1761             gatt_client_handle_transaction_complete(gatt_client, gatt_client->pending_error_code);
1762             break;
1763     }
1764 }
1765 
1766 static void gatt_client_handle_disconnection_complete(const uint8_t * packet){
1767     log_info("GATT Client: HCI_EVENT_DISCONNECTION_COMPLETE");
1768     hci_con_handle_t con_handle = little_endian_read_16(packet,3);
1769     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1770     if (gatt_client == NULL) return;
1771 
1772     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1773     gatt_client_timeout_stop(gatt_client);
1774     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1775     btstack_memory_gatt_client_free(gatt_client);
1776 }
1777 
1778 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1779     UNUSED(channel);    // ok: handling own l2cap events
1780     UNUSED(size);       // ok: there is no channel
1781 
1782     if (packet_type != HCI_EVENT_PACKET) return;
1783 
1784     hci_con_handle_t con_handle;
1785     gatt_client_t * gatt_client;
1786     switch (hci_event_packet_get_type(packet)) {
1787         case HCI_EVENT_DISCONNECTION_COMPLETE:
1788             gatt_client_handle_disconnection_complete(packet);
1789             break;
1790 
1791         // Pairing complete (with/without bonding=storing of pairing information)
1792         case SM_EVENT_PAIRING_COMPLETE:
1793             con_handle = sm_event_pairing_complete_get_handle(packet);
1794             gatt_client = gatt_client_get_context_for_handle(con_handle);
1795             if (gatt_client == NULL) break;
1796 
1797             // update security level
1798             gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1799 
1800             if (gatt_client->wait_for_authentication_complete){
1801                 gatt_client->wait_for_authentication_complete = false;
1802                 if (sm_event_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS){
1803                     log_info("pairing failed, report previous error 0x%x", gatt_client->pending_error_code);
1804                     gatt_client_report_error_if_pending(gatt_client, gatt_client->pending_error_code);
1805                 } else {
1806                     log_info("pairing success, retry operation");
1807                 }
1808             }
1809             break;
1810 
1811 #ifdef ENABLE_LE_SIGNED_WRITE
1812         // Identity Resolving completed (no code, gatt_client_run will continue)
1813         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
1814         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
1815             break;
1816 #endif
1817 
1818         // re-encryption started
1819         case SM_EVENT_REENCRYPTION_STARTED:
1820             con_handle = sm_event_reencryption_complete_get_handle(packet);
1821             gatt_client = gatt_client_get_context_for_handle(con_handle);
1822             if (gatt_client == NULL) break;
1823 
1824             gatt_client->reencryption_active = true;
1825             gatt_client->reencryption_result = ERROR_CODE_SUCCESS;
1826             break;
1827 
1828         // re-encryption complete
1829         case SM_EVENT_REENCRYPTION_COMPLETE:
1830             gatt_client_handle_reencryption_complete(packet);
1831             break;
1832         default:
1833             break;
1834     }
1835 
1836     gatt_client_run();
1837 }
1838 
1839 static void gatt_client_handle_att_read_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1840     switch (gatt_client->state) {
1841         case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT:
1842             if (size >= 17) {
1843                 uint8_t uuid128[16];
1844                 reverse_128(&packet[1], uuid128);
1845                 report_gatt_included_service_uuid128(gatt_client, gatt_client->start_group_handle, uuid128);
1846             }
1847             trigger_next_included_service_query(gatt_client, gatt_client->start_group_handle);
1848             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1849             break;
1850 
1851         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1852             report_gatt_characteristic_value(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u);
1853             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1854             break;
1855 
1856         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1857             report_gatt_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1858                                                   size - 1u, 0u);
1859             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1860             break;
1861 
1862             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic
1863         case P_W4_READ_BLOB_RESULT:
1864             report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1865                                                        size - 1u, gatt_client->attribute_offset);
1866             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, size - 1u);
1867             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1868             break;
1869 
1870             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic Descriptor
1871         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1872             report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1873                                                        size - 1u, gatt_client->attribute_offset);
1874             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
1875                                     size - 1u);
1876             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1877             break;
1878 
1879         default:
1880             break;
1881     }
1882 }
1883 
1884 static void gatt_client_handle_att_read_by_type_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1885     switch (gatt_client->state) {
1886         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1887             report_gatt_characteristics(gatt_client, packet, size);
1888             trigger_next_characteristic_query(gatt_client,
1889                                               get_last_result_handle_from_characteristics_list(packet, size));
1890             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1891             break;
1892         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1893             report_gatt_characteristics(gatt_client, packet, size);
1894             trigger_next_characteristic_query(gatt_client,
1895                                               get_last_result_handle_from_characteristics_list(packet, size));
1896             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1897             break;
1898         case P_W4_INCLUDED_SERVICE_QUERY_RESULT: {
1899             if (size < 2u) break;
1900             uint16_t uuid16 = 0;
1901             uint16_t pair_size = packet[1];
1902 
1903             if (pair_size == 6u) {
1904                 if (size < 8u) break;
1905                 // UUIDs not available, query first included service
1906                 gatt_client->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1907                 gatt_client->query_start_handle = little_endian_read_16(packet, 4);
1908                 gatt_client->query_end_handle = little_endian_read_16(packet, 6);
1909                 gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1910                 break;
1911             }
1912 
1913             if (pair_size != 8u) break;
1914 
1915             // UUIDs included, report all of them
1916             uint16_t offset;
1917             for (offset = 2u; (offset + 8u) <= size; offset += pair_size) {
1918                 uint16_t include_handle = little_endian_read_16(packet, offset);
1919                 gatt_client->query_start_handle = little_endian_read_16(packet, offset + 2u);
1920                 gatt_client->query_end_handle = little_endian_read_16(packet, offset + 4u);
1921                 uuid16 = little_endian_read_16(packet, offset + 6u);
1922                 report_gatt_included_service_uuid16(gatt_client, include_handle, uuid16);
1923             }
1924 
1925             trigger_next_included_service_query(gatt_client,
1926                                                 get_last_result_handle_from_included_services_list(packet,
1927                                                                                                    size));
1928             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1929             break;
1930         }
1931 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1932         case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1933             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1934             gatt_client->state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1935             break;
1936 #endif
1937         case P_W4_READ_BY_TYPE_RESPONSE: {
1938             uint16_t pair_size = packet[1];
1939             // set last result handle to last valid handle, only used if pair_size invalid
1940             uint16_t last_result_handle = 0xffff;
1941             if (pair_size > 2) {
1942                 uint16_t offset;
1943                 for (offset = 2; offset < size; offset += pair_size) {
1944                     uint16_t value_handle = little_endian_read_16(packet, offset);
1945                     report_gatt_characteristic_value(gatt_client, value_handle, &packet[offset + 2u],
1946                                                      pair_size - 2u);
1947                     last_result_handle = value_handle;
1948                 }
1949             }
1950             trigger_next_read_by_type_query(gatt_client, last_result_handle);
1951             break;
1952         }
1953         default:
1954             break;
1955     }
1956 }
1957 
1958 static void gatt_client_handle_att_write_response(gatt_client_t *gatt_client) {
1959     switch (gatt_client->state) {
1960         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1961             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1962             break;
1963         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1964             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1965             break;
1966         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1967             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1968             break;
1969         default:
1970             break;
1971     }
1972 }
1973 
1974 static void gatt_client_handle_att_response(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size) {
1975     uint8_t att_status;
1976     switch (packet[0]) {
1977         case ATT_EXCHANGE_MTU_RESPONSE: {
1978             if (size < 3u) break;
1979             bool update_gatt_server_att_mtu = false;
1980             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1981             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1982             switch (gatt_client->bearer_type){
1983                 case ATT_BEARER_UNENHANCED_LE:
1984                     update_gatt_server_att_mtu = true;
1985                     break;
1986 #ifdef ENABLE_GATT_OVER_CLASSIC
1987                 case ATT_BEARER_UNENHANCED_CLASSIC:
1988                     local_rx_mtu = gatt_client->mtu;
1989                     break;
1990 #endif
1991                 default:
1992                     btstack_unreachable();
1993                     break;
1994             }
1995 
1996             uint16_t mtu = (remote_rx_mtu < local_rx_mtu) ? remote_rx_mtu : local_rx_mtu;
1997 
1998             // set gatt client mtu
1999             gatt_client->mtu = mtu;
2000             gatt_client->mtu_state = MTU_EXCHANGED;
2001 
2002             if (update_gatt_server_att_mtu){
2003                 // set per connection mtu state - for fixed channel
2004                 hci_connection_t *hci_connection = hci_connection_for_handle(gatt_client->con_handle);
2005                 hci_connection->att_connection.mtu = gatt_client->mtu;
2006                 hci_connection->att_connection.mtu_exchanged = true;
2007             }
2008             emit_gatt_mtu_exchanged_result_event(gatt_client, gatt_client->mtu);
2009             break;
2010         }
2011         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
2012             switch (gatt_client->state) {
2013                 case P_W4_SERVICE_QUERY_RESULT:
2014                     report_gatt_services(gatt_client, packet, size);
2015                     trigger_next_service_query(gatt_client, get_last_result_handle_from_service_list(packet, size));
2016                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2017                     break;
2018                 default:
2019                     break;
2020             }
2021             break;
2022         case ATT_HANDLE_VALUE_NOTIFICATION:
2023             if (size < 3u) return;
2024             report_gatt_notification(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
2025             return;
2026 #ifdef ENABLE_GATT_OVER_EATT
2027         case ATT_MULTIPLE_HANDLE_VALUE_NTF:
2028             if (size >= 5u) {
2029                 uint16_t offset = 1;
2030                 while (true){
2031                     uint16_t value_handle = little_endian_read_16(packet, offset);
2032                     offset += 2;
2033                     uint16_t value_length = little_endian_read_16(packet, offset);
2034                     offset += 2;
2035                     if ((offset + value_length) > size) break;
2036                     report_gatt_notification(gatt_client, value_handle, &packet[offset], value_length);
2037                     offset += value_length;
2038                 }
2039             }
2040             return;
2041 #endif
2042         case ATT_HANDLE_VALUE_INDICATION:
2043             if (size < 3u) break;
2044             report_gatt_indication(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
2045             gatt_client->send_confirmation = true;
2046             break;
2047         case ATT_READ_BY_TYPE_RESPONSE:
2048             gatt_client_handle_att_read_by_type_response(gatt_client, packet, size);
2049             break;
2050         case ATT_READ_RESPONSE:
2051             gatt_client_handle_att_read_response(gatt_client, packet, size);
2052             break;
2053         case ATT_FIND_BY_TYPE_VALUE_RESPONSE: {
2054             uint8_t pair_size = 4;
2055             int i;
2056             uint16_t start_group_handle;
2057             uint16_t end_group_handle = 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
2058             for (i = 1u; (i + pair_size) <= size; i += pair_size) {
2059                 start_group_handle = little_endian_read_16(packet, i);
2060                 end_group_handle = little_endian_read_16(packet, i + 2);
2061                 emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle,
2062                                                      gatt_client->uuid128);
2063             }
2064             trigger_next_service_by_uuid_query(gatt_client, end_group_handle);
2065             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2066             break;
2067         }
2068         case ATT_FIND_INFORMATION_REPLY: {
2069             if (size < 2u) break;
2070 
2071             uint8_t pair_size = 4;
2072             if (packet[1u] == 2u) {
2073                 pair_size = 18;
2074             }
2075             uint16_t offset = 2;
2076 
2077             if (size < (pair_size + offset)) break;
2078             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
2079 
2080 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2081             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", gatt_client->gatt_client_state);
2082             if (gatt_client->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
2083                 // iterate over descriptors looking for CCC
2084                 if (pair_size == 4){
2085                     while ((offset + 4) <= size){
2086                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
2087                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
2088                             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
2089                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2090                             log_info("CCC found %x", gatt_client->client_characteristic_configuration_handle);
2091                             break;
2092                         }
2093                         offset += pair_size;
2094                     }
2095                 }
2096                 if (is_query_done(gatt_client, last_descriptor_handle)){
2097 
2098                 } else {
2099                     // next
2100                     gatt_client->start_group_handle = last_descriptor_handle + 1;
2101                     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2102                 }
2103                 break;
2104             }
2105 #endif
2106             report_gatt_all_characteristic_descriptors(gatt_client, &packet[2], size - 2u, pair_size);
2107             trigger_next_characteristic_descriptor_query(gatt_client, last_descriptor_handle);
2108             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2109             break;
2110         }
2111 
2112         case ATT_WRITE_RESPONSE:
2113             gatt_client_handle_att_write_response(gatt_client);
2114             break;
2115 
2116         case ATT_READ_BLOB_RESPONSE: {
2117             uint16_t received_blob_length = size - 1u;
2118             switch (gatt_client->state) {
2119                 case P_W4_READ_BLOB_RESULT:
2120                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
2121                                                                received_blob_length, gatt_client->attribute_offset);
2122                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
2123                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2124                     break;
2125                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2126                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle,
2127                                                                &packet[1], received_blob_length,
2128                                                                gatt_client->attribute_offset);
2129                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
2130                                             received_blob_length);
2131                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2132                     break;
2133                 default:
2134                     break;
2135             }
2136             break;
2137         }
2138         case ATT_PREPARE_WRITE_RESPONSE:
2139             switch (gatt_client->state) {
2140                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2141                     if (is_value_valid(gatt_client, packet, size)) {
2142                         att_status = ATT_ERROR_SUCCESS;
2143                     } else {
2144                         att_status = ATT_ERROR_DATA_MISMATCH;
2145                     }
2146                     gatt_client_handle_transaction_complete(gatt_client, att_status);
2147                     break;
2148 
2149                 case P_W4_PREPARE_WRITE_RESULT: {
2150                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2151                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
2152                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2153                     break;
2154                 }
2155                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT: {
2156                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2157                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR,
2158                                                      P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
2159                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2160                     break;
2161                 }
2162                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT: {
2163                     if (is_value_valid(gatt_client, packet, size)) {
2164                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2165                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE,
2166                                                          P_W2_EXECUTE_PREPARED_WRITE);
2167                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2168                         break;
2169                     }
2170                     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2171                     break;
2172                 }
2173                 default:
2174                     break;
2175             }
2176             break;
2177 
2178         case ATT_EXECUTE_WRITE_RESPONSE:
2179             switch (gatt_client->state) {
2180                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2181                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2182                     break;
2183                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2184                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2185                     break;
2186                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2187                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_DATA_MISMATCH);
2188                     break;
2189                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2190                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2191                     break;
2192                 default:
2193                     break;
2194 
2195             }
2196             break;
2197 
2198         case ATT_READ_MULTIPLE_RESPONSE:
2199             switch (gatt_client->state) {
2200                 case P_W4_READ_MULTIPLE_RESPONSE:
2201                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
2202                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2203                     break;
2204                 default:
2205                     break;
2206             }
2207             break;
2208 
2209 #ifdef ENABLE_GATT_OVER_EATT
2210         case ATT_READ_MULTIPLE_VARIABLE_RSP:
2211             switch (gatt_client->state) {
2212                 case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2213                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
2214                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2215                     break;
2216                 default:
2217                     break;
2218             }
2219             break;
2220 #endif
2221 
2222         case ATT_ERROR_RESPONSE:
2223             if (size < 5u) return;
2224             att_status = packet[4];
2225             switch (att_status) {
2226                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
2227                     switch (gatt_client->state) {
2228                         case P_W4_SERVICE_QUERY_RESULT:
2229                         case P_W4_SERVICE_WITH_UUID_RESULT:
2230                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
2231                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
2232                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2233                             break;
2234                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
2235                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
2236                             report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
2237                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2238                             break;
2239                         case P_W4_READ_BY_TYPE_RESPONSE:
2240                             if (gatt_client->start_group_handle == gatt_client->query_start_handle) {
2241                                 att_status = ATT_ERROR_ATTRIBUTE_NOT_FOUND;
2242                             } else {
2243                                 att_status = ATT_ERROR_SUCCESS;
2244                             }
2245                             gatt_client_handle_transaction_complete(gatt_client, att_status);
2246                             break;
2247                         default:
2248                             gatt_client_report_error_if_pending(gatt_client, att_status);
2249                             break;
2250                     }
2251                     break;
2252                 }
2253 
2254 #ifdef ENABLE_GATT_CLIENT_PAIRING
2255 
2256                     case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
2257                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
2258                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
2259 
2260                         // security too low
2261                         if (gatt_client->security_counter > 0) {
2262                             gatt_client_report_error_if_pending(gatt_client, att_status);
2263                             break;
2264                         }
2265                         // start security
2266                         gatt_client->security_counter++;
2267 
2268                         // setup action
2269                         int retry = 1;
2270                         switch (gatt_client->state){
2271                             case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
2272                                 gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
2273                                 break;
2274                             case P_W4_READ_BLOB_RESULT:
2275                                 gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2276                                 break;
2277                             case P_W4_READ_BY_TYPE_RESPONSE:
2278                                 gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2279                                 break;
2280                             case P_W4_READ_MULTIPLE_RESPONSE:
2281                                 gatt_client->state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2282                                 break;
2283                             case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2284                                 gatt_client->state = P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST;
2285                                 break;
2286                             case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
2287                                 gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2288                                 break;
2289                             case P_W4_PREPARE_WRITE_RESULT:
2290                                 gatt_client->state = P_W2_PREPARE_WRITE;
2291                                 break;
2292                             case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2293                                 gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
2294                                 break;
2295                             case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
2296                                 gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2297                                 break;
2298                             case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2299                                 gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
2300                                 break;
2301                             case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2302                                 gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
2303                                 break;
2304                             case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2305                                 gatt_client->state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2306                                 break;
2307                             case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
2308                                 gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2309                                 break;
2310                             case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2311                                 gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2312                                 break;
2313                             case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2314                                 gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2315                                 break;
2316                             case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
2317                                 gatt_client->state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2318                                 break;
2319                             case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2320                                 gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2321                                 break;
2322                             case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2323                                 gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
2324                                 break;
2325 #ifdef ENABLE_LE_SIGNED_WRITE
2326                             case P_W4_SEND_SIGNED_WRITE_DONE:
2327                                 gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2328                                 break;
2329 #endif
2330                             default:
2331                                 log_info("retry not supported for state %x", gatt_client->state);
2332                                 retry = 0;
2333                                 break;
2334                         }
2335 
2336                         if (!retry) {
2337                             gatt_client_report_error_if_pending(gatt_client, att_status);
2338                             break;
2339                         }
2340 
2341                         log_info("security error, start pairing");
2342 
2343                         // start pairing for higher security level
2344                         gatt_client->wait_for_authentication_complete = true;
2345                         gatt_client->pending_error_code = att_status;
2346                         sm_request_pairing(gatt_client->con_handle);
2347                         break;
2348                     }
2349 #endif
2350 
2351                     // nothing we can do about that
2352                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
2353                 default:
2354                     gatt_client_report_error_if_pending(gatt_client, att_status);
2355                     break;
2356             }
2357             break;
2358 
2359         default:
2360             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
2361             break;
2362     }
2363 }
2364 
2365 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size) {
2366     gatt_client_t *gatt_client;
2367 #ifdef ENABLE_GATT_OVER_CLASSIC
2368     uint8_t status;
2369     hci_connection_t * hci_connection;
2370     hci_con_handle_t con_handle;
2371 #endif
2372 
2373     if (size < 1u) return;
2374     switch (packet_type){
2375         case HCI_EVENT_PACKET:
2376             switch (hci_event_packet_get_type(packet)) {
2377 #ifdef ENABLE_GATT_OVER_CLASSIC
2378                 case L2CAP_EVENT_CHANNEL_OPENED:
2379                     status = l2cap_event_channel_opened_get_status(packet);
2380                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_opened_get_local_cid(packet));
2381                     if (gatt_client != NULL){
2382                         con_handle = l2cap_event_channel_opened_get_handle(packet);
2383                         hci_connection = hci_connection_for_handle(con_handle);
2384                         if (status == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES){
2385                             if ((hci_connection != NULL) && hci_connection->att_server.incoming_connection_request) {
2386                                 log_info("Collision, retry in 100ms");
2387                                 gatt_client->state = P_W2_L2CAP_CONNECT;
2388                                 // set timer for retry
2389                                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
2390                                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_classic_retry);
2391                                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
2392                                 break;
2393                             }
2394                         }
2395                         // if status != 0, gatt_client will be discarded
2396                         gatt_client->state = P_READY;
2397                         gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2398                         gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2399                         gatt_client_classic_handle_connected(gatt_client, status);
2400                     }
2401                     break;
2402                 case L2CAP_EVENT_CHANNEL_CLOSED:
2403                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2404                     if (gatt_client != NULL){
2405                         // discard gatt client object
2406                         gatt_client_classic_handle_disconnected(gatt_client);
2407                     }
2408                     break;
2409 #endif
2410                 case L2CAP_EVENT_CAN_SEND_NOW:
2411                     gatt_client_run();
2412                     break;
2413                     // att_server has negotiated the mtu for this connection, cache if context exists
2414                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
2415                     if (size < 6u) break;
2416                     gatt_client = gatt_client_get_context_for_handle(handle);
2417                     if (gatt_client != NULL) {
2418                         gatt_client->mtu = little_endian_read_16(packet, 4);
2419                     }
2420                     break;
2421                 default:
2422                     break;
2423             }
2424             break;
2425 
2426         case ATT_DATA_PACKET:
2427             // special cases: notifications & indications motivate creating context
2428             switch (packet[0]) {
2429                 case ATT_HANDLE_VALUE_NOTIFICATION:
2430                 case ATT_HANDLE_VALUE_INDICATION:
2431                     gatt_client_provide_context_for_handle(handle, &gatt_client);
2432                     break;
2433                 default:
2434                     gatt_client = gatt_client_get_context_for_handle(handle);
2435                     break;
2436             }
2437 
2438             if (gatt_client != NULL) {
2439                 gatt_client_handle_att_response(gatt_client, packet, size);
2440                 gatt_client_run();
2441             }
2442             break;
2443 
2444 #ifdef ENABLE_GATT_OVER_CLASSIC
2445         case L2CAP_DATA_PACKET:
2446             gatt_client = gatt_client_get_context_for_l2cap_cid(handle);
2447             if (gatt_client != NULL){
2448                 gatt_client_handle_att_response(gatt_client, packet, size);
2449                 gatt_client_run();
2450             }
2451             break;
2452 #endif
2453 
2454         default:
2455             break;
2456     }
2457 }
2458 
2459 #ifdef ENABLE_LE_SIGNED_WRITE
2460 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2461     btstack_linked_list_iterator_t it;
2462     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2463     while (btstack_linked_list_iterator_has_next(&it)){
2464         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2465         if (gatt_client->state == P_W4_CMAC_RESULT){
2466             // store result
2467             (void)memcpy(gatt_client->cmac, hash, 8);
2468             // reverse_64(hash, gatt_client->cmac);
2469             gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2470             gatt_client_run();
2471             return;
2472         }
2473     }
2474 }
2475 
2476 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){
2477     gatt_client_t * gatt_client;
2478     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2479     if (status != ERROR_CODE_SUCCESS){
2480         return status;
2481     }
2482     if (is_ready(gatt_client) == 0){
2483         return GATT_CLIENT_IN_WRONG_STATE;
2484     }
2485 
2486     gatt_client->callback = callback;
2487     gatt_client->attribute_handle = value_handle;
2488     gatt_client->attribute_length = message_len;
2489     gatt_client->attribute_value = message;
2490     gatt_client->state = P_W4_IDENTITY_RESOLVING;
2491     gatt_client_run();
2492     return ERROR_CODE_SUCCESS;
2493 }
2494 #endif
2495 
2496 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2497     gatt_client_t * gatt_client;
2498     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2499     if (status != ERROR_CODE_SUCCESS){
2500         return status;
2501     }
2502 
2503     gatt_client->callback = callback;
2504     gatt_client->start_group_handle = 0x0001;
2505     gatt_client->end_group_handle   = 0xffff;
2506     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2507     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2508     gatt_client_run();
2509     return ERROR_CODE_SUCCESS;
2510 }
2511 
2512 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2513     gatt_client_t * gatt_client;
2514     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2515     if (status != ERROR_CODE_SUCCESS){
2516         return status;
2517     }
2518 
2519     gatt_client->callback = callback;
2520     gatt_client->start_group_handle = 0x0001;
2521     gatt_client->end_group_handle   = 0xffff;
2522     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2523     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2524     gatt_client_run();
2525     return ERROR_CODE_SUCCESS;
2526 }
2527 
2528 uint8_t gatt_client_discover_primary_services_by_uuid16_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle,
2529                                                                      uint16_t uuid16, uint16_t service_id, uint16_t connection_id){
2530     gatt_client_t * gatt_client;
2531     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2532     if (status != ERROR_CODE_SUCCESS){
2533         return status;
2534     }
2535 
2536     gatt_client->callback = callback;
2537     gatt_client->service_id = service_id;
2538     gatt_client->connection_id = connection_id;
2539     gatt_client->start_group_handle = 0x0001;
2540     gatt_client->end_group_handle   = 0xffff;
2541     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2542     gatt_client->uuid16 = uuid16;
2543     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2544     gatt_client_run();
2545     return ERROR_CODE_SUCCESS;
2546 }
2547 
2548 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2549     return gatt_client_discover_primary_services_by_uuid16_with_context(callback, con_handle, uuid16, 0, 0);
2550 }
2551 
2552 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2553     gatt_client_t * gatt_client;
2554     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2555     if (status != ERROR_CODE_SUCCESS){
2556         return status;
2557     }
2558 
2559     gatt_client->callback = callback;
2560     gatt_client->start_group_handle = 0x0001;
2561     gatt_client->end_group_handle   = 0xffff;
2562     gatt_client->uuid16 = 0;
2563     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2564     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2565     gatt_client_run();
2566     return ERROR_CODE_SUCCESS;
2567 }
2568 
2569 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,
2570                                                                       uint16_t service_id, uint16_t connection_id){
2571     gatt_client_t * gatt_client;
2572     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2573     if (status != ERROR_CODE_SUCCESS){
2574         return status;
2575     }
2576 
2577     gatt_client->callback = callback;
2578     gatt_client->service_id = service_id;
2579     gatt_client->connection_id = connection_id;
2580     gatt_client->start_group_handle = service->start_group_handle;
2581     gatt_client->end_group_handle   = service->end_group_handle;
2582     gatt_client->filter_with_uuid = false;
2583     gatt_client->characteristic_start_handle = 0;
2584     gatt_client->state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2585     gatt_client_run();
2586     return ERROR_CODE_SUCCESS;
2587 }
2588 
2589 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2590     return gatt_client_discover_characteristics_for_service_with_context(callback, con_handle, service, 0, 0);
2591 }
2592 
2593 uint8_t gatt_client_find_included_services_for_service_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle,
2594                                                                     gatt_client_service_t * service, uint16_t service_id, uint16_t connection_id){
2595     gatt_client_t * gatt_client;
2596     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2597     if (status != ERROR_CODE_SUCCESS){
2598         return status;
2599     }
2600 
2601     gatt_client->callback = callback;
2602     gatt_client->service_id = service_id;
2603     gatt_client->connection_id = connection_id;
2604     gatt_client->start_group_handle = service->start_group_handle;
2605     gatt_client->end_group_handle   = service->end_group_handle;
2606     gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2607 
2608     gatt_client_run();
2609     return ERROR_CODE_SUCCESS;
2610 }
2611 
2612 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) {
2613     return gatt_client_find_included_services_for_service_with_context(callback, con_handle, service, 0, 0);
2614 }
2615 
2616 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){
2617     gatt_client_t * gatt_client;
2618     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2619     if (status != ERROR_CODE_SUCCESS){
2620         return status;
2621     }
2622 
2623     gatt_client->callback = callback;
2624     gatt_client->start_group_handle = start_handle;
2625     gatt_client->end_group_handle   = end_handle;
2626     gatt_client->filter_with_uuid = true;
2627     gatt_client->uuid16 = uuid16;
2628     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2629     gatt_client->characteristic_start_handle = 0;
2630     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2631     gatt_client_run();
2632     return ERROR_CODE_SUCCESS;
2633 }
2634 
2635 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){
2636     gatt_client_t * gatt_client;
2637     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2638     if (status != ERROR_CODE_SUCCESS){
2639         return status;
2640     }
2641 
2642     gatt_client->callback = callback;
2643     gatt_client->start_group_handle = start_handle;
2644     gatt_client->end_group_handle   = end_handle;
2645     gatt_client->filter_with_uuid = true;
2646     gatt_client->uuid16 = 0;
2647     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2648     gatt_client->characteristic_start_handle = 0;
2649     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2650     gatt_client_run();
2651     return ERROR_CODE_SUCCESS;
2652 }
2653 
2654 
2655 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){
2656     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2657 }
2658 
2659 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){
2660     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2661 }
2662 
2663 uint8_t gatt_client_discover_characteristic_descriptors_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle,
2664                                                                      gatt_client_characteristic_t * characteristic,  uint16_t service_id, uint16_t connection_id){
2665     gatt_client_t * gatt_client;
2666     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2667     if (status != ERROR_CODE_SUCCESS){
2668         return status;
2669     }
2670 
2671     gatt_client->service_id = service_id;
2672     gatt_client->connection_id = connection_id;
2673 
2674     // check if there is space for characteristics descriptors
2675     if (characteristic->end_handle > characteristic->value_handle){
2676         gatt_client->callback = callback;
2677         gatt_client->start_group_handle = characteristic->value_handle + 1u;
2678         gatt_client->end_group_handle   = characteristic->end_handle;
2679         gatt_client->state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2680         gatt_client_run();
2681     } else {
2682         // schedule gatt complete event on next run loop iteration otherwise
2683         gatt_client->state = P_W2_EMIT_QUERY_COMPLETE_EVENT;
2684         gatt_client_deferred_event_emit.callback = gatt_client_emit_events;
2685         btstack_run_loop_execute_on_main_thread(&gatt_client_deferred_event_emit);
2686     }
2687     return ERROR_CODE_SUCCESS;
2688 }
2689 
2690 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2691     return gatt_client_discover_characteristic_descriptors_with_context(callback, con_handle, characteristic, 0, 0);
2692 }
2693 
2694 uint8_t gatt_client_read_value_of_characteristic_using_value_handle_with_context(btstack_packet_handler_t callback,
2695                                                                                  hci_con_handle_t con_handle,
2696                                                                                  uint16_t value_handle,
2697                                                                                  uint16_t service_id,
2698                                                                                  uint16_t connection_id) {
2699     gatt_client_t * gatt_client;
2700     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2701     if (status != ERROR_CODE_SUCCESS){
2702         return status;
2703     }
2704 
2705     gatt_client->callback = callback;
2706     gatt_client->service_id = service_id;
2707     gatt_client->connection_id = connection_id;
2708     gatt_client->attribute_handle = value_handle;
2709     gatt_client->attribute_offset = 0;
2710     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2711     gatt_client_run();
2712     return ERROR_CODE_SUCCESS;
2713 }
2714 
2715 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){
2716     return gatt_client_read_value_of_characteristic_using_value_handle_with_context(callback, con_handle, value_handle, 0, 0);
2717 
2718 }
2719 
2720 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){
2721     gatt_client_t * gatt_client;
2722     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2723     if (status != ERROR_CODE_SUCCESS){
2724         return status;
2725     }
2726 
2727     gatt_client->callback = callback;
2728     gatt_client->start_group_handle = start_handle;
2729     gatt_client->end_group_handle = end_handle;
2730     gatt_client->query_start_handle = start_handle;
2731     gatt_client->query_end_handle = end_handle;
2732     gatt_client->uuid16 = uuid16;
2733     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2734     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2735     gatt_client_run();
2736     return ERROR_CODE_SUCCESS;
2737 }
2738 
2739 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){
2740     gatt_client_t * gatt_client;
2741     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2742     if (status != ERROR_CODE_SUCCESS){
2743         return status;
2744     }
2745 
2746     gatt_client->callback = callback;
2747     gatt_client->start_group_handle = start_handle;
2748     gatt_client->end_group_handle = end_handle;
2749     gatt_client->query_start_handle = start_handle;
2750     gatt_client->query_end_handle = end_handle;
2751     gatt_client->uuid16 = 0;
2752     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2753     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2754     gatt_client_run();
2755     return ERROR_CODE_SUCCESS;
2756 }
2757 
2758 
2759 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2760     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2761 }
2762 
2763 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){
2764     gatt_client_t * gatt_client;
2765     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2766     if (status != ERROR_CODE_SUCCESS){
2767         return status;
2768     }
2769 
2770     gatt_client->callback = callback;
2771     gatt_client->attribute_handle = value_handle;
2772     gatt_client->attribute_offset = offset;
2773     gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2774     gatt_client_run();
2775     return ERROR_CODE_SUCCESS;
2776 }
2777 uint8_t gatt_client_read_long_value_of_characteristic_using_value_handle_with_context(btstack_packet_handler_t callback,
2778                                                                                       hci_con_handle_t con_handle, uint16_t value_handle,
2779                                                                                       uint16_t service_id, uint16_t connection_id){
2780     // TODO: move into gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset once
2781     //       gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset_and_context exists
2782     gatt_client_t * gatt_client;
2783     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2784     if (status != ERROR_CODE_SUCCESS){
2785         return status;
2786     }
2787     gatt_client->service_id = service_id;
2788     gatt_client->connection_id = connection_id;
2789     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2790 }
2791 
2792 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){
2793     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_context(callback, con_handle, value_handle, 0, 0);
2794 }
2795 
2796 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){
2797     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2798 }
2799 
2800 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){
2801     gatt_client_t * gatt_client;
2802     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2803     if (status != ERROR_CODE_SUCCESS){
2804         return status;
2805     }
2806 
2807 #ifdef ENABLE_GATT_OVER_EATT
2808     if (state == P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST){
2809         if (gatt_client->bearer_type != ATT_BEARER_ENHANCED_LE){
2810             return ERROR_CODE_COMMAND_DISALLOWED;
2811         }
2812     }
2813 #endif
2814 
2815     gatt_client->callback = callback;
2816     gatt_client->read_multiple_handle_count = num_value_handles;
2817     gatt_client->read_multiple_handles = value_handles;
2818     gatt_client->state = state;
2819     gatt_client_run();
2820     return ERROR_CODE_SUCCESS;
2821 }
2822 
2823 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){
2824     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_REQUEST);
2825 }
2826 
2827 #ifdef ENABLE_GATT_OVER_EATT
2828 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){
2829     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST);
2830 }
2831 #endif
2832 
2833 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){
2834     gatt_client_t * gatt_client;
2835     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2836     if (status != ERROR_CODE_SUCCESS){
2837         return status;
2838     }
2839 
2840     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2841     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2842 
2843     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2844 }
2845 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,
2846                                                                uint16_t value_length, uint8_t * value, uint16_t service_id, uint16_t connection_id){
2847     gatt_client_t * gatt_client;
2848     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2849     if (status != ERROR_CODE_SUCCESS){
2850         return status;
2851     }
2852 
2853     gatt_client->callback = callback;
2854     gatt_client->service_id = service_id;
2855     gatt_client->connection_id = connection_id;
2856     gatt_client->attribute_handle = value_handle;
2857     gatt_client->attribute_length = value_length;
2858     gatt_client->attribute_value = value;
2859     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2860     gatt_client_run();
2861     return ERROR_CODE_SUCCESS;
2862 }
2863 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) {
2864     return gatt_client_write_value_of_characteristic_with_context(callback, con_handle, value_handle, value_length, value, 0, 0);
2865 }
2866 
2867 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){
2868     gatt_client_t * gatt_client;
2869     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2870     if (status != ERROR_CODE_SUCCESS){
2871         return status;
2872     }
2873 
2874     gatt_client->callback = callback;
2875     gatt_client->attribute_handle = value_handle;
2876     gatt_client->attribute_length = value_length;
2877     gatt_client->attribute_offset = offset;
2878     gatt_client->attribute_value = value;
2879     gatt_client->state = P_W2_PREPARE_WRITE;
2880     gatt_client_run();
2881     return ERROR_CODE_SUCCESS;
2882 }
2883 
2884 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){
2885     // 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
2886     gatt_client_t * gatt_client;
2887     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2888     if (status != ERROR_CODE_SUCCESS){
2889         return status;
2890     }
2891     gatt_client->service_id = service_id;
2892     gatt_client->connection_id = connection_id;
2893     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2894 }
2895 
2896 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){
2897     return gatt_client_write_long_value_of_characteristic_with_context(callback, con_handle, value_handle, value_length, value, 0, 0);
2898 }
2899 
2900 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){
2901     gatt_client_t * gatt_client;
2902     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2903     if (status != ERROR_CODE_SUCCESS){
2904         return status;
2905     }
2906 
2907     gatt_client->callback = callback;
2908     gatt_client->attribute_handle = value_handle;
2909     gatt_client->attribute_length = value_length;
2910     gatt_client->attribute_offset = 0;
2911     gatt_client->attribute_value = value;
2912     gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2913     gatt_client_run();
2914     return ERROR_CODE_SUCCESS;
2915 }
2916 
2917 uint8_t gatt_client_write_client_characteristic_configuration_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle,
2918                                                               gatt_client_characteristic_t * characteristic, uint16_t configuration, uint16_t service_id, uint16_t connection_id){
2919     gatt_client_t * gatt_client;
2920     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2921     if (status != ERROR_CODE_SUCCESS){
2922         return status;
2923     }
2924 
2925     if (configuration > 3){
2926         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2927     }
2928 
2929     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2930         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2931         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2932         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2933     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2934                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2935         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2936         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2937     }
2938 
2939     gatt_client->callback = callback;
2940     gatt_client->service_id = service_id;
2941     gatt_client->connection_id = connection_id;
2942     gatt_client->start_group_handle = characteristic->value_handle;
2943     gatt_client->end_group_handle = characteristic->end_handle;
2944     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2945 
2946 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2947     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2948 #else
2949     gatt_client->state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2950 #endif
2951     gatt_client_run();
2952     return ERROR_CODE_SUCCESS;
2953 }
2954 
2955 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){
2956     return gatt_client_write_client_characteristic_configuration_with_context(callback, con_handle, characteristic, configuration, 0, 0);
2957 }
2958 
2959 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){
2960     gatt_client_t * gatt_client;
2961     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2962     if (status != ERROR_CODE_SUCCESS){
2963         return status;
2964     }
2965 
2966     gatt_client->callback = callback;
2967     gatt_client->attribute_handle = descriptor_handle;
2968 
2969     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2970     gatt_client_run();
2971     return ERROR_CODE_SUCCESS;
2972 }
2973 
2974 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2975     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2976 }
2977 
2978 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){
2979     gatt_client_t * gatt_client;
2980     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2981     if (status != ERROR_CODE_SUCCESS){
2982         return status;
2983     }
2984 
2985     gatt_client->callback = callback;
2986     gatt_client->attribute_handle = descriptor_handle;
2987     gatt_client->attribute_offset = offset;
2988     gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2989     gatt_client_run();
2990     return ERROR_CODE_SUCCESS;
2991 }
2992 
2993 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){
2994     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2995 }
2996 
2997 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){
2998     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2999 }
3000 
3001 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){
3002     gatt_client_t * gatt_client;
3003     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3004     if (status != ERROR_CODE_SUCCESS){
3005         return status;
3006     }
3007 
3008     gatt_client->callback = callback;
3009     gatt_client->attribute_handle = descriptor_handle;
3010     gatt_client->attribute_length = value_length;
3011     gatt_client->attribute_offset = 0;
3012     gatt_client->attribute_value = value;
3013     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
3014     gatt_client_run();
3015     return ERROR_CODE_SUCCESS;
3016 }
3017 
3018 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){
3019     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
3020 }
3021 
3022 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){
3023     gatt_client_t * gatt_client;
3024     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3025     if (status != ERROR_CODE_SUCCESS){
3026         return status;
3027     }
3028 
3029     gatt_client->callback = callback;
3030     gatt_client->attribute_handle = descriptor_handle;
3031     gatt_client->attribute_length = value_length;
3032     gatt_client->attribute_offset = offset;
3033     gatt_client->attribute_value = value;
3034     gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
3035     gatt_client_run();
3036     return ERROR_CODE_SUCCESS;
3037 }
3038 
3039 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){
3040     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
3041 }
3042 
3043 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){
3044     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
3045 }
3046 
3047 /**
3048  * @brief -> gatt complete event
3049  */
3050 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){
3051     gatt_client_t * gatt_client;
3052     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3053     if (status != ERROR_CODE_SUCCESS){
3054         return status;
3055     }
3056 
3057     gatt_client->callback = callback;
3058     gatt_client->attribute_handle = attribute_handle;
3059     gatt_client->attribute_length = value_length;
3060     gatt_client->attribute_offset = offset;
3061     gatt_client->attribute_value = value;
3062     gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
3063     gatt_client_run();
3064     return ERROR_CODE_SUCCESS;
3065 }
3066 
3067 /**
3068  * @brief -> gatt complete event
3069  */
3070 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3071     gatt_client_t * gatt_client;
3072     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3073     if (status != ERROR_CODE_SUCCESS){
3074         return status;
3075     }
3076 
3077     gatt_client->callback = callback;
3078     gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
3079     gatt_client_run();
3080     return ERROR_CODE_SUCCESS;
3081 }
3082 
3083 /**
3084  * @brief -> gatt complete event
3085  */
3086 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3087     gatt_client_t * gatt_client;
3088     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3089     if (status != ERROR_CODE_SUCCESS){
3090         return status;
3091     }
3092 
3093     gatt_client->callback = callback;
3094     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
3095     gatt_client_run();
3096     return ERROR_CODE_SUCCESS;
3097 }
3098 
3099 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
3100     service->start_group_handle = little_endian_read_16(packet, offset);
3101     service->end_group_handle = little_endian_read_16(packet, offset + 2);
3102     reverse_128(&packet[offset + 4], service->uuid128);
3103     if (uuid_has_bluetooth_prefix(service->uuid128)){
3104         service->uuid16 = big_endian_read_32(service->uuid128, 0);
3105     } else {
3106         service->uuid16 = 0;
3107     }
3108 }
3109 
3110 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
3111     characteristic->start_handle = little_endian_read_16(packet, offset);
3112     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
3113     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
3114     characteristic->properties = little_endian_read_16(packet, offset + 6);
3115     reverse_128(&packet[offset+8], characteristic->uuid128);
3116     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
3117         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
3118     } else {
3119         characteristic->uuid16 = 0;
3120     }
3121 }
3122 
3123 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
3124     descriptor->handle = little_endian_read_16(packet, offset);
3125     reverse_128(&packet[offset+2], descriptor->uuid128);
3126     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
3127         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
3128     } else {
3129         descriptor->uuid16 = 0;
3130     }
3131 }
3132 
3133 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3134     gatt_client_t * gatt_client;
3135     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3136     if (status != ERROR_CODE_SUCCESS){
3137         return;
3138     }
3139     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
3140         gatt_client->callback = callback;
3141         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
3142         gatt_client_run();
3143     }
3144 }
3145 
3146 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3147     gatt_client_t * gatt_client;
3148     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3149     if (status != ERROR_CODE_SUCCESS){
3150         return status;
3151     }
3152     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
3153     if (added == false){
3154         return ERROR_CODE_COMMAND_DISALLOWED;
3155     } else {
3156         att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
3157         return ERROR_CODE_SUCCESS;
3158     }
3159 }
3160 
3161 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3162     gatt_client_t * gatt_client;
3163     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3164     if (status != ERROR_CODE_SUCCESS){
3165         return status;
3166     }
3167     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
3168     if (added == false){
3169         return ERROR_CODE_COMMAND_DISALLOWED;
3170     } else {
3171         gatt_client_notify_can_send_query(gatt_client);
3172         return ERROR_CODE_SUCCESS;
3173     }
3174 }
3175 
3176 uint8_t gatt_client_remove_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3177     gatt_client_t * gatt_client;
3178     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3179     if (status != ERROR_CODE_SUCCESS){
3180         return status;
3181     }
3182     (void)btstack_linked_list_remove(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
3183     return ERROR_CODE_SUCCESS;
3184 }
3185 
3186 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3187     gatt_client_t * gatt_client;
3188     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3189     if (status != ERROR_CODE_SUCCESS){
3190         return status;
3191     }
3192     if (gatt_client->write_without_response_callback != NULL){
3193         return GATT_CLIENT_IN_WRONG_STATE;
3194     }
3195     gatt_client->write_without_response_callback = callback;
3196     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
3197     return ERROR_CODE_SUCCESS;
3198 }
3199 
3200 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
3201 void gatt_client_add_service_changed_handler(btstack_packet_callback_registration_t * callback) {
3202     btstack_linked_list_add_tail(&gatt_client_service_changed_handler, (btstack_linked_item_t*) callback);
3203 }
3204 
3205 void gatt_client_remove_service_changed_handler(btstack_packet_callback_registration_t * callback){
3206     btstack_linked_list_remove(&gatt_client_service_changed_handler, (btstack_linked_item_t*) callback);
3207 }
3208 #endif
3209 
3210 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined(ENABLE_GATT_OVER_EATT)
3211 
3212 #include "hci_event.h"
3213 
3214 static const hci_event_t gatt_client_connected = {
3215         GATT_EVENT_CONNECTED, 0, "11BH"
3216 };
3217 
3218 static const hci_event_t gatt_client_disconnected = {
3219         GATT_EVENT_DISCONNECTED, 0, "H"
3220 };
3221 
3222 static void
3223 gatt_client_emit_connected(btstack_packet_handler_t callback, uint8_t status, bd_addr_type_t addr_type, bd_addr_t addr,
3224                            hci_con_handle_t con_handle) {
3225     uint8_t buffer[20];
3226     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr, con_handle);
3227     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
3228 }
3229 
3230 #endif
3231 
3232 #ifdef ENABLE_GATT_OVER_CLASSIC
3233 
3234 #include "bluetooth_psm.h"
3235 
3236 // single active SDP query
3237 static gatt_client_t * gatt_client_classic_active_sdp_query;
3238 
3239 // macos protocol descriptor list requires 16 bytes
3240 static uint8_t gatt_client_classic_sdp_buffer[32];
3241 
3242 
3243 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
3244     btstack_linked_item_t *it;
3245     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
3246         gatt_client_t * gatt_client = (gatt_client_t *) it;
3247         if (memcmp(gatt_client->addr, addr, 6) == 0){
3248             return gatt_client;
3249         }
3250     }
3251     return NULL;
3252 }
3253 
3254 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
3255     btstack_linked_item_t *it;
3256     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
3257         gatt_client_t * gatt_client = (gatt_client_t *) it;
3258         if (gatt_client->l2cap_cid == l2cap_cid){
3259             return gatt_client;
3260         }
3261     }
3262     return NULL;
3263 }
3264 
3265 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
3266     // cache peer information
3267     bd_addr_t addr;
3268     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
3269     memcpy(addr, gatt_client->addr, 6);
3270     bd_addr_type_t addr_type = gatt_client->addr_type;
3271     gatt_client->addr_type = BD_ADDR_TYPE_ACL;
3272     hci_con_handle_t con_handle = gatt_client->con_handle;
3273     btstack_packet_handler_t callback = gatt_client->callback;
3274 
3275     if (status != ERROR_CODE_SUCCESS){
3276         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
3277         btstack_memory_gatt_client_free(gatt_client);
3278     }
3279 
3280     gatt_client_emit_connected(callback, status, addr_type, addr, con_handle);
3281 }
3282 
3283 static void gatt_client_classic_retry(btstack_timer_source_t * ts){
3284     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3285     if (gatt_client != NULL){
3286         gatt_client->state = P_W4_L2CAP_CONNECTION;
3287         att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3288     }
3289 }
3290 
3291 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
3292 
3293     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3294     gatt_client_timeout_stop(gatt_client);
3295 
3296     hci_con_handle_t con_handle = gatt_client->con_handle;
3297     btstack_packet_handler_t callback = gatt_client->callback;
3298     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
3299     btstack_memory_gatt_client_free(gatt_client);
3300 
3301     uint8_t buffer[20];
3302     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
3303     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
3304 }
3305 
3306 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
3307     des_iterator_t des_list_it;
3308     des_iterator_t prot_it;
3309 
3310     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
3311         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
3312         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
3313             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
3314                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
3315                     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)) {
3316                         uint8_t       *des_element;
3317                         uint8_t       *element;
3318                         uint32_t       uuid;
3319 
3320                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
3321 
3322                         des_element = des_iterator_get_element(&des_list_it);
3323                         des_iterator_init(&prot_it, des_element);
3324                         element = des_iterator_get_element(&prot_it);
3325 
3326                         if (de_get_element_type(element) != DE_UUID) continue;
3327 
3328                         uuid = de_get_uuid32(element);
3329                         des_iterator_next(&prot_it);
3330                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
3331                         switch (uuid){
3332                             case BLUETOOTH_PROTOCOL_L2CAP:
3333                                 if (!des_iterator_has_more(&prot_it)) continue;
3334                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
3335                                 break;
3336                             default:
3337                                 break;
3338                         }
3339                     }
3340                     break;
3341 
3342                 default:
3343                     break;
3344             }
3345         }
3346     }
3347 }
3348 
3349 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3350     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
3351     btstack_assert(gatt_client != NULL);
3352     uint8_t status;
3353 
3354     // TODO: handle sdp events, get l2cap psm
3355     switch (hci_event_packet_get_type(packet)){
3356         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
3357             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
3358             // TODO:
3359             return;
3360         case SDP_EVENT_QUERY_COMPLETE:
3361             status = sdp_event_query_complete_get_status(packet);
3362             gatt_client_classic_active_sdp_query = NULL;
3363             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
3364             if (status != ERROR_CODE_SUCCESS) break;
3365             if (gatt_client->l2cap_psm == 0) {
3366                 status = SDP_SERVICE_NOT_FOUND;
3367                 break;
3368             }
3369             break;
3370         default:
3371             btstack_assert(false);
3372             return;
3373     }
3374 
3375     // done
3376     if (status == ERROR_CODE_SUCCESS){
3377         gatt_client->state = P_W4_L2CAP_CONNECTION;
3378         status = att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3379     }
3380     if (status != ERROR_CODE_SUCCESS) {
3381         gatt_client_classic_handle_connected(gatt_client, status);
3382     }
3383 }
3384 
3385 static void gatt_client_classic_sdp_start(void * context){
3386     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
3387     gatt_client_classic_active_sdp_query->state = P_W4_SDP_QUERY;
3388     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3389 }
3390 
3391 static void gatt_client_classic_emit_connected(void * context){
3392     gatt_client_t * gatt_client = (gatt_client_t *) context;
3393     gatt_client->state = P_READY;
3394     gatt_client_emit_connected(gatt_client->callback, ERROR_CODE_SUCCESS, gatt_client->addr_type, gatt_client->addr, gatt_client->con_handle);
3395 }
3396 
3397 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
3398     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
3399     if (gatt_client != NULL){
3400         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
3401     }
3402     gatt_client = btstack_memory_gatt_client_get();
3403     if (gatt_client == NULL){
3404         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3405     }
3406     // init state
3407     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
3408     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
3409     memcpy(gatt_client->addr, addr, 6);
3410     gatt_client->addr_type = BD_ADDR_TYPE_ACL;
3411     gatt_client->mtu = ATT_DEFAULT_MTU;
3412     gatt_client->security_level = LEVEL_0;
3413     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3414     gatt_client->callback = callback;
3415 #ifdef ENABLE_GATT_OVER_EATT
3416     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3417 #endif
3418     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
3419 
3420     // schedule emitted event if already connected, otherwise
3421     bool already_connected = false;
3422     hci_connection_t * hci_connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3423     if (hci_connection != NULL){
3424         if (hci_connection->att_server.l2cap_cid != 0){
3425             already_connected = true;
3426         }
3427     }
3428     gatt_client->callback_request.context = gatt_client;
3429     if (already_connected){
3430         gatt_client->con_handle = hci_connection->con_handle;
3431         gatt_client->callback_request.callback = &gatt_client_classic_emit_connected;
3432         gatt_client->state = P_W2_EMIT_CONNECTED;
3433         btstack_run_loop_execute_on_main_thread(&gatt_client->callback_request);
3434     } else {
3435         gatt_client->callback_request.callback = &gatt_client_classic_sdp_start;
3436         gatt_client->state = P_W2_SDP_QUERY;
3437         sdp_client_register_query_callback(&gatt_client->callback_request);
3438     }
3439     return ERROR_CODE_SUCCESS;
3440 }
3441 
3442 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3443     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
3444     if (gatt_client == NULL){
3445         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3446     }
3447     gatt_client->callback = callback;
3448     return l2cap_disconnect(gatt_client->l2cap_cid);
3449 }
3450 #endif
3451 
3452 #ifdef ENABLE_GATT_OVER_EATT
3453 
3454 #define MAX_NR_EATT_CHANNELS 5
3455 
3456 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
3457 
3458 static uint8_t gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client_t * gatt_client, gatt_client_state_t state){
3459     uint8_t num_clients = 0;
3460     btstack_linked_list_iterator_t it;
3461     btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3462     while (btstack_linked_list_iterator_has_next(&it)){
3463         gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3464         if (eatt_client->state == state){
3465             num_clients++;
3466         }
3467     }
3468     return num_clients;
3469 }
3470 
3471 static void gatt_client_eatt_finalize(gatt_client_t * gatt_client) {
3472     // free eatt clients
3473     btstack_linked_list_iterator_t it;
3474     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3475     while (btstack_linked_list_iterator_has_next(&it)) {
3476         gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3477         btstack_linked_list_iterator_remove(&it);
3478         btstack_memory_gatt_client_free(eatt_client);
3479     }
3480 }
3481 
3482 // all channels connected
3483 static void gatt_client_le_enhanced_handle_connected(gatt_client_t * gatt_client, uint8_t status) {
3484     if (status == ERROR_CODE_SUCCESS){
3485         uint8_t num_ready = gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_READY);
3486         if (num_ready > 0){
3487             gatt_client->eatt_state = GATT_CLIENT_EATT_READY;
3488             // free unused channels
3489             btstack_linked_list_iterator_t it;
3490             btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3491             while (btstack_linked_list_iterator_has_next(&it)) {
3492                 gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3493                 if (eatt_client->state == P_L2CAP_CLOSED){
3494                     btstack_linked_list_iterator_remove(&it);
3495                     btstack_memory_gatt_client_free(eatt_client);
3496                 }
3497             }
3498         } else {
3499             hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3500             btstack_assert(hci_connection != NULL);
3501             if (hci_connection->att_server.incoming_connection_request){
3502                 hci_connection->att_server.incoming_connection_request = false;
3503                 log_info("Collision, retry in 100ms");
3504                 gatt_client->state = P_W2_L2CAP_CONNECT;
3505                 // set timer for retry
3506                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
3507                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_le_enhanced_retry);
3508                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
3509                 return;
3510             } else {
3511                 gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3512                 status = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3513             }
3514         }
3515     } else {
3516         gatt_client_eatt_finalize(gatt_client);
3517         gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3518     }
3519 
3520     gatt_client_emit_connected(gatt_client->callback, status, gatt_client->addr_type, gatt_client->addr, gatt_client->con_handle);
3521 }
3522 
3523 // single channel disconnected
3524 static void gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client_t * gatt_client, gatt_client_t * eatt_client) {
3525 
3526     // report error
3527     gatt_client_report_error_if_pending(eatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3528 
3529     // free memory
3530     btstack_linked_list_remove(&gatt_client->eatt_clients, (btstack_linked_item_t *) eatt_client);
3531     btstack_memory_gatt_client_free(eatt_client);
3532 
3533     // last channel
3534     if (btstack_linked_list_empty(&gatt_client->eatt_clients)){
3535         hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3536         hci_connection->att_server.eatt_outgoing_active = false;
3537 
3538         if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY) {
3539             // report disconnected if last channel closed
3540             uint8_t buffer[20];
3541             uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, gatt_client->con_handle);
3542             (*gatt_client->callback)(HCI_EVENT_PACKET, 0, buffer, len);
3543         }
3544     }
3545 }
3546 
3547 static gatt_client_t * gatt_client_le_enhanced_get_context_for_l2cap_cid(uint16_t l2cap_cid, gatt_client_t ** out_eatt_client){
3548     btstack_linked_list_iterator_t it;
3549     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3550     while (btstack_linked_list_iterator_has_next(&it)) {
3551         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3552         btstack_linked_list_iterator_t it2;
3553         btstack_linked_list_iterator_init(&it2, &gatt_client->eatt_clients);
3554         while (btstack_linked_list_iterator_has_next(&it2)) {
3555             gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it2);
3556             if (eatt_client->l2cap_cid == l2cap_cid){
3557                 *out_eatt_client = eatt_client;
3558                 return gatt_client;
3559             }
3560         }
3561     }
3562     return NULL;
3563 }
3564 
3565 static void gatt_client_le_enhanced_setup_l2cap_channel(gatt_client_t * gatt_client){
3566     uint8_t num_channels = gatt_client->eatt_num_clients;
3567 
3568     // setup channels
3569     uint16_t buffer_size_per_client = gatt_client->eatt_storage_size / num_channels;
3570     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3571     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
3572     uint16_t  new_cids[MAX_NR_EATT_CHANNELS];
3573     memset(gatt_client->eatt_storage_buffer, 0, gatt_client->eatt_storage_size);
3574     uint8_t i;
3575     for (i=0;i<gatt_client->eatt_num_clients; i++){
3576         receive_buffers[i] = &gatt_client->eatt_storage_buffer[REPORT_PREBUFFER_HEADER];
3577         gatt_client->eatt_storage_buffer += REPORT_PREBUFFER_HEADER + max_mtu;
3578     }
3579 
3580     log_info("%u EATT clients with receive buffer size %u", gatt_client->eatt_num_clients, buffer_size_per_client);
3581 
3582     uint8_t status = l2cap_ecbm_create_channels(&gatt_client_le_enhanced_packet_handler,
3583                                                 gatt_client->con_handle,
3584                                                 gatt_client->security_level,
3585                                                 BLUETOOTH_PSM_EATT, num_channels,
3586                                                 L2CAP_LE_AUTOMATIC_CREDITS,
3587                                                 buffer_size_per_client,
3588                                                 receive_buffers,
3589                                                 new_cids);
3590 
3591     if (status == ERROR_CODE_SUCCESS){
3592         i = 0;
3593         btstack_linked_list_iterator_t it;
3594         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3595         while (btstack_linked_list_iterator_has_next(&it)) {
3596             gatt_client_t *new_eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3597 
3598             // init state with new cid and transmit buffer
3599             new_eatt_client->bearer_type = ATT_BEARER_ENHANCED_LE;
3600             new_eatt_client->con_handle = gatt_client->con_handle;
3601             new_eatt_client->mtu = 64;
3602             new_eatt_client->security_level = LEVEL_0;
3603             new_eatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3604             new_eatt_client->state = P_W4_L2CAP_CONNECTION;
3605             new_eatt_client->l2cap_cid = new_cids[i];
3606             new_eatt_client->eatt_storage_buffer = gatt_client->eatt_storage_buffer;
3607             gatt_client->eatt_storage_buffer += max_mtu;
3608             i++;
3609         }
3610         gatt_client->eatt_state = GATT_CLIENT_EATT_L2CAP_SETUP;
3611     } else {
3612         gatt_client_le_enhanced_handle_connected(gatt_client, status);
3613     }
3614 }
3615 
3616 static void gatt_client_le_enhanced_retry(btstack_timer_source_t * ts){
3617     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3618     if (gatt_client != NULL){
3619         gatt_client->state = P_W4_L2CAP_CONNECTION;
3620         gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3621     }
3622 }
3623 
3624 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
3625     gatt_client_t *gatt_client;
3626     gatt_client_t *eatt_client;
3627     hci_con_handle_t con_handle;
3628     uint16_t l2cap_cid;
3629     uint8_t status;
3630     gatt_client_characteristic_t characteristic;
3631     gatt_client_service_t service;
3632     switch (packet_type) {
3633         case HCI_EVENT_PACKET:
3634             switch (hci_event_packet_get_type(packet)) {
3635                 case GATT_EVENT_SERVICE_QUERY_RESULT:
3636                     con_handle = gatt_event_service_query_result_get_handle(packet);
3637                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3638                     btstack_assert(gatt_client != NULL);
3639                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE);
3640                     gatt_event_service_query_result_get_service(packet, &service);
3641                     gatt_client->gatt_service_start_group_handle = service.start_group_handle;
3642                     gatt_client->gatt_service_end_group_handle = service.end_group_handle;
3643                     break;
3644                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
3645                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
3646                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3647                     btstack_assert(gatt_client != NULL);
3648                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE);
3649                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
3650                         gatt_client->gatt_server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
3651                     }
3652                     break;
3653                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
3654                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
3655                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3656                     btstack_assert(gatt_client != NULL);
3657                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE);
3658                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
3659                     gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
3660                     break;
3661                 case GATT_EVENT_QUERY_COMPLETE:
3662                     con_handle = gatt_event_query_complete_get_handle(packet);
3663                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3664                     btstack_assert(gatt_client != NULL);
3665                     switch (gatt_client->eatt_state){
3666                         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE:
3667                             if (gatt_client->gatt_service_start_group_handle == 0){
3668                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3669                             } else {
3670                                 gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
3671                             }
3672                             break;
3673                         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE:
3674                             if ((gatt_client->gatt_server_supported_features & 1) == 0) {
3675                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3676                             } else {
3677                                 gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND;
3678                             }
3679                             break;
3680                         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE:
3681                             if (gatt_client->gatt_client_supported_features_handle == 0){
3682                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3683                             } else {
3684                                 gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
3685                             }
3686                             break;
3687                         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE:
3688                             gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3689                             break;
3690                         default:
3691                             break;
3692                     }
3693                     break;
3694                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
3695                     l2cap_cid = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
3696                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3697 
3698                     btstack_assert(gatt_client != NULL);
3699                     btstack_assert(eatt_client != NULL);
3700                     btstack_assert(eatt_client->state == P_W4_L2CAP_CONNECTION);
3701 
3702                     status = l2cap_event_channel_opened_get_status(packet);
3703                     if (status == ERROR_CODE_SUCCESS){
3704                         eatt_client->state = P_READY;
3705                         eatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
3706                     } else {
3707                         eatt_client->state = P_L2CAP_CLOSED;
3708                     }
3709                     // connected if opened event for all channels received
3710                     if (gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_W4_L2CAP_CONNECTION) == 0){
3711                         gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_SUCCESS);
3712                     }
3713                     break;
3714                 case L2CAP_EVENT_CHANNEL_CLOSED:
3715                     l2cap_cid = l2cap_event_channel_closed_get_local_cid(packet);
3716                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3717                     btstack_assert(gatt_client != NULL);
3718                     btstack_assert(eatt_client != NULL);
3719                     gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3720                     break;
3721                 default:
3722                     break;
3723             }
3724             break;
3725         case L2CAP_DATA_PACKET:
3726             gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(channel, &eatt_client);
3727             btstack_assert(gatt_client != NULL);
3728             btstack_assert(eatt_client != NULL);
3729             gatt_client_handle_att_response(eatt_client, packet, size);
3730             gatt_client_run();
3731             break;
3732         default:
3733             break;
3734     }
3735 }
3736 
3737 static bool gatt_client_le_enhanced_handle_can_send_query(gatt_client_t * gatt_client){
3738     uint8_t status = ERROR_CODE_SUCCESS;
3739     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
3740     switch (gatt_client->eatt_state){
3741         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND:
3742             gatt_client->gatt_service_start_group_handle = 0;
3743             gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE;
3744             status = gatt_client_discover_primary_services_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3745                                                                      gatt_client->con_handle,
3746                                                                      ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3747             break;
3748         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
3749             gatt_client->gatt_server_supported_features = 0;
3750             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
3751             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3752                                                                          gatt_client->con_handle,
3753                                                                          gatt_client->gatt_service_start_group_handle,
3754                                                                          gatt_client->gatt_service_end_group_handle,
3755                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
3756             return true;
3757         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
3758             gatt_client->gatt_client_supported_features_handle = 0;
3759             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE;
3760             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3761                                                                                      gatt_client->con_handle,
3762                                                                                      gatt_client->gatt_service_start_group_handle,
3763                                                                                      gatt_client->gatt_service_end_group_handle,
3764                                                                                      ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
3765             return true;
3766         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
3767             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
3768             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
3769                                                                gatt_client->gatt_client_supported_features_handle, 1,
3770                                                                &gatt_client_supported_features);
3771             return true;
3772         default:
3773             break;
3774     }
3775     btstack_assert(status == ERROR_CODE_SUCCESS);
3776     UNUSED(status);
3777     return false;
3778 }
3779 
3780 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) {
3781     gatt_client_t * gatt_client;
3782     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3783     if (status != ERROR_CODE_SUCCESS){
3784         return status;
3785     }
3786 
3787     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
3788         return ERROR_CODE_COMMAND_DISALLOWED;
3789     }
3790 
3791     // need one buffer for sending and one for receiving. Receiving includes pre-buffer for reports
3792     uint16_t buffer_size_per_client = storage_size / num_channels;
3793     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3794     if (max_mtu < 64) {
3795         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3796     }
3797 
3798     if ((num_channels == 0) || (num_channels > MAX_NR_EATT_CHANNELS)){
3799         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3800     }
3801 
3802     // create max num_channel eatt clients
3803     uint8_t i;
3804     btstack_linked_list_t eatt_clients = NULL;
3805     for (i=0;i<num_channels;i++) {
3806         gatt_client_t * new_gatt_client = btstack_memory_gatt_client_get();
3807         if (new_gatt_client == NULL) {
3808             break;
3809         }
3810         btstack_linked_list_add(&eatt_clients, (btstack_linked_item_t*)new_gatt_client);
3811     }
3812 
3813     if (i != num_channels){
3814         while (true){
3815             gatt_client = (gatt_client_t *) btstack_linked_list_pop(&eatt_clients);
3816             if (gatt_client == NULL) {
3817                 break;
3818             }
3819             btstack_memory_gatt_client_free(gatt_client);
3820         }
3821         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3822     }
3823 
3824     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
3825     hci_connection->att_server.eatt_outgoing_active = true;
3826 
3827     gatt_client->callback = callback;
3828     gatt_client->eatt_num_clients   = num_channels;
3829     gatt_client->eatt_storage_buffer = storage_buffer;
3830     gatt_client->eatt_storage_size   = storage_size;
3831     gatt_client->eatt_clients = eatt_clients;
3832     gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND;
3833     gatt_client_notify_can_send_query(gatt_client);
3834 
3835     return ERROR_CODE_SUCCESS;
3836 }
3837 
3838 #endif
3839 
3840 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3841 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3842     gatt_client_att_packet_handler(packet_type, handle, packet, size);
3843 }
3844 
3845 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
3846     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
3847     return status;
3848 }
3849 #endif
3850