xref: /btstack/example/hid_host_demo.c (revision e615b0ec8b3fb47784b40c01d784e14cadd4ad92)
1 /*
2  * Copyright (C) 2017 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_demo.c"
39 
40 /*
41  * hid_host_demo.c
42  */
43 
44 /* EXAMPLE_START(hid_host_demo): HID Host Classic
45  *
46  * @text This example implements an HID Host. For now, it connnects to a fixed device, queries the HID SDP
47  * record and opens the HID Control + Interrupt channels
48  */
49 
50 #include <inttypes.h>
51 #include <stdio.h>
52 
53 #include "btstack_config.h"
54 #include "btstack.h"
55 
56 #define MAX_ATTRIBUTE_VALUE_SIZE 300
57 
58 // MBP 2016 static const char * remote_addr_string = "F4-0F-24-3B-1B-E1";
59 // iMpulse static const char * remote_addr_string = "64:6E:6C:C1:AA:B5";
60 // Logitec
61 static const char * remote_addr_string = "00:1F:20:86:DF:52";
62 
63 static bd_addr_t remote_addr;
64 
65 static btstack_packet_callback_registration_t hci_event_callback_registration;
66 
67 // Simplified US Keyboard with Shift modifier
68 
69 #define CHAR_ILLEGAL     0xff
70 #define CHAR_RETURN     '\n'
71 #define CHAR_ESCAPE      27
72 #define CHAR_TAB         '\t'
73 #define CHAR_BACKSPACE   0x7f
74 
75 /**
76  * English (US)
77  */
78 static const uint8_t keytable_us_none [] = {
79     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*   0-3 */
80     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                   /*  4-13 */
81     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',                   /* 14-23 */
82     'u', 'v', 'w', 'x', 'y', 'z',                                       /* 24-29 */
83     '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',                   /* 30-39 */
84     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
85     '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',',       /* 45-54 */
86     '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
87     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
88     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
89     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
90     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
91     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
92     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
93     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
94     '6', '7', '8', '9', '0', '.', 0xa7,                                 /* 97-100 */
95 };
96 
97 static const uint8_t keytable_us_shift[] = {
98     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*  0-3  */
99     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',                   /*  4-13 */
100     'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',                   /* 14-23 */
101     'U', 'V', 'W', 'X', 'Y', 'Z',                                       /* 24-29 */
102     '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',                   /* 30-39 */
103     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
104     '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<',         /* 45-54 */
105     '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
106     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
107     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
108     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
109     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
110     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
111     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
112     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
113     '6', '7', '8', '9', '0', '.', 0xb1,                                 /* 97-100 */
114 };
115 
116 // SDP
117 static uint8_t hid_descriptor[MAX_ATTRIBUTE_VALUE_SIZE];
118 
119 // App
120 static enum {
121     APP_IDLE,
122     APP_CONNECTED
123 } app_state = APP_IDLE;
124 
125 static uint16_t hid_host_cid = 0;
126 static bool     hid_host_descriptor_available = false;
127 static hid_protocol_mode_t hid_host_report_mode = HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT;
128 
129 /* @section Main application configuration
130  *
131  * @text In the application configuration, L2CAP is initialized
132  */
133 
134 /* LISTING_START(PanuSetup): Panu setup */
135 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
136 
137 static void hid_host_setup(void){
138 
139     // Initialize L2CAP
140     l2cap_init();
141 
142     // Initialize HID Host
143     hid_host_init(hid_descriptor, sizeof(hid_descriptor));
144     hid_host_register_packet_handler(packet_handler);
145 
146     // Allow sniff mode requests by HID device and support role switch
147     gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH);
148 
149     // try to become master on incoming connections
150     hci_set_master_slave_policy(HCI_ROLE_MASTER);
151 
152     // register for HCI events
153     hci_event_callback_registration.callback = &packet_handler;
154     hci_add_event_handler(&hci_event_callback_registration);
155 
156     // Disable stdout buffering
157     setbuf(stdout, NULL);
158 }
159 /* LISTING_END */
160 
161 /*
162  * @section HID Report Handler
163  *
164  * @text Use BTstack's compact HID Parser to process incoming HID Report
165  * Iterate over all fields and process fields with usage page = 0x07 / Keyboard
166  * Check if SHIFT is down and process first character (don't handle multiple key presses)
167  *
168  */
169 #define NUM_KEYS 6
170 static uint8_t last_keys[NUM_KEYS];
171 static void hid_host_handle_interrupt_report(const uint8_t * report, uint16_t report_len){
172     // check if HID Input Report
173     if (report_len < 1) return;
174     if (*report != 0xa1) return;
175 
176     report++;
177     report_len--;
178 
179     btstack_hid_parser_t parser;
180     btstack_hid_parser_init(&parser,
181         hid_descriptor_storage_get_descriptor_data(hid_host_cid),
182         hid_descriptor_storage_get_descriptor_len(hid_host_cid),
183         HID_REPORT_TYPE_INPUT, report, report_len);
184 
185     int shift = 0;
186     uint8_t new_keys[NUM_KEYS];
187     memset(new_keys, 0, sizeof(new_keys));
188     int     new_keys_count = 0;
189     while (btstack_hid_parser_has_more(&parser)){
190         uint16_t usage_page;
191         uint16_t usage;
192         int32_t  value;
193         btstack_hid_parser_get_field(&parser, &usage_page, &usage, &value);
194         if (usage_page != 0x07) continue;
195         switch (usage){
196             case 0xe1:
197             case 0xe6:
198                 if (value){
199                     shift = 1;
200                 }
201                 continue;
202             case 0x00:
203                 continue;
204             default:
205                 break;
206         }
207         if (usage >= sizeof(keytable_us_none)) continue;
208 
209         // store new keys
210         new_keys[new_keys_count++] = usage;
211 
212         // check if usage was used last time (and ignore in that case)
213         int i;
214         for (i=0;i<NUM_KEYS;i++){
215             if (usage == last_keys[i]){
216                 usage = 0;
217             }
218         }
219         if (usage == 0) continue;
220 
221         uint8_t key;
222         if (shift){
223             key = keytable_us_shift[usage];
224         } else {
225             key = keytable_us_none[usage];
226         }
227         if (key == CHAR_ILLEGAL) continue;
228         if (key == CHAR_BACKSPACE){
229             printf("\b \b");    // go back one char, print space, go back one char again
230             continue;
231         }
232         printf("%c", key);
233     }
234     memcpy(last_keys, new_keys, NUM_KEYS);
235 }
236 
237 /*
238  * @section Packet Handler
239  *
240  * @text The packet handler responds to various HCI Events.
241  */
242 
243 /* LISTING_START(packetHandler): Packet Handler */
244 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
245 {
246     /* LISTING_PAUSE */
247     UNUSED(channel);
248     UNUSED(size);
249 
250     uint8_t   event;
251     bd_addr_t event_addr;
252     uint8_t   status;
253 
254     /* LISTING_RESUME */
255     switch (packet_type) {
256 		case HCI_EVENT_PACKET:
257             event = hci_event_packet_get_type(packet);
258 
259             switch (event) {
260 #ifndef HAVE_BTSTACK_STDIN
261                 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING
262                  * is received and the example is started in client mode, the remote SDP HID query is started.
263                  */
264                 case BTSTACK_EVENT_STATE:
265                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
266                         status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
267                         if (status != ERROR_CODE_SUCCESS){
268                             printf("HID host connect failed, status 0x%02x\n", status);
269                         }
270                     }
271                     break;
272 #endif
273                 /* LISTING_PAUSE */
274                 case HCI_EVENT_PIN_CODE_REQUEST:
275 					// inform about pin code request
276                     printf("Pin code request - using '0000'\n");
277                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
278                     gap_pin_code_response(event_addr, "0000");
279 					break;
280 
281                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
282                     // inform about user confirmation request
283                     printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8));
284                     printf("SSP User Confirmation Auto accept\n");
285                     break;
286 
287                 /* LISTING_RESUME */
288                 case HCI_EVENT_HID_META:
289                     switch (hci_event_hid_meta_get_subevent_code(packet)){
290                         case HID_SUBEVENT_INCOMING_CONNECTION:
291                             hid_host_accept_connection(hid_subevent_incoming_connection_get_hid_cid(packet), hid_host_report_mode);
292                             break;
293 
294                         case HID_SUBEVENT_CONNECTION_OPENED:
295                             status = hid_subevent_connection_opened_get_status(packet);
296                             if (status) {
297                                 // outgoing connection failed
298                                 printf("Connection failed, status 0x%x\n", status);
299                                 app_state = APP_IDLE;
300                                 hid_host_cid = 0;
301                                 return;
302                             }
303                             app_state = APP_CONNECTED;
304                             hid_host_descriptor_available = false;
305                             hid_host_cid = hid_subevent_connection_opened_get_hid_cid(packet);
306                             printf("HID Host connected...\n");
307                             break;
308 
309                         case HID_SUBEVENT_DESCRIPTOR_AVAILABLE:
310                             status = hid_subevent_descriptor_available_get_status(packet);
311                             if (status == ERROR_CODE_SUCCESS){
312                                 hid_host_descriptor_available = true;
313                                 printf("HID Descriptor available\n");
314                             } else {
315                                 printf("Cannot handle input report, HID Descriptor is not available.\n");
316                             }
317                             break;
318                         case HID_SUBEVENT_CONNECTION_CLOSED:
319                             hid_host_cid = 0;
320                             hid_host_descriptor_available = false;
321                             printf("HID Host disconnected..\n");
322                             break;
323 
324                         case HID_SUBEVENT_GET_REPORT_RESPONSE:
325                             status = hid_subevent_get_report_response_get_handshake_status(packet);
326                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
327                                 printf("Error get report, status 0x%02x\n", status);
328                                 break;
329                             }
330                             printf("Received report[%d]: ", hid_subevent_get_report_response_get_report_len(packet));
331                             printf_hexdump(hid_subevent_get_report_response_get_report(packet), hid_subevent_get_report_response_get_report_len(packet));
332                             printf("\n");
333                             break;
334 
335                         case HID_SUBEVENT_SET_REPORT_RESPONSE:
336                             status = hid_subevent_set_report_response_get_handshake_status(packet);
337                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
338                                 printf("Error set report, status 0x%02x\n", status);
339                                 break;
340                             }
341                             printf("Report set.\n");
342                             break;
343 
344                         case HID_SUBEVENT_GET_PROTOCOL_RESPONSE:
345                             status = hid_subevent_get_protocol_response_get_handshake_status(packet);
346                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
347                                 printf("Error get report, status 0x%02x\n", status);
348                                 break;
349                             }
350                             switch ((hid_protocol_mode_t)hid_subevent_get_protocol_response_get_protocol_mode(packet)){
351                                 case HID_PROTOCOL_MODE_BOOT:
352                                     printf("HID device is in BOOT mode.\n");
353                                     break;
354                                 case HID_PROTOCOL_MODE_REPORT:
355                                     printf("HID device is in REPORT mode.\n");
356                                     break;
357                                 default:
358                                     break;
359                             }
360                             break;
361 
362                         case HID_SUBEVENT_SET_PROTOCOL_RESPONSE:
363                             status = hid_subevent_set_protocol_response_get_handshake_status(packet);
364                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
365                                 printf("Error set protocol, status 0x%02x\n", status);
366                                 break;
367                             }
368                             switch ((hid_protocol_mode_t)hid_subevent_set_protocol_response_get_protocol_mode(packet)){
369                                 case HID_PROTOCOL_MODE_BOOT:
370                                     printf("Protocol mode set: BOOT.\n");
371                                     break;
372                                 case HID_PROTOCOL_MODE_REPORT:
373                                     printf("Protocol mode set: REPORT.\n");
374                                     break;
375                                 default:
376                                     printf("Unknown protocol mode.\n");
377                                     break;
378                             }
379 
380                             break;
381 
382                         case HID_SUBEVENT_REPORT:
383                             if (hid_host_descriptor_available){
384                                 hid_host_handle_interrupt_report(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
385                             } else {
386                                 printf_hexdump(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
387                             }
388                             break;
389 
390                         default:
391                             break;
392                     }
393                     break;
394                 default:
395                     break;
396             }
397             break;
398         default:
399             break;
400     }
401 }
402 /* LISTING_END */
403 
404 #ifdef HAVE_BTSTACK_STDIN
405 static void show_usage(void){
406     bd_addr_t      iut_address;
407     gap_local_bd_addr(iut_address);
408     printf("\n--- Bluetooth HID Host Test Console %s ---\n", bd_addr_to_str(iut_address));
409     printf("c      - Connect to %s in report mode, with fallback to BOOT mode.\n", remote_addr_string);
410     printf("C      - Disconnect from %s\n", remote_addr_string);
411 
412     printf("\n");
413     printf("Ctrl-c - exit\n");
414     printf("---\n");
415 }
416 
417 static void stdin_process(char cmd){
418     uint8_t status = ERROR_CODE_SUCCESS;
419     switch (cmd){
420         case 'c':
421             printf("Connect to %s in report mode, with fallback to BOOT mode.\n", remote_addr_string);
422             status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
423             break;
424 
425         case 'C':
426             printf("Disconnect from  %s...\n", remote_addr_string);
427             hid_host_disconnect(hid_host_cid);
428             break;
429         case '\n':
430         case '\r':
431             break;
432         default:
433             show_usage();
434             break;
435     }
436     if (status != ERROR_CODE_SUCCESS){
437         printf("HID host cmd \'%c\' failed, status 0x%02x\n", cmd, status);
438     }
439 }
440 #endif
441 
442 int btstack_main(int argc, const char * argv[]);
443 int btstack_main(int argc, const char * argv[]){
444 
445     (void)argc;
446     (void)argv;
447 
448     hid_host_setup();
449 
450     // parse human readable Bluetooth address
451     sscanf_bd_addr(remote_addr_string, remote_addr);
452 
453 #ifdef HAVE_BTSTACK_STDIN
454     btstack_stdin_setup(stdin_process);
455 #endif
456 
457     // Turn on the device
458     hci_power_control(HCI_POWER_ON);
459     return 0;
460 }
461 
462 /* EXAMPLE_END */
463