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