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