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