xref: /btstack/src/classic/hid_device.c (revision 630ffdd469bbec3276322f46b93e6cfdfcb21c27)
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_device.c"
39 
40 #include <string.h>
41 
42 #include "classic/hid_device.h"
43 #include "classic/sdp_util.h"
44 #include "bluetooth.h"
45 #include "bluetooth_sdp.h"
46 #include "l2cap.h"
47 #include "btstack_event.h"
48 #include "btstack_debug.h"
49 
50 typedef enum {
51     HID_DEVICE_IDLE,
52     HID_DEVICE_CONNECTED,
53     HID_DEVICE_W2_GET_REPORT,
54     HID_DEVICE_W2_SET_REPORT,
55     HID_DEVICE_W2_GET_PROTOCOL,
56     HID_DEVICE_W2_SET_PROTOCOL,
57     HID_DEVICE_W2_ANSWER_SET_PROTOCOL,
58     HID_DEVICE_W2_SEND_UNSUPPORTED_REQUEST,
59 } hid_device_state_t;
60 
61 // hid device state
62 typedef struct hid_device {
63     uint16_t  cid;
64     bd_addr_t bd_addr;
65     hci_con_handle_t con_handle;
66     uint16_t  control_cid;
67     uint16_t  interrupt_cid;
68     uint8_t   incoming;
69     uint8_t   connected;
70     hid_device_state_t state;
71     hid_report_type_t report_type;
72     uint16_t  report_id;
73     uint16_t  max_packet_size;
74 
75     hid_handshake_param_type_t report_status;
76     hid_protocol_mode_t protocol_mode;
77 } hid_device_t;
78 
79 static hid_device_t _hid_device;
80 static uint8_t hid_boot_protocol_mode_supported;
81 static uint8_t hid_report_ids_declared;
82 
83 static hid_handshake_param_type_t dummy_write_report(uint16_t hid_cid, hid_report_type_t report_type, uint16_t report_id, uint8_t report_max_size, int * out_report_size, uint8_t * out_report){
84     UNUSED(hid_cid);
85     UNUSED(report_type);
86     UNUSED(report_id);
87     UNUSED(report_max_size);
88     UNUSED(out_report_size);
89     UNUSED(out_report);
90     return HID_HANDSHAKE_PARAM_TYPE_ERR_UNKNOWN;
91 }
92 static hid_handshake_param_type_t dummy_set_report(uint16_t hid_cid, hid_report_type_t report_type, int report_size, uint8_t * report){
93     UNUSED(hid_cid);
94     UNUSED(report_type);
95     UNUSED(report_size);
96     UNUSED(report);
97     return HID_HANDSHAKE_PARAM_TYPE_ERR_UNKNOWN;
98 }
99 static void dummy_report_data(uint16_t hid_cid, hid_report_type_t report_type, uint16_t report_id, int report_size, uint8_t * report){
100     UNUSED(hid_cid);
101     UNUSED(report_type);
102     UNUSED(report_id);
103     UNUSED(report_size);
104     UNUSED(report);
105 }
106 
107 static hid_handshake_param_type_t (*hci_device_write_report) (uint16_t hid_cid, hid_report_type_t report_type, uint16_t report_id, uint8_t report_max_size, int * out_report_size, uint8_t * out_report) = dummy_write_report;
108 static hid_handshake_param_type_t (*hci_device_set_report)   (uint16_t hid_cid, hid_report_type_t report_type, int report_size, uint8_t * report) = dummy_set_report;
109 static void                       (*hci_device_report_data)  (uint16_t hid_cid, hid_report_type_t report_type, uint16_t report_id, int report_size, uint8_t * report) = dummy_report_data;
110 
111 static btstack_packet_handler_t hid_callback;
112 
113 static uint16_t hid_device_cid = 0;
114 
115 static uint16_t hid_device_get_next_cid(void){
116     hid_device_cid++;
117     if (!hid_device_cid){
118         hid_device_cid = 1;
119     }
120     return hid_device_cid;
121 }
122 
123 // TODO: store hid device connection into list
124 static hid_device_t * hid_device_get_instance_for_cid(uint16_t cid){
125     // printf("control_cid 0x%02x, interrupt_cid 0x%02x, query_cid 0x%02x \n", _hid_device.control_cid,  _hid_device.interrupt_cid, cid);
126     if (_hid_device.cid == cid || _hid_device.control_cid == cid || _hid_device.interrupt_cid == cid){
127         return &_hid_device;
128     }
129     return NULL;
130 }
131 
132 static hid_device_t * hid_device_provide_instance_for_bt_addr(bd_addr_t bd_addr){
133     if (!_hid_device.cid){
134         memcpy(_hid_device.bd_addr, bd_addr, 6);
135         _hid_device.cid = hid_device_get_next_cid();
136         _hid_device.protocol_mode = HID_PROTOCOL_MODE_REPORT;
137     }
138     return &_hid_device;
139 }
140 
141 static hid_device_t * hid_device_get_instance_for_con_handle(uint16_t con_handle){
142     UNUSED(con_handle);
143     return &_hid_device;
144 }
145 
146 static hid_device_t * hid_device_create_instance(void){
147 
148     return &_hid_device;
149 }
150 
151 void hid_create_sdp_record(
152     uint8_t *service,
153     uint32_t service_record_handle,
154     uint16_t hid_device_subclass,
155     uint8_t  hid_country_code,
156     uint8_t  hid_virtual_cable,
157     uint8_t  hid_reconnect_initiate,
158     uint8_t  hid_boot_device,
159     const uint8_t * hid_descriptor, uint16_t hid_descriptor_size,
160     const char *device_name){
161 
162     uint8_t * attribute;
163     de_create_sequence(service);
164 
165     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
166     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
167 
168     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
169     attribute = de_push_sequence(service);
170     {
171         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HUMAN_INTERFACE_DEVICE_SERVICE);
172     }
173     de_pop_sequence(service, attribute);
174 
175     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
176     attribute = de_push_sequence(service);
177     {
178         uint8_t * l2cpProtocol = de_push_sequence(attribute);
179         {
180             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
181             de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, PSM_HID_CONTROL);
182         }
183         de_pop_sequence(attribute, l2cpProtocol);
184 
185         uint8_t * hidProtocol = de_push_sequence(attribute);
186         {
187             de_add_number(hidProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_HIDP);
188         }
189         de_pop_sequence(attribute, hidProtocol);
190     }
191     de_pop_sequence(service, attribute);
192 
193     // TODO?
194     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_LANGUAGE_BASE_ATTRIBUTE_ID_LIST);
195     attribute = de_push_sequence(service);
196     {
197         de_add_number(attribute, DE_UINT, DE_SIZE_16, 0x656e);
198         de_add_number(attribute, DE_UINT, DE_SIZE_16, 0x006a);
199         de_add_number(attribute, DE_UINT, DE_SIZE_16, 0x0100);
200     }
201     de_pop_sequence(service, attribute);
202 
203     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS);
204     attribute = de_push_sequence(service);
205     {
206         uint8_t * additionalDescriptorAttribute = de_push_sequence(attribute);
207         {
208             uint8_t * l2cpProtocol = de_push_sequence(additionalDescriptorAttribute);
209             {
210                 de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
211                 de_add_number(l2cpProtocol,  DE_UINT, DE_SIZE_16, PSM_HID_INTERRUPT);
212             }
213             de_pop_sequence(additionalDescriptorAttribute, l2cpProtocol);
214 
215             uint8_t * hidProtocol = de_push_sequence(attribute);
216             {
217                 de_add_number(hidProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_HIDP);
218             }
219             de_pop_sequence(attribute, hidProtocol);
220         }
221         de_pop_sequence(attribute, additionalDescriptorAttribute);
222     }
223     de_pop_sequence(service, attribute);
224 
225     // 0x0100 "ServiceName"
226     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
227     de_add_data(service,  DE_STRING, strlen(device_name), (uint8_t *) device_name);
228 
229     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
230     attribute = de_push_sequence(service);
231     {
232         uint8_t * hidProfile = de_push_sequence(attribute);
233         {
234             de_add_number(hidProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HUMAN_INTERFACE_DEVICE_SERVICE);
235             de_add_number(hidProfile,  DE_UINT, DE_SIZE_16, 0x0101);    // Version 1.1
236         }
237         de_pop_sequence(attribute, hidProfile);
238     }
239     de_pop_sequence(service, attribute);
240 
241     // Deprecated in v1.1.1
242     // de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_DEVICE_RELEASE_NUMBER);
243     // de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0101);
244 
245     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_PARSER_VERSION);
246     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0111);  // v1.1.1
247 
248     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_DEVICE_SUBCLASS);
249     de_add_number(service,  DE_UINT, DE_SIZE_8,  hid_device_subclass);
250 
251     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_COUNTRY_CODE);
252     de_add_number(service,  DE_UINT, DE_SIZE_8,  hid_country_code);
253 
254     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_VIRTUAL_CABLE);
255     de_add_number(service,  DE_BOOL, DE_SIZE_8,  hid_virtual_cable);
256 
257     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_RECONNECT_INITIATE);
258     de_add_number(service,  DE_BOOL, DE_SIZE_8,  hid_reconnect_initiate);
259 
260     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_DESCRIPTOR_LIST);
261     attribute = de_push_sequence(service);
262     {
263         uint8_t* hidDescriptor = de_push_sequence(attribute);
264         {
265             de_add_number(hidDescriptor,  DE_UINT, DE_SIZE_8, 0x22);    // Report Descriptor
266             de_add_data(hidDescriptor,  DE_STRING, hid_descriptor_size, (uint8_t *) hid_descriptor);
267         }
268         de_pop_sequence(attribute, hidDescriptor);
269     }
270     de_pop_sequence(service, attribute);
271 
272     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HIDLANGID_BASE_LIST);
273     attribute = de_push_sequence(service);
274     {
275         uint8_t* hig_lang_base = de_push_sequence(attribute);
276         {
277             // see: http://www.usb.org/developers/docs/USB_LANGIDs.pdf
278             de_add_number(hig_lang_base,  DE_UINT, DE_SIZE_16, 0x0409);    // HIDLANGID = English (US)
279             de_add_number(hig_lang_base,  DE_UINT, DE_SIZE_16, 0x0100);    // HIDLanguageBase = 0x0100 default
280         }
281         de_pop_sequence(attribute, hig_lang_base);
282     }
283     de_pop_sequence(service, attribute);
284 
285     uint8_t hid_remote_wake = 1;
286     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_REMOTE_WAKE);
287     de_add_number(service,  DE_BOOL, DE_SIZE_8,  hid_remote_wake);
288 
289     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_HID_BOOT_DEVICE);
290     de_add_number(service,  DE_BOOL, DE_SIZE_8,  hid_boot_device);
291 }
292 
293 static inline void hid_device_emit_connected_event(hid_device_t * context, uint8_t status){
294     uint8_t event[15];
295     int pos = 0;
296     event[pos++] = HCI_EVENT_HID_META;
297     pos++;  // skip len
298     event[pos++] = HID_SUBEVENT_CONNECTION_OPENED;
299     little_endian_store_16(event,pos,context->cid);
300     pos+=2;
301     event[pos++] = status;
302     reverse_bd_addr(context->bd_addr, &event[pos]);
303     pos += 6;
304     little_endian_store_16(event,pos,context->con_handle);
305     pos += 2;
306     event[pos++] = context->incoming;
307     event[1] = pos - 2;
308     if (pos != sizeof(event)) log_error("hid_device_emit_connected_event size %u", pos);
309     hid_callback(HCI_EVENT_PACKET, context->cid, &event[0], pos);
310 }
311 
312 static inline void hid_device_emit_connection_closed_event(hid_device_t * context){
313     uint8_t event[5];
314     int pos = 0;
315     event[pos++] = HCI_EVENT_HID_META;
316     pos++;  // skip len
317     event[pos++] = HID_SUBEVENT_CONNECTION_CLOSED;
318     little_endian_store_16(event,pos,context->cid);
319     pos+=2;
320     event[1] = pos - 2;
321     if (pos != sizeof(event)) log_error("hid_device_emit_connection_closed_event size %u", pos);
322     hid_callback(HCI_EVENT_PACKET, context->cid, &event[0], pos);
323 }
324 
325 static inline void hid_device_emit_can_send_now_event(hid_device_t * context){
326     uint8_t event[5];
327     int pos = 0;
328     event[pos++] = HCI_EVENT_HID_META;
329     pos++;  // skip len
330     event[pos++] = HID_SUBEVENT_CAN_SEND_NOW;
331     little_endian_store_16(event,pos,context->cid);
332     pos+=2;
333     event[1] = pos - 2;
334     if (pos != sizeof(event)) log_error("hid_device_emit_can_send_now_event size %u", pos);
335     hid_callback(HCI_EVENT_PACKET, context->cid, &event[0], pos);
336 }
337 
338 static inline void hid_device_emit_event(hid_device_t * context, uint8_t subevent_type){
339     uint8_t event[4];
340     int pos = 0;
341     event[pos++] = HCI_EVENT_HID_META;
342     pos++;  // skip len
343     event[pos++] = subevent_type;
344     little_endian_store_16(event,pos,context->cid);
345     pos+=2;
346     event[1] = pos - 2;
347     if (pos != sizeof(event)) log_error("hid_device_emit_event size %u", pos);
348     hid_callback(HCI_EVENT_PACKET, context->cid, &event[0], pos);
349 }
350 
351 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t packet_size){
352     UNUSED(channel);
353     UNUSED(packet_size);
354     int connected_before;
355     uint16_t psm;
356     uint8_t status;
357     hid_device_t * device = NULL;
358     uint8_t param;
359     bd_addr_t address;
360     uint16_t local_cid;
361 
362     int report_size;
363     uint8_t report[20];
364 
365     switch (packet_type){
366         case L2CAP_DATA_PACKET:
367             device = hid_device_get_instance_for_cid(channel);
368             if (!device) {
369                 log_error("no device with cid 0x%02x", channel);
370                 return;
371             }
372             hid_message_type_t message_type = packet[0] >> 4;
373             // printf("L2CAP_DATA_PACKET message_type %d, packet_size %d  \n", message_type, packet_size);
374             switch (message_type){
375                 case HID_MESSAGE_TYPE_GET_REPORT:
376                     device->report_type = packet[0] & 0x03;
377                     device->report_id = 0;
378                     device->report_status = HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL;
379 
380                     switch (device->protocol_mode){
381                         case HID_PROTOCOL_MODE_BOOT:
382                             // printf("HID_PROTOCOL_MODE_BOOT \n");
383                             if (!hid_report_ids_declared || packet_size < 2){
384                                 device->report_status = HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
385                                 break;
386                             }
387                             device->report_id = packet[1];
388                             break;
389                         case HID_PROTOCOL_MODE_REPORT:
390                             // printf("HID_PROTOCOL_MODE_REPORT,  hid_report_ids_declared %d\n", hid_report_ids_declared);
391                             if (!hid_report_ids_declared) break;
392 
393                             if (packet_size < 2){
394                                 device->report_status = HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
395                                 break;
396                             }
397                             device->report_id = packet[1];
398                             break;
399                     }
400 
401                     if ((packet[0] & 0x08) && packet_size >= 4){
402                         device->max_packet_size = little_endian_read_16(packet, 2);
403                     } else {
404                         device->max_packet_size = l2cap_max_mtu();
405                     }
406                     device->state = HID_DEVICE_W2_GET_REPORT;
407                     // l2cap_request_can_send_now_event(device->control_cid);
408                     hid_device_request_can_send_now_event(channel);
409                     break;
410 
411                 case HID_MESSAGE_TYPE_SET_REPORT:
412                     device->state = HID_DEVICE_W2_SET_REPORT;
413                     device->max_packet_size = l2cap_max_mtu();
414                     device->report_type = packet[0] & 0x03;
415                     if (packet_size < 1){
416                         device->report_status = HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
417                         break;
418                     }
419 
420                     switch (device->protocol_mode){
421                         case HID_PROTOCOL_MODE_BOOT:
422                             // printf("HID_PROTOCOL_MODE_BOOT \n");
423                             if (packet_size < 3){
424                                 device->report_status = HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
425                                 break;
426                             }
427                             device->report_id = packet[1];
428                             device->report_status = (*hci_device_set_report)(device->cid, device->report_type, packet_size-1, &packet[1]);
429                             break;
430                         case HID_PROTOCOL_MODE_REPORT:
431                             // printf("HID_PROTOCOL_MODE_REPORT \n");
432                             if (packet_size >= 2){
433                                 device->report_status = (*hci_device_set_report)(device->cid, device->report_type, packet_size-1, &packet[1]);
434                             } else {
435                                 uint8_t payload[] = {0};
436                                 device->report_status = (*hci_device_set_report)(device->cid, device->report_type, 1, payload);
437                             }
438                             break;
439                     }
440                     device->report_type = packet[0] & 0x03;
441                     hid_device_request_can_send_now_event(channel);
442                     // l2cap_request_can_send_now_event(device->control_cid);
443                     break;
444                 case HID_MESSAGE_TYPE_GET_PROTOCOL:
445                     // printf(" HID_MESSAGE_TYPE_GET_PROTOCOL\n");
446                     device->state = HID_DEVICE_W2_GET_PROTOCOL;
447                     if (packet_size != 1) {
448                         device->report_status = HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
449                         break;
450                     }
451                     device->report_status = HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL;
452                     // hid_device_request_can_send_now_event(channel);
453                     // printf("HID_MESSAGE_TYPE_GET_PROTOCOL l2cap_request_can_send_now_event\n");
454                     l2cap_request_can_send_now_event(device->control_cid);
455                     break;
456 
457                 case HID_MESSAGE_TYPE_SET_PROTOCOL:
458                     device->state = HID_DEVICE_W2_SET_PROTOCOL;
459                     if (packet_size != 1) {
460                         device->report_status = HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
461                         break;
462                     }
463                     param = packet[0] & 0x01;
464                     if (param == HID_PROTOCOL_MODE_BOOT && !hid_boot_protocol_mode_supported){
465                         device->report_status = HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
466                         break;
467                     }
468                     device->protocol_mode = param;
469                     switch (device->protocol_mode){
470                         case HID_PROTOCOL_MODE_BOOT:
471                             // printf("Set protocol mode to BOOT\n");
472                             break;
473                         case HID_PROTOCOL_MODE_REPORT:
474                             // printf("Set protocol mode to REPORT\n");
475                             break;
476                     }
477                     device->report_status = HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL;
478                     hid_device_request_can_send_now_event(channel);
479                     break;
480 
481                 case HID_MESSAGE_TYPE_HID_CONTROL:
482                     param = packet[0] & 0x0F;
483                     switch (param){
484                         case HID_CONTROL_PARAM_SUSPEND:
485                             hid_device_emit_event(device, HID_SUBEVENT_SUSPEND);
486                             break;
487                         case HID_CONTROL_PARAM_EXIT_SUSPEND:
488                             hid_device_emit_event(device, HID_SUBEVENT_EXIT_SUSPEND);
489                             break;
490                         default:
491                             device->state = HID_DEVICE_W2_SEND_UNSUPPORTED_REQUEST;
492                             hid_device_request_can_send_now_event(channel);
493                             // l2cap_request_can_send_now_event(device->control_cid);
494                             break;
495                     }
496                     break;
497 
498                 case HID_MESSAGE_TYPE_DATA:
499                     if (packet_size < 2) {
500                         break;
501                     }
502                     device->report_type = packet[0] & 0x03;
503                     device->report_id = packet[1];
504                     (*hci_device_report_data)(device->cid, device->report_type, device->report_id, packet_size - 2, &packet[2]);
505                     break;
506                 default:
507                     // printf("HID_DEVICE_W2_SEND_UNSUPPORTED_REQUEST %d  \n", message_type);
508                     device->state = HID_DEVICE_W2_SEND_UNSUPPORTED_REQUEST;
509                     // l2cap_request_can_send_now_event(device->control_cid);
510                     hid_device_request_can_send_now_event(channel);
511                     break;
512             }
513             break;
514         case HCI_EVENT_PACKET:
515             switch (packet[0]){
516                 case L2CAP_EVENT_INCOMING_CONNECTION:
517                     switch (l2cap_event_incoming_connection_get_psm(packet)){
518                         case PSM_HID_CONTROL:
519                         case PSM_HID_INTERRUPT:
520                             l2cap_event_incoming_connection_get_address(packet, address);
521                             device = hid_device_provide_instance_for_bt_addr(address);
522                             if (!device) {
523                                 log_error("L2CAP_EVENT_INCOMING_CONNECTION, no hid device for con handle 0x%02x", l2cap_event_incoming_connection_get_handle(packet));
524                                 l2cap_decline_connection(channel);
525                                 break;
526                             }
527                             if (device->con_handle == 0 || l2cap_event_incoming_connection_get_handle(packet) == device->con_handle){
528                                 device->con_handle = l2cap_event_incoming_connection_get_handle(packet);
529                                 device->incoming = 1;
530                                 l2cap_event_incoming_connection_get_address(packet, device->bd_addr);
531                                 l2cap_accept_connection(channel);
532                             } else {
533                                 l2cap_decline_connection(channel);
534                                 log_error("L2CAP_EVENT_INCOMING_CONNECTION, decline connection for con handle 0x%02x", l2cap_event_incoming_connection_get_handle(packet));
535                             }
536                             break;
537                         default:
538                             l2cap_decline_connection(channel);
539                             break;
540                     }
541                     break;
542                 case L2CAP_EVENT_CHANNEL_OPENED:
543                     device = hid_device_get_instance_for_con_handle(l2cap_event_channel_opened_get_handle(packet));
544                     if (!device) {
545                         log_error("L2CAP_EVENT_CHANNEL_OPENED, no hid device for local cid 0x%02x", l2cap_event_channel_opened_get_local_cid(packet));
546                         return;
547                     }
548                     status = l2cap_event_channel_opened_get_status(packet);
549                     if (status) {
550                         if (device->incoming == 0){
551                             // report error for outgoing connection
552                             hid_device_emit_connected_event(device, status);
553                         }
554                         return;
555                     }
556                     psm = l2cap_event_channel_opened_get_psm(packet);
557                     connected_before = device->connected;
558                     switch (psm){
559                         case PSM_HID_CONTROL:
560                             device->control_cid = l2cap_event_channel_opened_get_local_cid(packet);
561                             // printf("HID Control opened, cid 0x%02x\n", device->control_cid);
562                             break;
563                         case PSM_HID_INTERRUPT:
564                             device->interrupt_cid = l2cap_event_channel_opened_get_local_cid(packet);
565                             // printf("HID Interrupt opened, cid 0x%02x\n", device->interrupt_cid);
566                             break;
567                         default:
568                             break;
569                     }
570 
571                     // connect HID Interrupt for outgoing
572                     if (device->incoming == 0 && psm == PSM_HID_CONTROL){
573                         // printf("Create outgoing HID Interrupt\n");
574                         status = l2cap_create_channel(packet_handler, device->bd_addr, PSM_HID_INTERRUPT, 48, &device->interrupt_cid);
575                         break;
576                     }
577                     if (!connected_before && device->control_cid && device->interrupt_cid){
578                         device->connected = 1;
579                         // printf("HID Connected\n");
580                         hid_device_emit_connected_event(device, 0);
581                     }
582                     break;
583                 case L2CAP_EVENT_CHANNEL_CLOSED:
584                     device = hid_device_get_instance_for_cid(l2cap_event_channel_closed_get_local_cid(packet));
585                     if (!device) return;
586 
587                     // connected_before = device->connected;
588                     device->incoming  = 0;
589                     if (l2cap_event_channel_closed_get_local_cid(packet) == device->interrupt_cid){
590                         // printf("HID Interrupt closed\n");
591                         device->interrupt_cid = 0;
592                     }
593                     if (l2cap_event_channel_closed_get_local_cid(packet) == device->control_cid){
594                         // printf("HID Control closed\n");
595                         device->control_cid = 0;
596                     }
597                     if (!device->interrupt_cid && !device->control_cid){
598                         device->connected = 0;
599                         device->con_handle = 0;
600                         device->cid = 0;
601                         // printf("HID Disconnected\n");
602                         hid_device_emit_connection_closed_event(device);
603                     }
604                     break;
605 
606                 case L2CAP_EVENT_CAN_SEND_NOW:
607                     local_cid = l2cap_event_can_send_now_get_local_cid(packet);
608                     device = hid_device_get_instance_for_cid(l2cap_event_can_send_now_get_local_cid(packet));
609 
610                     if (!device) return;
611                     switch (device->state){
612                         case HID_DEVICE_W2_GET_REPORT:
613                             // printf("HID_DEVICE_W2_GET_REPORT \n");
614                             if (device->report_status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL) {
615                                 report[0] = (HID_MESSAGE_TYPE_HANDSHAKE << 4) | device->report_status;
616                                 hid_device_send_control_message(device->cid, &report[0], 1);
617                                 break;
618                             }
619                             report_size = 0;
620                             device->report_status = (*hci_device_write_report)(device->cid, device->report_type, device->report_id, (uint16_t) sizeof(report) - 1, &report_size, &report[1]);
621                             // add header size
622                             report_size += 1;
623 
624                             // printf(" report size %d, status %d, max_packet_size %d\n", report_size, device->report_status, device->max_packet_size);
625                             if (device->report_status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
626                                 report[0] = (HID_MESSAGE_TYPE_HANDSHAKE << 4) | device->report_status;
627                                 hid_device_send_control_message(device->cid, &report[0], 1);
628                                 break;
629                             }
630 
631                             if (report_size > l2cap_max_mtu()){
632                                 report[0] = (HID_MESSAGE_TYPE_HANDSHAKE << 4) | HID_HANDSHAKE_PARAM_TYPE_ERR_INVALID_PARAMETER;
633                                 hid_device_send_control_message(device->cid, &report[0], 1);
634                                 break;
635                             }
636 
637                             // printf("report type %d, report_size %d, max_packet_size %d \n", device->report_type, report_size, device->max_packet_size);
638                             report[0] = (HID_MESSAGE_TYPE_DATA << 4) | device->report_type;
639                             hid_device_send_control_message(device->cid, &report[0], btstack_min(report_size, device->max_packet_size));
640                             //     device->state = HID_DEVICE_IDLE;
641                             break;
642                         case HID_DEVICE_W2_SET_REPORT:
643                         case HID_DEVICE_W2_SET_PROTOCOL:
644                             report[0] = (HID_MESSAGE_TYPE_HANDSHAKE << 4) | device->report_status;
645                             hid_device_send_control_message(device->cid, &report[0], 1);
646                             break;
647                         case HID_DEVICE_W2_GET_PROTOCOL:
648                             if (device->report_status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
649                                 // printf("send HID_MESSAGE_TYPE_HANDSHAKE, report_status %d \n", device->report_status);
650                                 report[0] = (HID_MESSAGE_TYPE_HANDSHAKE << 4) | device->report_status;
651                                 hid_device_send_control_message(device->cid, &report[0], 1);
652                                 break;
653                             }
654 
655                             // printf("send HID_MESSAGE_TYPE_DATA, protocol_mode %d \n", device->protocol_mode);
656                             report[0] = (HID_MESSAGE_TYPE_DATA << 4);
657                             report[1] =  device->protocol_mode;
658                             hid_device_send_control_message(device->cid, &report[0], 2);
659                             break;
660 
661 
662                         case HID_DEVICE_W2_SEND_UNSUPPORTED_REQUEST:
663                             report[0] = (HID_MESSAGE_TYPE_HANDSHAKE << 4) | HID_HANDSHAKE_PARAM_TYPE_ERR_UNSUPPORTED_REQUEST;
664                             hid_device_send_control_message(device->cid, &report[0], 1);
665                             break;
666                         default:
667                             log_info("HID Can send now, emit event");
668                             hid_device_emit_can_send_now_event(device);
669                             // device->state = HID_DEVICE_IDLE;
670                             break;
671                     }
672                     device->state = HID_DEVICE_IDLE;
673                     break;
674                 default:
675                     break;
676             }
677             break;
678         default:
679             break;
680     }
681 }
682 
683 /**
684  * @brief Set up HID Device
685  */
686 void hid_device_init(uint8_t boot_protocol_mode_supported, uint8_t report_ids_declared){
687     hid_boot_protocol_mode_supported = boot_protocol_mode_supported;
688     hid_report_ids_declared = report_ids_declared;
689     l2cap_register_service(packet_handler, PSM_HID_INTERRUPT, 100, LEVEL_2);
690     l2cap_register_service(packet_handler, PSM_HID_CONTROL,   100, LEVEL_2);
691 }
692 
693 /**
694  * @brief Register callback for the HID Device client.
695  * @param callback
696  */
697 void hid_device_register_packet_handler(btstack_packet_handler_t callback){
698     hid_callback = callback;
699 }
700 
701 
702 
703 void hid_device_register_report_request_callback(hid_handshake_param_type_t (*callback) (uint16_t hid_cid, hid_report_type_t report_type, uint16_t report_id, uint8_t report_max_size, int * out_report_size, uint8_t * out_report)){
704     if (callback == NULL){
705         callback = dummy_write_report;
706     }
707     hci_device_write_report = callback;
708 }
709 
710 void hid_device_register_set_report_callback(hid_handshake_param_type_t (*callback) (uint16_t hid_cid, hid_report_type_t report_type, int report_size, uint8_t * report)){
711     if (callback == NULL){
712         callback = dummy_set_report;
713     }
714     hci_device_set_report = callback;
715 }
716 
717 void hid_device_register_report_data_callback(void (*callback)(uint16_t cid, hid_report_type_t report_type, uint16_t report_id, int report_size, uint8_t * report)){
718     if (callback == NULL){
719         callback = dummy_report_data;
720     }
721     hci_device_report_data = callback;
722 }
723 
724 
725 /**
726  * @brief Request can send now event to send HID Report
727  * @param hid_cid
728  */
729 void hid_device_request_can_send_now_event(uint16_t hid_cid){
730     hid_device_t * hid_device = hid_device_get_instance_for_cid(hid_cid);
731     if (!hid_device || !hid_device->control_cid){
732          hid_device->state = HID_DEVICE_IDLE;
733          return;
734     }
735     l2cap_request_can_send_now_event(hid_device->control_cid);
736 }
737 
738 /**
739  * @brief Send HID messageon interrupt channel
740  * @param hid_cid
741  */
742 void hid_device_send_interrupt_message(uint16_t hid_cid, const uint8_t * message, uint16_t message_len){
743     hid_device_t * hid_device = hid_device_get_instance_for_cid(hid_cid);
744     if (!hid_device || !hid_device->interrupt_cid) return;
745     l2cap_send(hid_device->interrupt_cid, (uint8_t*) message, message_len);
746 }
747 
748 /**
749  * @brief Send HID messageon control channel
750  * @param hid_cid
751  */
752 void hid_device_send_control_message(uint16_t hid_cid, const uint8_t * message, uint16_t message_len){
753     hid_device_t * hid_device = hid_device_get_instance_for_cid(hid_cid);
754     if (!hid_device || !hid_device->control_cid) return;
755     l2cap_send(hid_device->control_cid, (uint8_t*) message, message_len);
756 }
757 
758 /*
759  * @brief Create HID connection to HID Host
760  * @param addr
761  * @param hid_cid to use for other commands
762  * @result status
763  */
764 uint8_t hid_device_connect(bd_addr_t addr, uint16_t * hid_cid){
765     hid_device_t * hid_device = hid_device_create_instance();
766     if (!hid_device){
767         log_error("hid_device_connect: could not create a hid device instace");
768         return BTSTACK_MEMORY_ALLOC_FAILED;
769     }
770     // assign hic_cid
771     *hid_cid = hid_device_get_next_cid();
772     // store address
773     memcpy(hid_device->bd_addr, addr, 6);
774 
775     // reset state
776     hid_device->cid           = *hid_cid;
777     hid_device->incoming      = 0;
778     hid_device->connected     = 0;
779     hid_device->control_cid   = 0;
780     hid_device->interrupt_cid = 0;
781     // create l2cap control using fixed HID L2CAP PSM
782     log_info("Create outgoing HID Control");
783     uint8_t status = l2cap_create_channel(packet_handler, hid_device->bd_addr, PSM_HID_CONTROL, 48, &hid_device->control_cid);
784     return status;
785 }
786 
787 /*
788  * @brief Disconnect from HID Host
789  * @param hid_cid
790  * @result status
791  */
792 void hid_device_disconnect_interrupt_channel(uint16_t hid_cid){
793     hid_device_t * hid_device = hid_device_get_instance_for_cid(hid_cid);
794     if (!hid_device){
795         log_error("hid_device_disconnect_interrupt_channel: could not find hid device instace");
796         return;
797     }
798     log_info("Disconnect from interrupt channel HID Host");
799     if (hid_device->interrupt_cid){
800         l2cap_disconnect(hid_device->interrupt_cid, 0);  // reason isn't used
801     }
802 }
803 
804 void hid_device_disconnect_control_channel(uint16_t hid_cid){
805     hid_device_t * hid_device = hid_device_get_instance_for_cid(hid_cid);
806     if (!hid_device){
807         log_error("hid_device_disconnect_control_channel: could not find hid device instace");
808         return;
809     }
810     log_info("Disconnect from control channel HID Host");
811     if (hid_device->control_cid){
812         l2cap_disconnect(hid_device->control_cid, 0);  // reason isn't used
813     }
814 }
815 
816 void hid_device_disconnect(uint16_t hid_cid){
817     hid_device_t * hid_device = hid_device_get_instance_for_cid(hid_cid);
818     if (!hid_device){
819         log_error("hid_device_disconnect: could not find hid device instace");
820         return;
821     }
822     log_info("Disconnect from HID Host");
823     if (hid_device->interrupt_cid){
824         l2cap_disconnect(hid_device->interrupt_cid, 0);  // reason isn't used
825     }
826     if (hid_device->control_cid){
827         l2cap_disconnect(hid_device->control_cid, 0); // reason isn't used
828     }
829 }
830 
831 int hid_device_in_boot_protocol_mode(uint16_t hid_cid){
832     hid_device_t * hid_device = hid_device_get_instance_for_cid(hid_cid);
833     if (!hid_device){
834         log_error("hid_device_in_boot_protocol_mode: could not find hid device instace");
835         return 0;
836     }
837     return hid_device->protocol_mode == HID_PROTOCOL_MODE_BOOT;
838 }
839