xref: /btstack/src/ble/gatt_client.c (revision ab6f9d8f7ccbef42e9e2c44010c775d535d8fe34)
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){
2129                         if ((hci_connection != NULL) && hci_connection->att_server.incoming_connection_request) {
2130                             log_info("Collision, retry in 100ms");
2131                             gatt_client->state = P_W2_L2CAP_CONNECT;
2132                             // set timer for retry
2133                             btstack_run_loop_set_timer(&gatt_client->gc_timeout, 100);
2134                             btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_classic_retry);
2135                             btstack_run_loop_add_timer(&gatt_client->gc_timeout);
2136                             break;
2137                         }
2138                     }
2139                     // if status != 0, gatt_client will be discarded
2140                     gatt_client->state = P_READY;
2141                     gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2142                     gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2143                     gatt_client_classic_handle_connected(gatt_client, status);
2144                     break;
2145                 case L2CAP_EVENT_CHANNEL_CLOSED:
2146                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2147                     // discard gatt client object
2148                     gatt_client_classic_handle_disconnected(gatt_client);
2149                     break;
2150 #endif
2151                 case L2CAP_EVENT_CAN_SEND_NOW:
2152                     gatt_client_run();
2153                     break;
2154                     // att_server has negotiated the mtu for this connection, cache if context exists
2155                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
2156                     if (size < 6u) break;
2157                     gatt_client = gatt_client_get_context_for_handle(handle);
2158                     if (gatt_client == NULL) break;
2159                     gatt_client->mtu = little_endian_read_16(packet, 4);
2160                     break;
2161                 default:
2162                     break;
2163             }
2164             break;
2165 
2166         case ATT_DATA_PACKET:
2167             // special cases: notifications & indications motivate creating context
2168             switch (packet[0]) {
2169                 case ATT_HANDLE_VALUE_NOTIFICATION:
2170                 case ATT_HANDLE_VALUE_INDICATION:
2171                     gatt_client_provide_context_for_handle(handle, &gatt_client);
2172                     break;
2173                 default:
2174                     gatt_client = gatt_client_get_context_for_handle(handle);
2175                     break;
2176             }
2177 
2178             if (gatt_client != NULL) {
2179                 gatt_client_handle_att_response(gatt_client, packet, size);
2180                 gatt_client_run();
2181             }
2182             break;
2183 
2184 #ifdef ENABLE_GATT_OVER_CLASSIC
2185         case L2CAP_DATA_PACKET:
2186             gatt_client = gatt_client_get_context_for_l2cap_cid(handle);
2187             btstack_assert(gatt_client != NULL);
2188             gatt_client_handle_att_response(gatt_client, packet, size);
2189             gatt_client_run();
2190             break;
2191 #endif
2192 
2193         default:
2194             break;
2195     }
2196 }
2197 
2198 #ifdef ENABLE_LE_SIGNED_WRITE
2199 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2200     btstack_linked_list_iterator_t it;
2201     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2202     while (btstack_linked_list_iterator_has_next(&it)){
2203         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2204         if (gatt_client->state == P_W4_CMAC_RESULT){
2205             // store result
2206             (void)memcpy(gatt_client->cmac, hash, 8);
2207             // reverse_64(hash, gatt_client->cmac);
2208             gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2209             gatt_client_run();
2210             return;
2211         }
2212     }
2213 }
2214 
2215 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){
2216     gatt_client_t * gatt_client;
2217     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2218     if (status != ERROR_CODE_SUCCESS){
2219         return status;
2220     }
2221     if (is_ready(gatt_client) == 0){
2222         return GATT_CLIENT_IN_WRONG_STATE;
2223     }
2224 
2225     gatt_client->callback = callback;
2226     gatt_client->attribute_handle = value_handle;
2227     gatt_client->attribute_length = message_len;
2228     gatt_client->attribute_value = message;
2229     gatt_client->state = P_W4_IDENTITY_RESOLVING;
2230     gatt_client_run();
2231     return ERROR_CODE_SUCCESS;
2232 }
2233 #endif
2234 
2235 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2236     gatt_client_t * gatt_client;
2237     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2238     if (status != ERROR_CODE_SUCCESS){
2239         return status;
2240     }
2241 
2242     gatt_client->callback = callback;
2243     gatt_client->start_group_handle = 0x0001;
2244     gatt_client->end_group_handle   = 0xffff;
2245     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2246     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2247     gatt_client_run();
2248     return ERROR_CODE_SUCCESS;
2249 }
2250 
2251 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2252     gatt_client_t * gatt_client;
2253     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2254     if (status != ERROR_CODE_SUCCESS){
2255         return status;
2256     }
2257 
2258     gatt_client->callback = callback;
2259     gatt_client->start_group_handle = 0x0001;
2260     gatt_client->end_group_handle   = 0xffff;
2261     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2262     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2263     gatt_client_run();
2264     return ERROR_CODE_SUCCESS;
2265 }
2266 
2267 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2268     gatt_client_t * gatt_client;
2269     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2270     if (status != ERROR_CODE_SUCCESS){
2271         return status;
2272     }
2273 
2274     gatt_client->callback = callback;
2275     gatt_client->start_group_handle = 0x0001;
2276     gatt_client->end_group_handle   = 0xffff;
2277     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2278     gatt_client->uuid16 = uuid16;
2279     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2280     gatt_client_run();
2281     return ERROR_CODE_SUCCESS;
2282 }
2283 
2284 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2285     gatt_client_t * gatt_client;
2286     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2287     if (status != ERROR_CODE_SUCCESS){
2288         return status;
2289     }
2290 
2291     gatt_client->callback = callback;
2292     gatt_client->start_group_handle = 0x0001;
2293     gatt_client->end_group_handle   = 0xffff;
2294     gatt_client->uuid16 = 0;
2295     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2296     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2297     gatt_client_run();
2298     return ERROR_CODE_SUCCESS;
2299 }
2300 
2301 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2302     gatt_client_t * gatt_client;
2303     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2304     if (status != ERROR_CODE_SUCCESS){
2305         return status;
2306     }
2307 
2308     gatt_client->callback = callback;
2309     gatt_client->start_group_handle = service->start_group_handle;
2310     gatt_client->end_group_handle   = service->end_group_handle;
2311     gatt_client->filter_with_uuid = 0;
2312     gatt_client->characteristic_start_handle = 0;
2313     gatt_client->state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2314     gatt_client_run();
2315     return ERROR_CODE_SUCCESS;
2316 }
2317 
2318 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){
2319     gatt_client_t * gatt_client;
2320     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2321     if (status != ERROR_CODE_SUCCESS){
2322         return status;
2323     }
2324 
2325     gatt_client->callback = callback;
2326     gatt_client->start_group_handle = service->start_group_handle;
2327     gatt_client->end_group_handle   = service->end_group_handle;
2328     gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2329 
2330     gatt_client_run();
2331     return ERROR_CODE_SUCCESS;
2332 }
2333 
2334 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){
2335     gatt_client_t * gatt_client;
2336     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2337     if (status != ERROR_CODE_SUCCESS){
2338         return status;
2339     }
2340 
2341     gatt_client->callback = callback;
2342     gatt_client->start_group_handle = start_handle;
2343     gatt_client->end_group_handle   = end_handle;
2344     gatt_client->filter_with_uuid = 1;
2345     gatt_client->uuid16 = uuid16;
2346     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2347     gatt_client->characteristic_start_handle = 0;
2348     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2349     gatt_client_run();
2350     return ERROR_CODE_SUCCESS;
2351 }
2352 
2353 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){
2354     gatt_client_t * gatt_client;
2355     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2356     if (status != ERROR_CODE_SUCCESS){
2357         return status;
2358     }
2359 
2360     gatt_client->callback = callback;
2361     gatt_client->start_group_handle = start_handle;
2362     gatt_client->end_group_handle   = end_handle;
2363     gatt_client->filter_with_uuid = 1;
2364     gatt_client->uuid16 = 0;
2365     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2366     gatt_client->characteristic_start_handle = 0;
2367     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2368     gatt_client_run();
2369     return ERROR_CODE_SUCCESS;
2370 }
2371 
2372 
2373 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){
2374     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2375 }
2376 
2377 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){
2378     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2379 }
2380 
2381 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2382     gatt_client_t * gatt_client;
2383     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2384     if (status != ERROR_CODE_SUCCESS){
2385         return status;
2386     }
2387 
2388     if (characteristic->value_handle == characteristic->end_handle){
2389         return ERROR_CODE_SUCCESS;
2390     }
2391     gatt_client->callback = callback;
2392     gatt_client->start_group_handle = characteristic->value_handle + 1u;
2393     gatt_client->end_group_handle   = characteristic->end_handle;
2394     gatt_client->state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2395     gatt_client_run();
2396     return ERROR_CODE_SUCCESS;
2397 }
2398 
2399 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){
2400     gatt_client_t * gatt_client;
2401     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2402     if (status != ERROR_CODE_SUCCESS){
2403         return status;
2404     }
2405 
2406     gatt_client->callback = callback;
2407     gatt_client->attribute_handle = value_handle;
2408     gatt_client->attribute_offset = 0;
2409     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2410     gatt_client_run();
2411     return ERROR_CODE_SUCCESS;
2412 }
2413 
2414 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){
2415     gatt_client_t * gatt_client;
2416     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2417     if (status != ERROR_CODE_SUCCESS){
2418         return status;
2419     }
2420 
2421     gatt_client->callback = callback;
2422     gatt_client->start_group_handle = start_handle;
2423     gatt_client->end_group_handle = end_handle;
2424     gatt_client->query_start_handle = start_handle;
2425     gatt_client->query_end_handle = end_handle;
2426     gatt_client->uuid16 = uuid16;
2427     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2428     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2429     gatt_client_run();
2430     return ERROR_CODE_SUCCESS;
2431 }
2432 
2433 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){
2434     gatt_client_t * gatt_client;
2435     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2436     if (status != ERROR_CODE_SUCCESS){
2437         return status;
2438     }
2439 
2440     gatt_client->callback = callback;
2441     gatt_client->start_group_handle = start_handle;
2442     gatt_client->end_group_handle = end_handle;
2443     gatt_client->query_start_handle = start_handle;
2444     gatt_client->query_end_handle = end_handle;
2445     gatt_client->uuid16 = 0;
2446     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2447     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2448     gatt_client_run();
2449     return ERROR_CODE_SUCCESS;
2450 }
2451 
2452 
2453 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2454     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2455 }
2456 
2457 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){
2458     gatt_client_t * gatt_client;
2459     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2460     if (status != ERROR_CODE_SUCCESS){
2461         return status;
2462     }
2463 
2464     gatt_client->callback = callback;
2465     gatt_client->attribute_handle = value_handle;
2466     gatt_client->attribute_offset = offset;
2467     gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2468     gatt_client_run();
2469     return ERROR_CODE_SUCCESS;
2470 }
2471 
2472 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){
2473     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2474 }
2475 
2476 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){
2477     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2478 }
2479 
2480 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){
2481     gatt_client_t * gatt_client;
2482     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2483     if (status != ERROR_CODE_SUCCESS){
2484         return status;
2485     }
2486 
2487 #ifdef ENABLE_GATT_OVER_EATT
2488     if (state == P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST){
2489         if (gatt_client->bearer_type != ATT_BEARER_ENHANCED_LE){
2490             return ERROR_CODE_COMMAND_DISALLOWED;
2491         }
2492     }
2493 #endif
2494 
2495     gatt_client->callback = callback;
2496     gatt_client->read_multiple_handle_count = num_value_handles;
2497     gatt_client->read_multiple_handles = value_handles;
2498     gatt_client->state = state;
2499     gatt_client_run();
2500     return ERROR_CODE_SUCCESS;
2501 }
2502 
2503 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){
2504     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_REQUEST);
2505 }
2506 
2507 #ifdef ENABLE_GATT_OVER_EATT
2508 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){
2509     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST);
2510 }
2511 #endif
2512 
2513 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){
2514     gatt_client_t * gatt_client;
2515     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2516     if (status != ERROR_CODE_SUCCESS){
2517         return status;
2518     }
2519 
2520     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2521     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2522 
2523     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2524 }
2525 
2526 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){
2527     gatt_client_t * gatt_client;
2528     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2529     if (status != ERROR_CODE_SUCCESS){
2530         return status;
2531     }
2532 
2533     gatt_client->callback = callback;
2534     gatt_client->attribute_handle = value_handle;
2535     gatt_client->attribute_length = value_length;
2536     gatt_client->attribute_value = value;
2537     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2538     gatt_client_run();
2539     return ERROR_CODE_SUCCESS;
2540 }
2541 
2542 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){
2543     gatt_client_t * gatt_client;
2544     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2545     if (status != ERROR_CODE_SUCCESS){
2546         return status;
2547     }
2548 
2549     gatt_client->callback = callback;
2550     gatt_client->attribute_handle = value_handle;
2551     gatt_client->attribute_length = value_length;
2552     gatt_client->attribute_offset = offset;
2553     gatt_client->attribute_value = value;
2554     gatt_client->state = P_W2_PREPARE_WRITE;
2555     gatt_client_run();
2556     return ERROR_CODE_SUCCESS;
2557 }
2558 
2559 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){
2560     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2561 }
2562 
2563 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){
2564     gatt_client_t * gatt_client;
2565     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2566     if (status != ERROR_CODE_SUCCESS){
2567         return status;
2568     }
2569 
2570     gatt_client->callback = callback;
2571     gatt_client->attribute_handle = value_handle;
2572     gatt_client->attribute_length = value_length;
2573     gatt_client->attribute_offset = 0;
2574     gatt_client->attribute_value = value;
2575     gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2576     gatt_client_run();
2577     return ERROR_CODE_SUCCESS;
2578 }
2579 
2580 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){
2581     gatt_client_t * gatt_client;
2582     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2583     if (status != ERROR_CODE_SUCCESS){
2584         return status;
2585     }
2586 
2587     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2588         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2589         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2590         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2591     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2592                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2593         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2594         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2595     }
2596 
2597     gatt_client->callback = callback;
2598     gatt_client->start_group_handle = characteristic->value_handle;
2599     gatt_client->end_group_handle = characteristic->end_handle;
2600     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2601 
2602 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2603     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2604 #else
2605     gatt_client->state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2606 #endif
2607     gatt_client_run();
2608     return ERROR_CODE_SUCCESS;
2609 }
2610 
2611 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){
2612     gatt_client_t * gatt_client;
2613     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2614     if (status != ERROR_CODE_SUCCESS){
2615         return status;
2616     }
2617 
2618     gatt_client->callback = callback;
2619     gatt_client->attribute_handle = descriptor_handle;
2620 
2621     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2622     gatt_client_run();
2623     return ERROR_CODE_SUCCESS;
2624 }
2625 
2626 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2627     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2628 }
2629 
2630 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){
2631     gatt_client_t * gatt_client;
2632     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2633     if (status != ERROR_CODE_SUCCESS){
2634         return status;
2635     }
2636 
2637     gatt_client->callback = callback;
2638     gatt_client->attribute_handle = descriptor_handle;
2639     gatt_client->attribute_offset = offset;
2640     gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2641     gatt_client_run();
2642     return ERROR_CODE_SUCCESS;
2643 }
2644 
2645 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){
2646     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2647 }
2648 
2649 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){
2650     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2651 }
2652 
2653 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){
2654     gatt_client_t * gatt_client;
2655     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2656     if (status != ERROR_CODE_SUCCESS){
2657         return status;
2658     }
2659 
2660     gatt_client->callback = callback;
2661     gatt_client->attribute_handle = descriptor_handle;
2662     gatt_client->attribute_length = value_length;
2663     gatt_client->attribute_offset = 0;
2664     gatt_client->attribute_value = value;
2665     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2666     gatt_client_run();
2667     return ERROR_CODE_SUCCESS;
2668 }
2669 
2670 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){
2671     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2672 }
2673 
2674 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){
2675     gatt_client_t * gatt_client;
2676     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2677     if (status != ERROR_CODE_SUCCESS){
2678         return status;
2679     }
2680 
2681     gatt_client->callback = callback;
2682     gatt_client->attribute_handle = descriptor_handle;
2683     gatt_client->attribute_length = value_length;
2684     gatt_client->attribute_offset = offset;
2685     gatt_client->attribute_value = value;
2686     gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2687     gatt_client_run();
2688     return ERROR_CODE_SUCCESS;
2689 }
2690 
2691 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){
2692     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2693 }
2694 
2695 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){
2696     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2697 }
2698 
2699 /**
2700  * @brief -> gatt complete event
2701  */
2702 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){
2703     gatt_client_t * gatt_client;
2704     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2705     if (status != ERROR_CODE_SUCCESS){
2706         return status;
2707     }
2708 
2709     gatt_client->callback = callback;
2710     gatt_client->attribute_handle = attribute_handle;
2711     gatt_client->attribute_length = value_length;
2712     gatt_client->attribute_offset = offset;
2713     gatt_client->attribute_value = value;
2714     gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
2715     gatt_client_run();
2716     return ERROR_CODE_SUCCESS;
2717 }
2718 
2719 /**
2720  * @brief -> gatt complete event
2721  */
2722 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2723     gatt_client_t * gatt_client;
2724     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2725     if (status != ERROR_CODE_SUCCESS){
2726         return status;
2727     }
2728 
2729     gatt_client->callback = callback;
2730     gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
2731     gatt_client_run();
2732     return ERROR_CODE_SUCCESS;
2733 }
2734 
2735 /**
2736  * @brief -> gatt complete event
2737  */
2738 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2739     gatt_client_t * gatt_client;
2740     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2741     if (status != ERROR_CODE_SUCCESS){
2742         return status;
2743     }
2744 
2745     gatt_client->callback = callback;
2746     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
2747     gatt_client_run();
2748     return ERROR_CODE_SUCCESS;
2749 }
2750 
2751 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
2752     service->start_group_handle = little_endian_read_16(packet, offset);
2753     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2754     reverse_128(&packet[offset + 4], service->uuid128);
2755     if (uuid_has_bluetooth_prefix(service->uuid128)){
2756         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2757     } else {
2758         service->uuid16 = 0;
2759     }
2760 }
2761 
2762 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2763     characteristic->start_handle = little_endian_read_16(packet, offset);
2764     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2765     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2766     characteristic->properties = little_endian_read_16(packet, offset + 6);
2767     reverse_128(&packet[offset+8], characteristic->uuid128);
2768     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2769         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2770     } else {
2771         characteristic->uuid16 = 0;
2772     }
2773 }
2774 
2775 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2776     descriptor->handle = little_endian_read_16(packet, offset);
2777     reverse_128(&packet[offset+2], descriptor->uuid128);
2778     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2779         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2780     } else {
2781         descriptor->uuid16 = 0;
2782     }
2783 }
2784 
2785 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2786     gatt_client_t * gatt_client;
2787     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2788     if (status != ERROR_CODE_SUCCESS){
2789         return;
2790     }
2791     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2792         gatt_client->callback = callback;
2793         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
2794         gatt_client_run();
2795     }
2796 }
2797 
2798 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2799     gatt_client_t * gatt_client;
2800     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2801     if (status != ERROR_CODE_SUCCESS){
2802         return status;
2803     }
2804     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
2805     if (added == false){
2806         return ERROR_CODE_COMMAND_DISALLOWED;
2807     } else {
2808         att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2809         return ERROR_CODE_SUCCESS;
2810     }
2811 }
2812 
2813 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2814     gatt_client_t * gatt_client;
2815     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2816     if (status != ERROR_CODE_SUCCESS){
2817         return status;
2818     }
2819     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
2820     if (added == false){
2821         return ERROR_CODE_COMMAND_DISALLOWED;
2822     } else {
2823         gatt_client_notify_can_send_query(gatt_client);
2824         return ERROR_CODE_SUCCESS;
2825     }
2826 }
2827 
2828 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2829     gatt_client_t * gatt_client;
2830     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2831     if (status != ERROR_CODE_SUCCESS){
2832         return status;
2833     }
2834     if (gatt_client->write_without_response_callback != NULL){
2835         return GATT_CLIENT_IN_WRONG_STATE;
2836     }
2837     gatt_client->write_without_response_callback = callback;
2838     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2839     return ERROR_CODE_SUCCESS;
2840 }
2841 
2842 
2843 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined(ENABLE_GATT_OVER_EATT)
2844 
2845 #include "hci_event.h"
2846 
2847 static const hci_event_t gatt_client_connected = {
2848         GATT_EVENT_CONNECTED, 0, "1BH"
2849 };
2850 
2851 static const hci_event_t gatt_client_disconnected = {
2852         GATT_EVENT_DISCONNECTED, 0, "H"
2853 };
2854 
2855 static void gatt_client_emit_connected(btstack_packet_handler_t callback, uint8_t status, bd_addr_t addr,
2856                                        hci_con_handle_t con_handle) {
2857     uint8_t buffer[20];
2858     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr, con_handle);
2859     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2860 }
2861 
2862 #endif
2863 
2864 #ifdef ENABLE_GATT_OVER_CLASSIC
2865 
2866 #include "bluetooth_psm.h"
2867 
2868 // single active SDP query
2869 static gatt_client_t * gatt_client_classic_active_sdp_query;
2870 
2871 // macos protocol descriptor list requires 16 bytes
2872 static uint8_t gatt_client_classic_sdp_buffer[32];
2873 
2874 
2875 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
2876     btstack_linked_item_t *it;
2877     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2878         gatt_client_t * gatt_client = (gatt_client_t *) it;
2879         if (memcmp(gatt_client->addr, addr, 6) == 0){
2880             return gatt_client;
2881         }
2882     }
2883     return NULL;
2884 }
2885 
2886 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
2887     btstack_linked_item_t *it;
2888     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2889         gatt_client_t * gatt_client = (gatt_client_t *) it;
2890         if (gatt_client->l2cap_cid == l2cap_cid){
2891             return gatt_client;
2892         }
2893     }
2894     return NULL;
2895 }
2896 
2897 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
2898     bd_addr_t addr;
2899     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
2900     memcpy(addr, gatt_client->addr, 6);
2901     hci_con_handle_t con_handle = gatt_client->con_handle;
2902     btstack_packet_handler_t callback = gatt_client->callback;
2903     if (status != ERROR_CODE_SUCCESS){
2904         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2905         btstack_memory_gatt_client_free(gatt_client);
2906     }
2907     gatt_client_emit_connected(callback, status, addr, con_handle);
2908 }
2909 
2910 static void gatt_client_classic_retry(btstack_timer_source_t * ts){
2911     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
2912     if (gatt_client != NULL){
2913         gatt_client->state = P_W4_L2CAP_CONNECTION;
2914         att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
2915     }
2916 }
2917 
2918 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
2919 
2920     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
2921     gatt_client_timeout_stop(gatt_client);
2922 
2923     hci_con_handle_t con_handle = gatt_client->con_handle;
2924     btstack_packet_handler_t callback = gatt_client->callback;
2925     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2926     btstack_memory_gatt_client_free(gatt_client);
2927 
2928     uint8_t buffer[20];
2929     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
2930     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2931 }
2932 
2933 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
2934     des_iterator_t des_list_it;
2935     des_iterator_t prot_it;
2936 
2937     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
2938         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
2939         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
2940             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
2941                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
2942                     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)) {
2943                         uint8_t       *des_element;
2944                         uint8_t       *element;
2945                         uint32_t       uuid;
2946 
2947                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
2948 
2949                         des_element = des_iterator_get_element(&des_list_it);
2950                         des_iterator_init(&prot_it, des_element);
2951                         element = des_iterator_get_element(&prot_it);
2952 
2953                         if (de_get_element_type(element) != DE_UUID) continue;
2954 
2955                         uuid = de_get_uuid32(element);
2956                         des_iterator_next(&prot_it);
2957                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
2958                         switch (uuid){
2959                             case BLUETOOTH_PROTOCOL_L2CAP:
2960                                 if (!des_iterator_has_more(&prot_it)) continue;
2961                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
2962                                 break;
2963                             default:
2964                                 break;
2965                         }
2966                     }
2967                     break;
2968 
2969                 default:
2970                     break;
2971             }
2972         }
2973     }
2974 }
2975 
2976 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2977     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
2978     btstack_assert(gatt_client != NULL);
2979     uint8_t status;
2980 
2981     // TODO: handle sdp events, get l2cap psm
2982     switch (hci_event_packet_get_type(packet)){
2983         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
2984             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
2985             // TODO:
2986             return;
2987         case SDP_EVENT_QUERY_COMPLETE:
2988             status = sdp_event_query_complete_get_status(packet);
2989             gatt_client_classic_active_sdp_query = NULL;
2990             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
2991             if (status != ERROR_CODE_SUCCESS) break;
2992             if (gatt_client->l2cap_psm == 0) {
2993                 status = SDP_SERVICE_NOT_FOUND;
2994                 break;
2995             }
2996             break;
2997         default:
2998             btstack_assert(false);
2999             return;
3000     }
3001 
3002     // done
3003     if (status == ERROR_CODE_SUCCESS){
3004         gatt_client->state = P_W4_L2CAP_CONNECTION;
3005         status = att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3006     }
3007     if (status != ERROR_CODE_SUCCESS) {
3008         gatt_client_classic_handle_connected(gatt_client, status);
3009     }
3010 }
3011 
3012 static void gatt_client_classic_sdp_start(void * context){
3013     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
3014     gatt_client_classic_active_sdp_query->state = P_W4_SDP_QUERY;
3015     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3016 }
3017 
3018 static void gatt_client_classic_emit_connected(void * context){
3019     gatt_client_t * gatt_client = (gatt_client_t *) context;
3020     gatt_client->state = P_READY;
3021     hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3022     btstack_assert(hci_connection != NULL);
3023     gatt_client_emit_connected(gatt_client->callback, ERROR_CODE_SUCCESS, hci_connection->address, gatt_client->con_handle);
3024 }
3025 
3026 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
3027     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
3028     if (gatt_client != NULL){
3029         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
3030     }
3031     gatt_client = btstack_memory_gatt_client_get();
3032     if (gatt_client == NULL){
3033         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3034     }
3035     // init state
3036     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
3037     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
3038     memcpy(gatt_client->addr, addr, 6);
3039     gatt_client->mtu = ATT_DEFAULT_MTU;
3040     gatt_client->security_level = LEVEL_0;
3041     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3042     gatt_client->callback = callback;
3043 #ifdef ENABLE_GATT_OVER_EATT
3044     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3045 #endif
3046     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
3047 
3048     // schedule emitted event if already connected, otherwise
3049     bool already_connected = false;
3050     hci_connection_t * hci_connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3051     if (hci_connection != NULL){
3052         if (hci_connection->att_server.l2cap_cid != 0){
3053             already_connected = true;
3054         }
3055     }
3056     gatt_client->callback_request.context = gatt_client;
3057     if (already_connected){
3058         gatt_client->con_handle = hci_connection->con_handle;
3059         gatt_client->callback_request.callback = &gatt_client_classic_emit_connected;
3060         gatt_client->state = P_W2_EMIT_CONNECTED;
3061         btstack_run_loop_execute_on_main_thread(&gatt_client->callback_request);
3062     } else {
3063         gatt_client->callback_request.callback = &gatt_client_classic_sdp_start;
3064         gatt_client->state = P_W2_SDP_QUERY;
3065         sdp_client_register_query_callback(&gatt_client->callback_request);
3066     }
3067     return ERROR_CODE_SUCCESS;
3068 }
3069 
3070 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3071     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
3072     if (gatt_client == NULL){
3073         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3074     }
3075     gatt_client->callback = callback;
3076     return l2cap_disconnect(gatt_client->l2cap_cid);
3077 }
3078 #endif
3079 
3080 #ifdef ENABLE_GATT_OVER_EATT
3081 
3082 #define MAX_NR_EATT_CHANNELS 5
3083 
3084 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
3085 
3086 static void gatt_client_eatt_finalize(gatt_client_t * gatt_client) {
3087     // free eatt clients
3088     btstack_linked_list_iterator_t it;
3089     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3090     while (btstack_linked_list_iterator_has_next(&it)) {
3091         gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3092         btstack_linked_list_iterator_remove(&it);
3093         btstack_memory_gatt_client_free(eatt_client);
3094     }
3095 }
3096 
3097 // all channels connected
3098 static void gatt_client_le_enhanced_handle_connected(gatt_client_t * gatt_client, uint8_t status) {
3099     if (status == ERROR_CODE_SUCCESS){
3100         gatt_client->eatt_state = GATT_CLIENT_EATT_READY;
3101     } else {
3102         gatt_client_eatt_finalize(gatt_client);
3103         gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3104     }
3105 
3106     gatt_client_emit_connected(gatt_client->callback, status,  gatt_client->addr, gatt_client->con_handle);
3107 }
3108 
3109 // single channel disconnected
3110 static void gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client_t * gatt_client, gatt_client_t * eatt_client) {
3111     if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY) {
3112 
3113         // report error
3114         gatt_client_report_error_if_pending(eatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3115 
3116         // free memory
3117         btstack_linked_list_remove(&gatt_client->eatt_clients, (btstack_linked_item_t *) eatt_client);
3118         btstack_memory_gatt_client_free(eatt_client);
3119 
3120         // report disconnected if last channel closed
3121         if (btstack_linked_list_empty(&gatt_client->eatt_clients)){
3122             // emit disconnected when last eatt client is gone
3123             uint8_t buffer[20];
3124             uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, gatt_client->con_handle);
3125             (*gatt_client->callback)(HCI_EVENT_PACKET, 0, buffer, len);
3126         }
3127     }
3128 }
3129 
3130 static gatt_client_t * gatt_client_le_enhanced_get_context_for_l2cap_cid(uint16_t l2cap_cid, gatt_client_t ** out_eatt_client){
3131     btstack_linked_list_iterator_t it;
3132     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3133     while (btstack_linked_list_iterator_has_next(&it)) {
3134         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3135         btstack_linked_list_iterator_t it2;
3136         btstack_linked_list_iterator_init(&it2, &gatt_client->eatt_clients);
3137         while (btstack_linked_list_iterator_has_next(&it2)) {
3138             gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it2);
3139             if (eatt_client->l2cap_cid == l2cap_cid){
3140                 *out_eatt_client = eatt_client;
3141                 return gatt_client;
3142             }
3143         }
3144     }
3145     return NULL;
3146 }
3147 
3148 static void gatt_client_le_enhanced_setup_l2cap_channel(gatt_client_t * gatt_client){
3149     uint8_t num_channels = gatt_client->eatt_num_clients;
3150 
3151     // setup channels
3152     uint16_t buffer_size_per_client = gatt_client->eatt_storage_size / num_channels;
3153     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3154     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
3155     uint16_t  new_cids[MAX_NR_EATT_CHANNELS];
3156     memset(gatt_client->eatt_storage_buffer, 0, gatt_client->eatt_storage_size);
3157     uint8_t i;
3158     for (i=0;i<gatt_client->eatt_num_clients; i++){
3159         receive_buffers[i] = &gatt_client->eatt_storage_buffer[REPORT_PREBUFFER_HEADER];
3160         gatt_client->eatt_storage_buffer += REPORT_PREBUFFER_HEADER + max_mtu;
3161     }
3162 
3163     log_info("%u EATT clients with receive buffer size %u", gatt_client->eatt_num_clients, buffer_size_per_client);
3164 
3165     uint8_t status = l2cap_ecbm_create_channels(&gatt_client_le_enhanced_packet_handler,
3166                                                 gatt_client->con_handle,
3167                                                 gatt_client->security_level,
3168                                                 BLUETOOTH_PSM_EATT, num_channels,
3169                                                 L2CAP_LE_AUTOMATIC_CREDITS,
3170                                                 buffer_size_per_client,
3171                                                 receive_buffers,
3172                                                 new_cids);
3173 
3174     if (status == ERROR_CODE_SUCCESS){
3175         i = 0;
3176         btstack_linked_list_iterator_t it;
3177         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3178         while (btstack_linked_list_iterator_has_next(&it)) {
3179             gatt_client_t *new_eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3180 
3181             // init state with new cid and transmit buffer
3182             new_eatt_client->bearer_type = ATT_BEARER_ENHANCED_LE;
3183             new_eatt_client->con_handle = gatt_client->con_handle;
3184             new_eatt_client->mtu = 64;
3185             new_eatt_client->security_level = LEVEL_0;
3186             new_eatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3187             new_eatt_client->state = P_W4_L2CAP_CONNECTION;
3188             new_eatt_client->l2cap_cid = new_cids[i];
3189             new_eatt_client->eatt_storage_buffer = gatt_client->eatt_storage_buffer;
3190             gatt_client->eatt_storage_buffer += max_mtu;
3191             i++;
3192         }
3193         gatt_client->eatt_state = GATT_CLIENT_EATT_L2CAP_SETUP;
3194     } else {
3195         gatt_client_le_enhanced_handle_connected(gatt_client, status);
3196     }
3197 }
3198 
3199 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
3200     gatt_client_t *gatt_client;
3201     gatt_client_t *eatt_client;
3202     hci_con_handle_t con_handle;
3203     uint16_t l2cap_cid;
3204     uint8_t status;
3205     gatt_client_characteristic_t characteristic;
3206     gatt_client_service_t service;
3207     switch (packet_type) {
3208         case HCI_EVENT_PACKET:
3209             switch (hci_event_packet_get_type(packet)) {
3210                 case GATT_EVENT_SERVICE_QUERY_RESULT:
3211                     con_handle = gatt_event_service_query_result_get_handle(packet);
3212                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3213                     btstack_assert(gatt_client != NULL);
3214                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE);
3215                     gatt_event_service_query_result_get_service(packet, &service);
3216                     gatt_client->gatt_service_start_group_handle = service.start_group_handle;
3217                     gatt_client->gatt_service_end_group_handle = service.end_group_handle;
3218                     break;
3219                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
3220                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
3221                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3222                     btstack_assert(gatt_client != NULL);
3223                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE);
3224                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
3225                         gatt_client->gatt_server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
3226                     }
3227                     break;
3228                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
3229                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
3230                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3231                     btstack_assert(gatt_client != NULL);
3232                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE);
3233                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
3234                     gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
3235                     break;
3236                 case GATT_EVENT_QUERY_COMPLETE:
3237                     con_handle = gatt_event_query_complete_get_handle(packet);
3238                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3239                     btstack_assert(gatt_client != NULL);
3240                     switch (gatt_client->eatt_state){
3241                         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE:
3242                             if (gatt_client->gatt_service_start_group_handle == 0){
3243                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3244                             } else {
3245                                 gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
3246                             }
3247                             break;
3248                         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE:
3249                             if ((gatt_client->gatt_server_supported_features & 1) == 0) {
3250                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3251                             } else {
3252                                 gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND;
3253                             }
3254                             break;
3255                         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE:
3256                             if (gatt_client->gatt_client_supported_features_handle == 0){
3257                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3258                             } else {
3259                                 gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
3260                             }
3261                             break;
3262                         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE:
3263                             gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3264                             break;
3265                         default:
3266                             break;
3267                     }
3268                     break;
3269                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
3270                     l2cap_cid = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
3271                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3272 
3273                     btstack_assert(gatt_client != NULL);
3274                     btstack_assert(eatt_client != NULL);
3275                     btstack_assert(eatt_client->state == P_W4_L2CAP_CONNECTION);
3276 
3277                     status = l2cap_event_channel_opened_get_status(packet);
3278                     if (status == ERROR_CODE_SUCCESS){
3279                         eatt_client->state = P_READY;
3280                         eatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
3281                     } else {
3282                         gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3283                     }
3284                     // all channels opened?
3285                     gatt_client->eatt_num_clients--;
3286                     if (gatt_client->eatt_num_clients == 0){
3287                         gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_SUCCESS);
3288                     }
3289                     break;
3290                 case L2CAP_EVENT_CHANNEL_CLOSED:
3291                     l2cap_cid = l2cap_event_channel_closed_get_local_cid(packet);
3292                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3293                     btstack_assert(gatt_client != NULL);
3294                     btstack_assert(eatt_client != NULL);
3295                     gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3296                     break;
3297                 default:
3298                     break;
3299             }
3300             break;
3301         case L2CAP_DATA_PACKET:
3302             gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(channel, &eatt_client);
3303             btstack_assert(gatt_client != NULL);
3304             btstack_assert(eatt_client != NULL);
3305             gatt_client_handle_att_response(eatt_client, packet, size);
3306             gatt_client_run();
3307             break;
3308         default:
3309             break;
3310     }
3311 }
3312 
3313 static bool gatt_client_le_enhanced_handle_can_send_query(gatt_client_t * gatt_client){
3314     uint8_t status = ERROR_CODE_SUCCESS;
3315     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
3316     switch (gatt_client->eatt_state){
3317         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND:
3318             gatt_client->gatt_service_start_group_handle = 0;
3319             gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE;
3320             status = gatt_client_discover_primary_services_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3321                                                                      gatt_client->con_handle,
3322                                                                      ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3323             break;
3324         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
3325             gatt_client->gatt_server_supported_features = 0;
3326             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
3327             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3328                                                                          gatt_client->con_handle,
3329                                                                          gatt_client->gatt_service_start_group_handle,
3330                                                                          gatt_client->gatt_service_end_group_handle,
3331                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
3332             return true;
3333         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
3334             gatt_client->gatt_client_supported_features_handle = 0;
3335             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE;
3336             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3337                                                                                      gatt_client->con_handle,
3338                                                                                      gatt_client->gatt_service_start_group_handle,
3339                                                                                      gatt_client->gatt_service_end_group_handle,
3340                                                                                      ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
3341             return true;
3342         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
3343             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
3344             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
3345                                                                gatt_client->gatt_client_supported_features_handle, 1,
3346                                                                &gatt_client_supported_features);
3347             return true;
3348         default:
3349             break;
3350     }
3351     btstack_assert(status == ERROR_CODE_SUCCESS);
3352     UNUSED(status);
3353     return false;
3354 }
3355 
3356 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) {
3357     gatt_client_t * gatt_client;
3358     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3359     if (status != ERROR_CODE_SUCCESS){
3360         return status;
3361     }
3362 
3363     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
3364         return ERROR_CODE_COMMAND_DISALLOWED;
3365     }
3366 
3367     // need one buffer for sending and one for receiving. Receiving includes pre-buffer for reports
3368     uint16_t buffer_size_per_client = storage_size / num_channels;
3369     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3370     if (max_mtu < 64) {
3371         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3372     }
3373 
3374     if ((num_channels == 0) || (num_channels > MAX_NR_EATT_CHANNELS)){
3375         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3376     }
3377 
3378     // create max num_channel eatt clients
3379     uint8_t i;
3380     btstack_linked_list_t eatt_clients = NULL;
3381     for (i=0;i<num_channels;i++) {
3382         gatt_client_t * new_gatt_client = btstack_memory_gatt_client_get();
3383         if (new_gatt_client == NULL) {
3384             break;
3385         }
3386         btstack_linked_list_add(&eatt_clients, (btstack_linked_item_t*)new_gatt_client);
3387     }
3388 
3389     if (i != num_channels){
3390         while (true){
3391             gatt_client = (gatt_client_t *) btstack_linked_list_pop(&eatt_clients);
3392             if (gatt_client == NULL) {
3393                 break;
3394             }
3395             btstack_memory_gatt_client_free(gatt_client);
3396         }
3397         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3398     }
3399 
3400     gatt_client->callback = callback;
3401     gatt_client->eatt_num_clients   = num_channels;
3402     gatt_client->eatt_storage_buffer = storage_buffer;
3403     gatt_client->eatt_storage_size   = storage_size;
3404     gatt_client->eatt_clients = eatt_clients;
3405     gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND;
3406     gatt_client_notify_can_send_query(gatt_client);
3407 
3408     return ERROR_CODE_SUCCESS;
3409 }
3410 
3411 #endif
3412 
3413 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3414 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3415     gatt_client_att_packet_handler(packet_type, handle, packet, size);
3416 }
3417 
3418 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
3419     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
3420     return status;
3421 }
3422 #endif
3423