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