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