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