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