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