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