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