xref: /btstack/src/classic/hid_host.c (revision e8b7768f4320b89e088aeff6b8ffd5c9b51f3338)
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__ "hid_host.c"
39 
40 #include <string.h>
41 
42 #include "bluetooth.h"
43 #include "bluetooth_psm.h"
44 #include "bluetooth_sdp.h"
45 #include "btstack_debug.h"
46 #include "btstack_event.h"
47 #include "btstack_hid.h"
48 #include "btstack_hid_parser.h"
49 #include "btstack_memory.h"
50 #include "l2cap.h"
51 
52 #include "classic/hid_host.h"
53 #include "classic/sdp_util.h"
54 #include "classic/sdp_client.h"
55 
56 #define MAX_ATTRIBUTE_VALUE_SIZE 300
57 
58 #define CONTROL_MESSAGE_BITMASK_SUSPEND             1
59 #define CONTROL_MESSAGE_BITMASK_EXIT_SUSPEND        2
60 #define CONTROL_MESSAGE_BITMASK_VIRTUAL_CABLE_UNPLUG 4
61 
62 // globals
63 
64 // higher-layer callbacks
65 static btstack_packet_handler_t hid_host_callback;
66 
67 // descriptor storage
68 static uint8_t * hid_host_descriptor_storage;
69 static uint16_t  hid_host_descriptor_storage_len;
70 
71 // SDP
72 static uint8_t            hid_host_sdp_attribute_value[MAX_ATTRIBUTE_VALUE_SIZE];
73 static const unsigned int hid_host_sdp_attribute_value_buffer_size = MAX_ATTRIBUTE_VALUE_SIZE;
74 static uint16_t           hid_host_sdp_context_control_cid = 0;
75 
76 // connections
77 static btstack_linked_list_t hid_host_connections;
78 static uint16_t              hid_host_cid_counter = 0;
79 
80 // lower layer callbacks
81 static btstack_context_callback_registration_t hid_host_handle_sdp_client_query_request;
82 
83 // prototypes
84 
85 static void hid_host_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
86 static void hid_host_handle_start_sdp_client_query(void * context);
87 
88 static uint16_t hid_descriptor_storage_get_available_space(void){
89     // assumes all descriptors are back to back
90     uint16_t free_space = hid_host_descriptor_storage_len;
91 
92     btstack_linked_list_iterator_t it;
93     btstack_linked_list_iterator_init(&it, &hid_host_connections);
94     while (btstack_linked_list_iterator_has_next(&it)){
95         hid_host_connection_t * connection = (hid_host_connection_t *)btstack_linked_list_iterator_next(&it);
96         free_space -= connection->hid_descriptor_len;
97     }
98     return free_space;
99 }
100 
101 static hid_host_connection_t * hid_host_get_connection_for_hid_cid(uint16_t hid_cid){
102     btstack_linked_list_iterator_t it;
103     btstack_linked_list_iterator_init(&it, &hid_host_connections);
104     while (btstack_linked_list_iterator_has_next(&it)){
105         hid_host_connection_t * connection = (hid_host_connection_t *)btstack_linked_list_iterator_next(&it);
106         if (connection->hid_cid != hid_cid) continue;
107         return connection;
108     }
109     return NULL;
110 }
111 
112 static hid_host_connection_t * hid_host_get_connection_for_l2cap_cid(uint16_t l2cap_cid){
113     btstack_linked_list_iterator_t it;
114     btstack_linked_list_iterator_init(&it, &hid_host_connections);
115     while (btstack_linked_list_iterator_has_next(&it)){
116         hid_host_connection_t * connection = (hid_host_connection_t *)btstack_linked_list_iterator_next(&it);
117         if ((connection->interrupt_cid != l2cap_cid) && (connection->control_cid != l2cap_cid)) continue;
118         return connection;
119     }
120     return NULL;
121 }
122 
123 static void hid_descriptor_storage_init(hid_host_connection_t * connection){
124     // reserve remaining space for this connection
125     uint16_t available_space = hid_descriptor_storage_get_available_space();
126     connection->hid_descriptor_len = 0;
127     connection->hid_descriptor_max_len = available_space;
128     connection->hid_descriptor_offset  = hid_host_descriptor_storage_len - available_space;
129 }
130 
131 static bool hid_descriptor_storage_store(hid_host_connection_t * connection, uint8_t byte){
132     // store single hid descriptor byte
133     if (connection->hid_descriptor_len >= connection->hid_descriptor_max_len) return false;
134 
135     hid_host_descriptor_storage[connection->hid_descriptor_offset + connection->hid_descriptor_len] = byte;
136     connection->hid_descriptor_len++;
137     return true;
138 }
139 
140 static void hid_descriptor_storage_delete(hid_host_connection_t * connection){
141     uint16_t descriptor_len = connection->hid_descriptor_len;
142 
143     if (descriptor_len > 0){
144         uint16_t next_offset = connection->hid_descriptor_offset + connection->hid_descriptor_len;
145 
146         // move higher descriptors down
147         memmove(&hid_host_descriptor_storage[connection->hid_descriptor_offset],
148                 &hid_host_descriptor_storage[next_offset],
149                 hid_host_descriptor_storage_len - next_offset);
150 
151         // fix descriptor offset of higher descriptors
152         btstack_linked_list_iterator_t it;
153         btstack_linked_list_iterator_init(&it, &hid_host_connections);
154         while (btstack_linked_list_iterator_has_next(&it)){
155             hid_host_connection_t * conn = (hid_host_connection_t *)btstack_linked_list_iterator_next(&it);
156             if (conn == connection) continue;
157             if (conn->hid_descriptor_offset >= next_offset){
158                 conn->hid_descriptor_offset -= descriptor_len;
159             }
160         }
161     }
162 
163     // clear descriptor
164     connection->hid_descriptor_len = 0;
165     connection->hid_descriptor_offset = 0;
166 }
167 
168 const uint8_t * hid_descriptor_storage_get_descriptor_data(uint16_t hid_cid){
169     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
170     if (!connection){
171         return NULL;
172     }
173     return &hid_host_descriptor_storage[connection->hid_descriptor_offset];
174 }
175 
176 uint16_t hid_descriptor_storage_get_descriptor_len(uint16_t hid_cid){
177     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
178     if (!connection){
179         return 0;
180     }
181     return connection->hid_descriptor_len;
182 }
183 
184 
185 // HID Util
186 static void hid_emit_connected_event(hid_host_connection_t * connection, uint8_t status){
187     uint8_t event[15];
188     uint16_t pos = 0;
189     event[pos++] = HCI_EVENT_HID_META;
190     pos++;  // skip len
191     event[pos++] = HID_SUBEVENT_CONNECTION_OPENED;
192     little_endian_store_16(event, pos, connection->hid_cid);
193     pos+=2;
194     event[pos++] = status;
195     reverse_bd_addr(connection->remote_addr, &event[pos]);
196     pos += 6;
197     little_endian_store_16(event,pos,connection->con_handle);
198     pos += 2;
199     event[pos++] = connection->incoming;
200     event[1] = pos - 2;
201     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, &event[0], pos);
202 }
203 
204 static void hid_emit_descriptor_available_event(hid_host_connection_t * connection){
205     uint8_t event[6];
206     uint16_t pos = 0;
207     event[pos++] = HCI_EVENT_HID_META;
208     pos++;  // skip len
209     event[pos++] = HID_SUBEVENT_DESCRIPTOR_AVAILABLE;
210     little_endian_store_16(event,pos,connection->hid_cid);
211     pos += 2;
212     event[pos++] = connection->hid_descriptor_status;
213     event[1] = pos - 2;
214     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, &event[0], pos);
215 }
216 
217 static void hid_emit_sniff_params_event(hid_host_connection_t * connection){
218     uint8_t event[9];
219     uint16_t pos = 0;
220     event[pos++] = HCI_EVENT_HID_META;
221     pos++;  // skip len
222     event[pos++] = HID_SUBEVENT_SNIFF_SUBRATING_PARAMS;
223     little_endian_store_16(event,pos,connection->hid_cid);
224     pos += 2;
225     little_endian_store_16(event,pos,connection->host_max_latency);
226     pos += 2;
227     little_endian_store_16(event,pos,connection->host_min_timeout);
228     pos += 2;
229 
230     event[1] = pos - 2;
231     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, &event[0], pos);
232 }
233 
234 static void hid_emit_event(hid_host_connection_t * connection, uint8_t subevent_type){
235     uint8_t event[5];
236     uint16_t pos = 0;
237     event[pos++] = HCI_EVENT_HID_META;
238     pos++;  // skip len
239     event[pos++] = subevent_type;
240     little_endian_store_16(event,pos,connection->hid_cid);
241     pos += 2;
242     event[1] = pos - 2;
243     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, &event[0], pos);
244 }
245 
246 static void hid_emit_event_with_status(hid_host_connection_t * connection, uint8_t subevent_type, hid_handshake_param_type_t status){
247     uint8_t event[6];
248     uint16_t pos = 0;
249     event[pos++] = HCI_EVENT_HID_META;
250     pos++;  // skip len
251     event[pos++] = subevent_type;
252     little_endian_store_16(event,pos,connection->hid_cid);
253     pos += 2;
254     event[pos++] = status;
255     event[1] = pos - 2;
256     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, &event[0], pos);
257 }
258 
259 static void hid_emit_set_protocol_response_event(hid_host_connection_t * connection, hid_handshake_param_type_t status){
260     uint8_t event[7];
261     uint16_t pos = 0;
262     event[pos++] = HCI_EVENT_HID_META;
263     pos++;  // skip len
264     event[pos++] = HID_SUBEVENT_SET_PROTOCOL_RESPONSE;
265     little_endian_store_16(event,pos,connection->hid_cid);
266     pos += 2;
267     event[pos++] = status;
268     event[pos++] = connection->protocol_mode;
269     event[1] = pos - 2;
270     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, &event[0], pos);
271 }
272 
273 static void hid_emit_incoming_connection_event(hid_host_connection_t * connection){
274     uint8_t event[13];
275     uint16_t pos = 0;
276     event[pos++] = HCI_EVENT_HID_META;
277     pos++;  // skip len
278     event[pos++] = HID_SUBEVENT_INCOMING_CONNECTION;
279     little_endian_store_16(event, pos, connection->hid_cid);
280     pos += 2;
281     reverse_bd_addr(connection->remote_addr, &event[pos]);
282     pos += 6;
283     little_endian_store_16(event,pos,connection->con_handle);
284     pos += 2;
285     event[1] = pos - 2;
286     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, &event[0], pos);
287 }
288 
289 // setup get report response event - potentially in-place of original l2cap packet
290 static void hid_setup_get_report_event(hid_host_connection_t * connection, hid_handshake_param_type_t status, uint8_t *buffer, uint16_t report_len){
291     uint16_t pos = 0;
292     buffer[pos++] = HCI_EVENT_HID_META;
293     pos++;  // skip len
294     buffer[pos++] = HID_SUBEVENT_GET_REPORT_RESPONSE;
295     little_endian_store_16(buffer, pos, connection->hid_cid);
296     pos += 2;
297     buffer[pos++] = (uint8_t) status;
298     little_endian_store_16(buffer, pos, report_len);
299     pos += 2;
300     buffer[1] = pos + report_len - 2;
301 }
302 
303 // setup report event - potentially in-place of original l2cap packet
304 static void hid_setup_report_event(hid_host_connection_t * connection, uint8_t *buffer, uint16_t report_len){
305     uint16_t pos = 0;
306     buffer[pos++] = HCI_EVENT_HID_META;
307     pos++;  // skip len
308     buffer[pos++] = HID_SUBEVENT_REPORT;
309     little_endian_store_16(buffer, pos, connection->hid_cid);
310     pos += 2;
311     little_endian_store_16(buffer, pos, report_len);
312     pos += 2;
313     buffer[1] = pos + report_len - 2;
314 }
315 
316 
317 static void hid_emit_get_protocol_event(hid_host_connection_t * connection, hid_handshake_param_type_t status, hid_protocol_mode_t protocol_mode){
318     uint8_t event[7];
319     uint16_t pos = 0;
320     event[pos++] = HCI_EVENT_HID_META;
321     pos++;  // skip len
322     event[pos++] = HID_SUBEVENT_GET_PROTOCOL_RESPONSE;
323     little_endian_store_16(event,pos,connection->hid_cid);
324     pos += 2;
325     event[pos++] = status;
326     event[pos++] = protocol_mode;
327     event[1] = pos - 2;
328     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, &event[0], pos);
329 }
330 
331 // HID Host
332 
333 static uint16_t hid_host_get_next_cid(void){
334     if (hid_host_cid_counter == 0xffff) {
335         hid_host_cid_counter = 1;
336     } else {
337         hid_host_cid_counter++;
338     }
339     return hid_host_cid_counter;
340 }
341 
342 static hid_host_connection_t * hid_host_create_connection(bd_addr_t remote_addr){
343     hid_host_connection_t * connection = btstack_memory_hid_host_connection_get();
344     if (!connection){
345         log_error("Not enough memory to create connection");
346         return NULL;
347     }
348     connection->state = HID_HOST_IDLE;
349     connection->hid_cid = hid_host_get_next_cid();
350     connection->control_cid = 0;
351     connection->control_psm = 0;
352     connection->interrupt_cid = 0;
353     connection->interrupt_psm = 0;
354     connection->con_handle = HCI_CON_HANDLE_INVALID;
355 
356     (void)memcpy(connection->remote_addr, remote_addr, 6);
357     btstack_linked_list_add(&hid_host_connections, (btstack_linked_item_t *) connection);
358     return connection;
359 }
360 
361 static hid_host_connection_t * hid_host_get_connection_for_bd_addr(bd_addr_t addr){
362     btstack_linked_list_iterator_t it;
363     btstack_linked_list_iterator_init(&it, &hid_host_connections);
364     while (btstack_linked_list_iterator_has_next(&it)){
365         hid_host_connection_t * connection = (hid_host_connection_t *)btstack_linked_list_iterator_next(&it);
366         if (memcmp(addr, connection->remote_addr, 6) != 0) continue;
367         return connection;
368     }
369     return NULL;
370 }
371 
372 
373 static void hid_host_finalize_connection(hid_host_connection_t * connection){
374     uint16_t interrupt_cid = connection->interrupt_cid;
375     uint16_t control_cid = connection->control_cid;
376 
377     connection->interrupt_cid = 0;
378     connection->control_cid = 0;
379 
380     if (interrupt_cid != 0){
381         l2cap_disconnect(interrupt_cid);
382     }
383     if (control_cid != 0){
384         l2cap_disconnect(control_cid);
385     }
386     btstack_linked_list_remove(&hid_host_connections, (btstack_linked_item_t*) connection);
387     btstack_memory_hid_host_connection_free(connection);
388 }
389 
390 static void hid_host_handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
391     UNUSED(packet_type);
392     UNUSED(channel);
393     UNUSED(size);
394 
395     des_iterator_t attribute_list_it;
396     des_iterator_t additional_des_it;
397     des_iterator_t prot_it;
398     uint8_t       *des_element;
399     uint8_t       *element;
400     uint32_t       uuid;
401     uint8_t        status = ERROR_CODE_SUCCESS;
402     bool try_fallback_to_boot;
403     bool finalize_connection;
404 
405 
406     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_host_sdp_context_control_cid);
407     if (!connection) {
408         log_error("SDP query, connection with 0x%02x cid not found", hid_host_sdp_context_control_cid);
409         return;
410     }
411 
412     btstack_assert(connection->state == HID_HOST_W4_SDP_QUERY_RESULT);
413 
414     switch (hci_event_packet_get_type(packet)){
415         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
416 
417             if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= hid_host_sdp_attribute_value_buffer_size) {
418 
419                 hid_host_sdp_attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
420 
421                 if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
422                     switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
423 
424                         case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
425                             for (des_iterator_init(&attribute_list_it, hid_host_sdp_attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) {
426                                 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue;
427                                 des_element = des_iterator_get_element(&attribute_list_it);
428                                 des_iterator_init(&prot_it, des_element);
429                                 element = des_iterator_get_element(&prot_it);
430                                 if (de_get_element_type(element) != DE_UUID) continue;
431                                 uuid = de_get_uuid32(element);
432                                 switch (uuid){
433                                     case BLUETOOTH_PROTOCOL_L2CAP:
434                                         if (!des_iterator_has_more(&prot_it)) continue;
435                                         des_iterator_next(&prot_it);
436                                         de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->control_psm);
437                                         log_info("HID Control PSM: 0x%04x", connection->control_psm);
438                                         break;
439                                     default:
440                                         break;
441                                 }
442                             }
443                             break;
444                         case BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS:
445                             for (des_iterator_init(&attribute_list_it, hid_host_sdp_attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) {
446                                 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue;
447                                 des_element = des_iterator_get_element(&attribute_list_it);
448                                 for (des_iterator_init(&additional_des_it, des_element); des_iterator_has_more(&additional_des_it); des_iterator_next(&additional_des_it)) {
449                                     if (des_iterator_get_type(&additional_des_it) != DE_DES) continue;
450                                     des_element = des_iterator_get_element(&additional_des_it);
451                                     des_iterator_init(&prot_it, des_element);
452                                     element = des_iterator_get_element(&prot_it);
453                                     if (de_get_element_type(element) != DE_UUID) continue;
454                                     uuid = de_get_uuid32(element);
455                                     switch (uuid){
456                                         case BLUETOOTH_PROTOCOL_L2CAP:
457                                             if (!des_iterator_has_more(&prot_it)) continue;
458                                             des_iterator_next(&prot_it);
459                                             de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->interrupt_psm);
460                                             log_info("HID Interrupt PSM: 0x%04x", connection->interrupt_psm);
461                                             break;
462                                         default:
463                                             break;
464                                     }
465                                 }
466                             }
467                             break;
468 
469                         case BLUETOOTH_ATTRIBUTE_HID_DESCRIPTOR_LIST:
470                             for (des_iterator_init(&attribute_list_it, hid_host_sdp_attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) {
471                                 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue;
472                                 des_element = des_iterator_get_element(&attribute_list_it);
473                                 for (des_iterator_init(&additional_des_it, des_element); des_iterator_has_more(&additional_des_it); des_iterator_next(&additional_des_it)) {
474                                     if (des_iterator_get_type(&additional_des_it) != DE_STRING) continue;
475                                     element = des_iterator_get_element(&additional_des_it);
476 
477                                     const uint8_t * descriptor = de_get_string(element);
478                                     uint16_t descriptor_len = de_get_data_size(element);
479 
480                                     uint16_t i;
481                                     bool stored = false;
482 
483                                     connection->hid_descriptor_status = ERROR_CODE_SUCCESS;
484                                     for (i = 0; i < descriptor_len; i++){
485                                         stored = hid_descriptor_storage_store(connection, descriptor[i]);
486                                         if (!stored){
487                                             connection->hid_descriptor_status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
488                                             break;
489                                         }
490                                     }
491                                 }
492                             }
493                             break;
494 
495                         case BLUETOOTH_ATTRIBUTE_HIDSSR_HOST_MAX_LATENCY:
496                             if (de_get_element_type(hid_host_sdp_attribute_value) == DE_UINT) {
497                                 uint16_t host_max_latency;
498                                 if (de_element_get_uint16(hid_host_sdp_attribute_value, &host_max_latency) == 1){
499                                     connection->host_max_latency = host_max_latency;
500                                 } else {
501                                     connection->host_max_latency = 0xFFFF;
502                                 }
503                             }
504                             break;
505 
506                         case BLUETOOTH_ATTRIBUTE_HIDSSR_HOST_MIN_TIMEOUT:
507                             if (de_get_element_type(hid_host_sdp_attribute_value) == DE_UINT) {
508                                 uint16_t host_min_timeout;
509                                 if (de_element_get_uint16(hid_host_sdp_attribute_value, &host_min_timeout) == 1){
510                                     connection->host_min_timeout = host_min_timeout;
511                                 } else {
512                                     connection->host_min_timeout = 0xFFFF;
513                                 }
514                             }
515                             break;
516 
517                         default:
518                             break;
519                     }
520                 }
521             } else {
522                 log_error("SDP attribute value buffer size exceeded: available %d, required %d", hid_host_sdp_attribute_value_buffer_size, sdp_event_query_attribute_byte_get_attribute_length(packet));
523             }
524             break;
525 
526         case SDP_EVENT_QUERY_COMPLETE:
527             status = sdp_event_query_complete_get_status(packet);
528             try_fallback_to_boot = false;
529             finalize_connection = false;
530 
531             switch (status){
532                 // remote has SDP server
533                 case ERROR_CODE_SUCCESS:
534                     //  but no HID record
535                     if (!connection->control_psm || !connection->interrupt_psm) {
536                         status = ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
537                         if (connection->requested_protocol_mode == HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT){
538                             try_fallback_to_boot = true;
539                         } else {
540                             finalize_connection = true;
541                         }
542                         break;
543                     }
544                     // report mode possible
545                     break;
546 
547                 // SDP connection failed or remote does not have SDP server
548                 default:
549                     if (connection->requested_protocol_mode == HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT){
550                         try_fallback_to_boot = true;
551                     } else {
552                         finalize_connection = true;
553                     }
554                     break;
555             }
556 
557             if (finalize_connection){
558                 hid_host_sdp_context_control_cid = 0;
559                 hid_emit_connected_event(connection, status);
560                 hid_host_finalize_connection(connection);
561                 break;
562             }
563 
564             hid_emit_sniff_params_event(connection);
565 
566             if (try_fallback_to_boot){
567                 if (connection->incoming){
568                     connection->set_protocol = true;
569                     connection->state = HID_HOST_CONNECTION_ESTABLISHED;
570                     connection->requested_protocol_mode = HID_PROTOCOL_MODE_BOOT;
571                     hid_emit_descriptor_available_event(connection);
572                     l2cap_request_can_send_now_event(connection->control_cid);
573                 } else {
574                     connection->state = HID_HOST_W4_CONTROL_CONNECTION_ESTABLISHED;
575                     status = l2cap_create_channel(hid_host_packet_handler, connection->remote_addr, BLUETOOTH_PSM_HID_CONTROL, 0xffff, &connection->control_cid);
576                     if (status != ERROR_CODE_SUCCESS){
577                         hid_host_sdp_context_control_cid = 0;
578                         hid_emit_connected_event(connection, status);
579                         hid_host_finalize_connection(connection);
580                     }
581                 }
582                 break;
583             }
584 
585             // report mode possible
586             if (connection->incoming) {
587                 connection->set_protocol = true;
588                 connection->state = HID_HOST_CONNECTION_ESTABLISHED;
589                 connection->requested_protocol_mode = HID_PROTOCOL_MODE_REPORT;
590                 hid_emit_descriptor_available_event(connection);
591                 l2cap_request_can_send_now_event(connection->control_cid);
592             } else {
593                 connection->state = HID_HOST_W4_CONTROL_CONNECTION_ESTABLISHED;
594                 status = l2cap_create_channel(hid_host_packet_handler, connection->remote_addr, connection->control_psm, 0xffff, &connection->control_cid);
595                 if (status != ERROR_CODE_SUCCESS){
596                     hid_emit_connected_event(connection, status);
597                     hid_host_finalize_connection(connection);
598                 }
599             }
600             break;
601 
602         default:
603             break;
604     }
605 
606 }
607 
608 
609 static void hid_host_handle_control_packet(hid_host_connection_t * connection, uint8_t *packet, uint16_t size){
610     UNUSED(size);
611     uint8_t param;
612     hid_message_type_t         message_type;
613     hid_handshake_param_type_t message_status;
614     hid_protocol_mode_t        protocol_mode;
615 
616     uint8_t * in_place_event;
617     uint8_t status;
618 
619     message_type   = (hid_message_type_t)(packet[0] >> 4);
620     if (message_type == HID_MESSAGE_TYPE_HID_CONTROL){
621         param = packet[0] & 0x0F;
622         switch ((hid_control_param_t)param){
623             case HID_CONTROL_PARAM_VIRTUAL_CABLE_UNPLUG:
624                 hid_emit_event(connection, HID_SUBEVENT_VIRTUAL_CABLE_UNPLUG);
625                 hid_host_disconnect(connection->hid_cid);
626                 return;
627             default:
628                 break;
629         }
630     }
631 
632     message_status = (hid_handshake_param_type_t)(packet[0] & 0x0F);
633 
634     switch (connection->state){
635         case HID_HOST_CONNECTION_ESTABLISHED:
636             if (!connection->w4_set_protocol_response) break;
637             connection->w4_set_protocol_response = false;
638 
639             switch (message_status){
640                 case HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL:
641                     connection->protocol_mode = connection->requested_protocol_mode;
642                     break;
643                 default:
644                     break;
645             }
646             hid_emit_set_protocol_response_event(connection, message_status);
647             break;
648 
649         case HID_HOST_CONTROL_CONNECTION_ESTABLISHED:           // outgoing
650         case HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED:      // outgoing
651             if (!connection->w4_set_protocol_response) break;
652             connection->w4_set_protocol_response = false;
653 
654             switch (message_status){
655                 case HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL:
656                     // we are already connected, here it is only confirmed that we are in required protocol
657                     btstack_assert(connection->incoming == false);
658                     status = l2cap_create_channel(hid_host_packet_handler, connection->remote_addr, connection->interrupt_psm, 0xffff, &connection->interrupt_cid);
659                     if (status != ERROR_CODE_SUCCESS){
660                         log_info("HID Interrupt Connection failed: 0x%02x\n", status);
661                         hid_emit_connected_event(connection, status);
662                         hid_host_finalize_connection(connection);
663                         break;
664                     }
665                     connection->state = HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED;
666                     break;
667                 default:
668                     hid_emit_connected_event(connection, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
669                     hid_host_finalize_connection(connection);
670                     break;
671             }
672             break;
673 
674         case HID_HOST_W4_GET_REPORT_RESPONSE:
675             switch (message_type){
676                 case HID_MESSAGE_TYPE_HANDSHAKE:{
677                     uint8_t event[8];
678                     hid_setup_get_report_event(connection, message_status, event, 0);
679                     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, event, sizeof(event));
680                     break;
681                 }
682                 case HID_MESSAGE_TYPE_DATA:
683                     // reuse hci+l2cap header - max 8 byte (7 bytes + 1 bytes overwriting hid header)
684                     in_place_event = packet - 7;
685                     hid_setup_get_report_event(connection, HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL, in_place_event, size-1);
686                     hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, in_place_event, size + 7);
687                     break;
688                 default:
689                     break;
690             }
691             connection->state =  HID_HOST_CONNECTION_ESTABLISHED;
692             break;
693 
694         case HID_HOST_W4_SET_REPORT_RESPONSE:
695             hid_emit_event_with_status(connection, HID_SUBEVENT_SET_REPORT_RESPONSE, message_status);
696             connection->state =  HID_HOST_CONNECTION_ESTABLISHED;
697             break;
698 
699         case HID_HOST_W4_GET_PROTOCOL_RESPONSE:
700             protocol_mode = connection->protocol_mode;
701 
702             switch (message_type){
703                 case HID_MESSAGE_TYPE_DATA:
704                     protocol_mode = (hid_protocol_mode_t)packet[1];
705                     switch (protocol_mode){
706                         case HID_PROTOCOL_MODE_BOOT:
707                         case HID_PROTOCOL_MODE_REPORT:
708                             message_status = HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL;
709                             break;
710                         default:
711                             message_status = HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
712                             break;
713                     }
714                     break;
715                 default:
716                     break;
717             }
718             hid_emit_get_protocol_event(connection, message_status, protocol_mode);
719             connection->state =  HID_HOST_CONNECTION_ESTABLISHED;
720             break;
721 
722         default:
723             log_info("ignore invalid HID Control message");
724             connection->state =  HID_HOST_CONNECTION_ESTABLISHED;
725             break;
726     }
727 
728 }
729 
730 static void hid_host_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
731     UNUSED(channel);
732     UNUSED(size);
733 
734     uint8_t   event;
735     bd_addr_t address;
736     uint8_t   status;
737     uint16_t  l2cap_cid;
738     hid_host_connection_t * connection;
739 
740     switch (packet_type) {
741 
742         case L2CAP_DATA_PACKET:
743             connection = hid_host_get_connection_for_l2cap_cid(channel);
744             if (!connection) break;
745 
746             if (channel == connection->interrupt_cid){
747                 uint8_t * in_place_event = packet - 7;
748                 hid_setup_report_event(connection, in_place_event, size-1);
749                 hid_host_callback(HCI_EVENT_PACKET, connection->hid_cid, in_place_event, size + 7);
750                 break;
751             }
752 
753             if (channel == connection->control_cid){
754                 hid_host_handle_control_packet(connection, packet, size);
755                 break;
756             }
757             break;
758 
759         case HCI_EVENT_PACKET:
760             event = hci_event_packet_get_type(packet);
761             switch (event) {
762                 case L2CAP_EVENT_INCOMING_CONNECTION:
763                     l2cap_event_incoming_connection_get_address(packet, address);
764                     // connection should exist if psm == PSM_HID_INTERRUPT
765                     connection = hid_host_get_connection_for_bd_addr(address);
766 
767                     switch (l2cap_event_incoming_connection_get_psm(packet)){
768                         case PSM_HID_CONTROL:
769                             if (connection){
770                                 l2cap_decline_connection(channel);
771                                 break;
772                             }
773 
774                             connection = hid_host_create_connection(address);
775                             if (!connection){
776                                 log_error("Cannot create connection for %s", bd_addr_to_str(address));
777                                 l2cap_decline_connection(channel);
778                                 break;
779                             }
780 
781                             connection->state = HID_HOST_W4_CONTROL_CONNECTION_ESTABLISHED;
782                             connection->hid_descriptor_status = ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
783                             connection->con_handle = l2cap_event_incoming_connection_get_handle(packet);
784                             connection->control_cid = l2cap_event_incoming_connection_get_local_cid(packet);
785                             connection->incoming = true;
786 
787                             // emit connection request
788                             // user calls either hid_host_accept_connection or hid_host_decline_connection
789                             hid_emit_incoming_connection_event(connection);
790                             break;
791 
792                         case PSM_HID_INTERRUPT:
793                             if (!connection || (connection->state != HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED)){
794                                 log_error("Decline connection for %s", bd_addr_to_str(address));
795                                 l2cap_decline_connection(channel);
796                                 break;
797                             }
798 
799                             connection->state = HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED;
800                             connection->interrupt_cid = l2cap_event_incoming_connection_get_local_cid(packet);
801                             log_info("Accept connection on Interrupt channel %s", bd_addr_to_str(address));
802                             l2cap_accept_connection(channel);
803                             break;
804 
805                         default:
806                             log_info("Decline connection for %s", bd_addr_to_str(address));
807                             l2cap_decline_connection(channel);
808                             break;
809                     }
810                     break;
811 
812                 case L2CAP_EVENT_CHANNEL_OPENED:
813                     l2cap_event_channel_opened_get_address(packet, address);
814 
815                     connection = hid_host_get_connection_for_bd_addr(address);
816                     if (!connection){
817                         log_error("Connection does not exist %s", bd_addr_to_str(address));
818                         break;
819                     }
820 
821                     status = l2cap_event_channel_opened_get_status(packet);
822                     if (status != ERROR_CODE_SUCCESS){
823                         log_info("L2CAP connection %s failed: 0x%02xn", bd_addr_to_str(address), status);
824                         hid_emit_connected_event(connection, status);
825                         hid_host_finalize_connection(connection);
826                         break;
827                     }
828 
829                     // handle incoming connection:
830                     if (connection->incoming){
831                         switch (connection->state){
832                             case HID_HOST_W4_CONTROL_CONNECTION_ESTABLISHED:
833                                 // A Bluetooth HID Host or Bluetooth HID device shall always open both the control and Interrupt channels. (HID_v1.1.1, Chapter 5.2.2)
834                                 // We expect incomming interrupt connection from remote HID device
835                                 connection->state = HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED;
836                                 log_info("Incoming control connection opened: w4 interrupt");
837                                 break;
838 
839                             case HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED:
840                                 hid_emit_connected_event(connection, ERROR_CODE_SUCCESS);
841                                 connection->state = HID_HOST_CONNECTION_ESTABLISHED;
842 
843                                 switch (connection->requested_protocol_mode){
844                                     case HID_PROTOCOL_MODE_BOOT:
845                                         hid_emit_descriptor_available_event(connection);
846                                         connection->set_protocol = true;
847                                         l2cap_request_can_send_now_event(connection->control_cid);
848                                         log_info("Incoming interrupt connection opened: set boot mode");
849                                         break;
850                                     default:
851                                         // SDP query
852                                         log_info("Incoming interrupt connection opened: start SDP query");
853                                         connection->state = HID_HOST_W2_SEND_SDP_QUERY;
854                                         hid_host_handle_sdp_client_query_request.callback = &hid_host_handle_start_sdp_client_query;
855                                         (void) sdp_client_register_query_callback(&hid_host_handle_sdp_client_query_request);
856                                         break;
857                                 }
858                                 break;
859 
860                             default:
861                                 btstack_assert(false);
862                                 break;
863                         }
864                         break;
865                     }
866 
867                     // handle outgoing connection
868                     switch (connection->state){
869                         case HID_HOST_W4_CONTROL_CONNECTION_ESTABLISHED:
870                             log_info("Opened control connection, requested protocol mode %d\n", connection->requested_protocol_mode);
871                             connection->con_handle = l2cap_event_channel_opened_get_handle(packet);
872                             connection->state = HID_HOST_CONTROL_CONNECTION_ESTABLISHED;
873 
874                             switch (connection->requested_protocol_mode){
875                                 case HID_PROTOCOL_MODE_BOOT:
876                                 case HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT:
877                                     connection->set_protocol = true;
878                                     connection->interrupt_psm = BLUETOOTH_PSM_HID_INTERRUPT;
879                                     l2cap_request_can_send_now_event(connection->control_cid);
880                                     break;
881                                 default:
882                                     status = l2cap_create_channel(hid_host_packet_handler, address, connection->interrupt_psm, 0xffff, &connection->interrupt_cid);
883                                     if (status){
884                                         log_info("Connecting to HID Interrupt failed: 0x%02x", status);
885                                         hid_emit_connected_event(connection, status);
886                                         break;
887                                     }
888                                     connection->protocol_mode = connection->requested_protocol_mode;
889                                     connection->state = HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED;
890                                     break;
891                             }
892                             break;
893 
894                         case HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED:
895                             connection->state = HID_HOST_CONNECTION_ESTABLISHED;
896                             log_info("HID host connection established, cids: control 0x%02x, interrupt 0x%02x interrupt, hid 0x%02x",
897                                 connection->control_cid, connection->interrupt_cid, connection->hid_cid);
898                             hid_emit_connected_event(connection, ERROR_CODE_SUCCESS);
899                             hid_emit_descriptor_available_event(connection);
900                             break;
901 
902                         default:
903                             btstack_assert(false);
904                             break;
905                     }
906                     break;
907 
908                 case L2CAP_EVENT_CHANNEL_CLOSED:
909                     l2cap_cid  = l2cap_event_channel_closed_get_local_cid(packet);
910                     connection = hid_host_get_connection_for_l2cap_cid(l2cap_cid);
911                     if (!connection) return;
912 
913                     if (l2cap_cid == connection->interrupt_cid){
914                         connection->interrupt_cid = 0;
915                         if (connection->state == HID_HOST_W4_INTERRUPT_CONNECTION_DISCONNECTED){
916                             connection->state = HID_HOST_W4_CONTROL_CONNECTION_DISCONNECTED;
917                             l2cap_disconnect(connection->control_cid);
918                         }
919                         break;
920                     }
921 
922                     if (l2cap_cid == connection->control_cid){
923                         connection->control_cid = 0;
924                         hid_emit_event(connection, HID_SUBEVENT_CONNECTION_CLOSED);
925                         hid_descriptor_storage_delete(connection);
926                         hid_host_finalize_connection(connection);
927                         break;
928                     }
929                     break;
930 
931                 case L2CAP_EVENT_CAN_SEND_NOW:
932                     l2cap_cid  = l2cap_event_can_send_now_get_local_cid(packet);
933                     connection = hid_host_get_connection_for_l2cap_cid(l2cap_cid);
934                     if (!connection) return;
935 
936 
937 
938                     if (connection->control_cid == l2cap_cid){
939                         switch(connection->state){
940                             case HID_HOST_CONTROL_CONNECTION_ESTABLISHED:
941                             case HID_HOST_W4_INTERRUPT_CONNECTION_ESTABLISHED:
942                                 if (connection->set_protocol){
943                                     connection->set_protocol = false;
944                                     uint8_t protocol_mode = connection->requested_protocol_mode == HID_PROTOCOL_MODE_BOOT ? 0 : 1;
945                                     uint8_t header = (HID_MESSAGE_TYPE_SET_PROTOCOL << 4) | protocol_mode;
946                                     uint8_t report[] = {header};
947                                     connection->w4_set_protocol_response = true;
948                                     l2cap_send(connection->control_cid, (uint8_t*) report, sizeof(report));
949                                     break;
950                                 }
951                                 break;
952 
953                             case HID_HOST_CONNECTION_ESTABLISHED:
954                                 if ((connection->control_tasks & CONTROL_MESSAGE_BITMASK_SUSPEND) != 0){
955                                     connection->control_tasks &= ~CONTROL_MESSAGE_BITMASK_SUSPEND;
956                                     uint8_t report[] = { (HID_MESSAGE_TYPE_HID_CONTROL << 4) | HID_CONTROL_PARAM_SUSPEND };
957                                     l2cap_send(connection->control_cid, (uint8_t*) report, 1);
958                                     break;
959                                 }
960                                 if ((connection->control_tasks & CONTROL_MESSAGE_BITMASK_EXIT_SUSPEND) != 0){
961                                     connection->control_tasks &= ~CONTROL_MESSAGE_BITMASK_EXIT_SUSPEND;
962                                     uint8_t report[] = { (HID_MESSAGE_TYPE_HID_CONTROL << 4) | HID_CONTROL_PARAM_EXIT_SUSPEND };
963                                     l2cap_send(connection->control_cid, (uint8_t*) report, 1);
964                                     break;
965                                 }
966                                 if ((connection->control_tasks & CONTROL_MESSAGE_BITMASK_VIRTUAL_CABLE_UNPLUG) != 0){
967                                     connection->control_tasks &= ~CONTROL_MESSAGE_BITMASK_VIRTUAL_CABLE_UNPLUG;
968                                     uint8_t report[] = { (HID_MESSAGE_TYPE_HID_CONTROL << 4) | HID_CONTROL_PARAM_VIRTUAL_CABLE_UNPLUG };
969                                     l2cap_send(connection->control_cid, (uint8_t*) report, 1);
970                                     break;
971                                 }
972 
973                                 if (connection->set_protocol){
974                                     connection->set_protocol = false;
975                                     uint8_t header = (HID_MESSAGE_TYPE_SET_PROTOCOL << 4) | connection->requested_protocol_mode;
976                                     uint8_t report[] = {header};
977 
978                                     connection->w4_set_protocol_response = true;
979                                     l2cap_send(connection->control_cid, (uint8_t*) report, sizeof(report));
980                                     break;
981                                 }
982                                 break;
983 
984                             case HID_HOST_W2_SEND_GET_REPORT:{
985                                 uint8_t header = (HID_MESSAGE_TYPE_GET_REPORT << 4) | connection->report_type;
986                                 uint8_t report[] = {header, connection->report_id};
987 
988                                 connection->state = HID_HOST_W4_GET_REPORT_RESPONSE;
989                                 l2cap_send(connection->control_cid, (uint8_t*) report, sizeof(report));
990                                 break;
991                             }
992 
993                             case HID_HOST_W2_SEND_SET_REPORT:{
994                                 uint8_t header = (HID_MESSAGE_TYPE_SET_REPORT << 4) | connection->report_type;
995                                 connection->state = HID_HOST_W4_SET_REPORT_RESPONSE;
996 
997                                 l2cap_reserve_packet_buffer();
998                                 uint8_t * out_buffer = l2cap_get_outgoing_buffer();
999                                 out_buffer[0] = header;
1000                                 out_buffer[1] = connection->report_id;
1001                                 (void)memcpy(out_buffer + 2, connection->report, connection->report_len);
1002                                 l2cap_send_prepared(connection->control_cid, connection->report_len + 2);
1003                                 break;
1004                             }
1005 
1006                             case HID_HOST_W2_SEND_GET_PROTOCOL:{
1007                                 uint8_t header = (HID_MESSAGE_TYPE_GET_PROTOCOL << 4);
1008                                 uint8_t report[] = {header};
1009                                 connection->state = HID_HOST_W4_GET_PROTOCOL_RESPONSE;
1010                                 l2cap_send(connection->control_cid, (uint8_t*) report, sizeof(report));
1011                                 break;
1012                             }
1013 
1014                             default:
1015                                 break;
1016                         }
1017                     }
1018 
1019                     if (connection->interrupt_cid == l2cap_cid && connection->state == HID_HOST_W2_SEND_REPORT){
1020                         connection->state = HID_HOST_CONNECTION_ESTABLISHED;
1021                         // there is no response for this type of message
1022                         uint8_t header = (HID_MESSAGE_TYPE_DATA << 4) | connection->report_type;
1023 
1024                         l2cap_reserve_packet_buffer();
1025                         uint8_t * out_buffer = l2cap_get_outgoing_buffer();
1026                         out_buffer[0] = header;
1027                         out_buffer[1] = connection->report_id;
1028                         (void)memcpy(out_buffer + 2, connection->report, connection->report_len);
1029                         l2cap_send_prepared(connection->interrupt_cid, connection->report_len + 2);
1030                         break;
1031                     }
1032 
1033                     if (connection->control_tasks != 0){
1034                         l2cap_request_can_send_now_event(connection->control_cid);
1035                     }
1036                     break;
1037                 default:
1038                     break;
1039             }
1040         default:
1041             break;
1042     }
1043 }
1044 
1045 
1046 void hid_host_init(uint8_t * hid_descriptor_storage, uint16_t hid_descriptor_storage_len){
1047     hid_host_descriptor_storage = hid_descriptor_storage;
1048     hid_host_descriptor_storage_len = hid_descriptor_storage_len;
1049 
1050     // register L2CAP Services for reconnections
1051     l2cap_register_service(hid_host_packet_handler, PSM_HID_INTERRUPT, 0xffff, gap_get_security_level());
1052     l2cap_register_service(hid_host_packet_handler, PSM_HID_CONTROL, 0xffff, gap_get_security_level());
1053 }
1054 
1055 void hid_host_deinit(void){
1056     hid_host_callback = NULL;
1057     hid_host_descriptor_storage = NULL;
1058     hid_host_sdp_context_control_cid = 0;
1059     hid_host_connections = NULL;
1060     hid_host_cid_counter = 0;
1061     (void) memset(&hid_host_handle_sdp_client_query_request, 0, sizeof(hid_host_handle_sdp_client_query_request));
1062 }
1063 
1064 void hid_host_register_packet_handler(btstack_packet_handler_t callback){
1065     hid_host_callback = callback;
1066 }
1067 
1068 static void hid_host_handle_start_sdp_client_query(void * context){
1069     UNUSED(context);
1070     btstack_linked_list_iterator_t it;
1071     btstack_linked_list_iterator_init(&it, &hid_host_connections);
1072 
1073     while (btstack_linked_list_iterator_has_next(&it)){
1074         hid_host_connection_t * connection = (hid_host_connection_t *)btstack_linked_list_iterator_next(&it);
1075 
1076         switch (connection->state){
1077             case HID_HOST_W2_SEND_SDP_QUERY:
1078                 connection->state = HID_HOST_W4_SDP_QUERY_RESULT;
1079                 connection->hid_descriptor_status = ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1080                 break;
1081             default:
1082                 continue;
1083         }
1084 
1085         hid_descriptor_storage_init(connection);
1086         hid_host_sdp_context_control_cid = connection->hid_cid;
1087         sdp_client_query_uuid16(&hid_host_handle_sdp_client_query_result, (uint8_t *) connection->remote_addr, BLUETOOTH_SERVICE_CLASS_HUMAN_INTERFACE_DEVICE_SERVICE);
1088         return;
1089     }
1090 }
1091 
1092 uint8_t hid_host_accept_connection(uint16_t hid_cid, hid_protocol_mode_t protocol_mode){
1093     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1094     if (!connection){
1095         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1096     }
1097     if (connection->state != HID_HOST_W4_CONTROL_CONNECTION_ESTABLISHED){
1098         return ERROR_CODE_COMMAND_DISALLOWED;
1099     }
1100 
1101     connection->requested_protocol_mode = protocol_mode;
1102     l2cap_accept_connection(connection->control_cid);
1103     return ERROR_CODE_SUCCESS;
1104 }
1105 
1106 uint8_t hid_host_decline_connection(uint16_t hid_cid){
1107     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1108     if (!connection){
1109         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1110     }
1111     if (connection->state != HID_HOST_W4_CONTROL_CONNECTION_ESTABLISHED){
1112         return ERROR_CODE_COMMAND_DISALLOWED;
1113     }
1114 
1115     l2cap_decline_connection(connection->control_cid);
1116     hid_host_finalize_connection(connection);
1117     return ERROR_CODE_SUCCESS;
1118 }
1119 
1120 uint8_t hid_host_connect(bd_addr_t remote_addr, hid_protocol_mode_t protocol_mode, uint16_t * hid_cid){
1121     if (hid_cid == NULL) {
1122         return ERROR_CODE_COMMAND_DISALLOWED;
1123     }
1124 
1125     hid_host_connection_t * connection = hid_host_get_connection_for_bd_addr(remote_addr);
1126     if (connection){
1127         return ERROR_CODE_COMMAND_DISALLOWED;
1128     }
1129 
1130     connection = hid_host_create_connection(remote_addr);
1131     if (!connection) return BTSTACK_MEMORY_ALLOC_FAILED;
1132 
1133     *hid_cid = connection->hid_cid;
1134 
1135     connection->state = HID_HOST_W2_SEND_SDP_QUERY;
1136     connection->incoming = false;
1137     connection->requested_protocol_mode = protocol_mode;
1138     connection->hid_descriptor_status = ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1139 
1140     uint8_t status = ERROR_CODE_SUCCESS;
1141 
1142     switch (connection->requested_protocol_mode){
1143         case HID_PROTOCOL_MODE_BOOT:
1144             connection->state = HID_HOST_W4_CONTROL_CONNECTION_ESTABLISHED;
1145             status = l2cap_create_channel(hid_host_packet_handler, connection->remote_addr, BLUETOOTH_PSM_HID_CONTROL, 0xffff, &connection->control_cid);
1146             break;
1147         default:
1148             hid_host_handle_sdp_client_query_request.callback = &hid_host_handle_start_sdp_client_query;
1149             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1150             (void) sdp_client_register_query_callback(&hid_host_handle_sdp_client_query_request);
1151             break;
1152     }
1153     return status;
1154 }
1155 
1156 
1157 void hid_host_disconnect(uint16_t hid_cid){
1158     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1159     if (!connection) return;
1160 
1161     switch (connection->state){
1162         case HID_HOST_IDLE:
1163         case HID_HOST_W4_CONTROL_CONNECTION_DISCONNECTED:
1164         case HID_HOST_W4_INTERRUPT_CONNECTION_DISCONNECTED:
1165             return;
1166         default:
1167             break;
1168     }
1169 
1170     if (connection->interrupt_cid){
1171         connection->state = HID_HOST_W4_INTERRUPT_CONNECTION_DISCONNECTED;
1172         l2cap_disconnect(connection->interrupt_cid);
1173         return;
1174     }
1175 
1176     if (connection->control_cid){
1177         connection->state = HID_HOST_W4_CONTROL_CONNECTION_DISCONNECTED;
1178         l2cap_disconnect(connection->control_cid);
1179         return;
1180     }
1181 }
1182 
1183 
1184 static inline uint8_t hid_host_send_control_message(uint16_t hid_cid, uint8_t control_message_bitmask){
1185     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1186     if (!connection || !connection->control_cid) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1187 
1188     if (connection->state < HID_HOST_CONTROL_CONNECTION_ESTABLISHED) {
1189         return ERROR_CODE_COMMAND_DISALLOWED;
1190     }
1191     if (connection->state >= HID_HOST_W4_INTERRUPT_CONNECTION_DISCONNECTED){
1192         return ERROR_CODE_COMMAND_DISALLOWED;
1193     }
1194 
1195     connection->control_tasks |= control_message_bitmask;
1196     l2cap_request_can_send_now_event(connection->control_cid);
1197     return ERROR_CODE_SUCCESS;
1198 }
1199 
1200 uint8_t hid_host_send_suspend(uint16_t hid_cid){
1201     return hid_host_send_control_message(hid_cid, CONTROL_MESSAGE_BITMASK_SUSPEND);
1202 }
1203 
1204 uint8_t hid_host_send_exit_suspend(uint16_t hid_cid){
1205     return hid_host_send_control_message(hid_cid, CONTROL_MESSAGE_BITMASK_EXIT_SUSPEND);
1206 }
1207 
1208 uint8_t hid_host_send_virtual_cable_unplug(uint16_t hid_cid){
1209     return hid_host_send_control_message(hid_cid, CONTROL_MESSAGE_BITMASK_VIRTUAL_CABLE_UNPLUG);
1210 }
1211 
1212 uint8_t hid_host_send_get_report(uint16_t hid_cid,  hid_report_type_t report_type, uint8_t report_id){
1213     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1214 
1215     if (!connection || !connection->control_cid){
1216         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1217     }
1218     if (connection->state != HID_HOST_CONNECTION_ESTABLISHED){
1219         return ERROR_CODE_COMMAND_DISALLOWED;
1220     }
1221 
1222     connection->state = HID_HOST_W2_SEND_GET_REPORT;
1223     connection->report_type = report_type;
1224     connection->report_id = report_id;
1225 
1226     l2cap_request_can_send_now_event(connection->control_cid);
1227     return ERROR_CODE_SUCCESS;
1228 }
1229 
1230 uint8_t hid_host_send_set_report(uint16_t hid_cid, hid_report_type_t report_type, uint8_t report_id, const uint8_t * report, uint8_t report_len){
1231     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1232 
1233     if (!connection || !connection->control_cid){
1234         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1235     }
1236 
1237     if (connection->state != HID_HOST_CONNECTION_ESTABLISHED){
1238         return ERROR_CODE_COMMAND_DISALLOWED;
1239     }
1240 
1241     if ((l2cap_max_mtu() - 2) < report_len ){
1242         return ERROR_CODE_COMMAND_DISALLOWED;
1243     }
1244 
1245     connection->state = HID_HOST_W2_SEND_SET_REPORT;
1246     connection->report_type = report_type;
1247     connection->report_id = report_id;
1248     connection->report = report;
1249     connection->report_len = report_len;
1250 
1251     l2cap_request_can_send_now_event(connection->control_cid);
1252     return ERROR_CODE_SUCCESS;
1253 }
1254 
1255 uint8_t hid_host_send_get_protocol(uint16_t hid_cid){
1256     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1257     if (!connection || !connection->control_cid){
1258         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1259     }
1260     if (connection->state != HID_HOST_CONNECTION_ESTABLISHED){
1261         return ERROR_CODE_COMMAND_DISALLOWED;
1262     }
1263 
1264     connection->state = HID_HOST_W2_SEND_GET_PROTOCOL;
1265     l2cap_request_can_send_now_event(connection->control_cid);
1266     return ERROR_CODE_SUCCESS;
1267 }
1268 
1269 uint8_t hid_host_send_set_protocol_mode(uint16_t hid_cid, hid_protocol_mode_t protocol_mode){
1270     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1271     if (!connection || !connection->control_cid){
1272         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1273     }
1274     if (connection->state != HID_HOST_CONNECTION_ESTABLISHED || connection->set_protocol || connection->w4_set_protocol_response){
1275         return ERROR_CODE_COMMAND_DISALLOWED;
1276     }
1277 
1278     connection->set_protocol = true;
1279     connection->requested_protocol_mode = protocol_mode;
1280 
1281     l2cap_request_can_send_now_event(connection->control_cid);
1282     return ERROR_CODE_SUCCESS;
1283 }
1284 
1285 
1286 uint8_t hid_host_send_report(uint16_t hid_cid, uint8_t report_id, const uint8_t * report, uint8_t report_len){
1287     hid_host_connection_t * connection = hid_host_get_connection_for_hid_cid(hid_cid);
1288     if (!connection || !connection->control_cid || !connection->interrupt_cid) {
1289         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1290     }
1291 
1292     if (connection->state < HID_HOST_CONNECTION_ESTABLISHED) {
1293         return ERROR_CODE_COMMAND_DISALLOWED;
1294     }
1295     if (connection->state >= HID_HOST_W4_INTERRUPT_CONNECTION_DISCONNECTED){
1296         return ERROR_CODE_COMMAND_DISALLOWED;
1297     }
1298 
1299     if ((l2cap_max_mtu() - 2) < report_len ){
1300         return ERROR_CODE_COMMAND_DISALLOWED;
1301     }
1302 
1303     connection->state = HID_HOST_W2_SEND_REPORT;
1304     connection->report_type = HID_REPORT_TYPE_OUTPUT;
1305     connection->report_id = report_id;
1306     connection->report = report;
1307     connection->report_len = report_len;
1308 
1309     l2cap_request_can_send_now_event(connection->interrupt_cid);
1310     return ERROR_CODE_SUCCESS;
1311 }
1312