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