xref: /btstack/example/hid_host_demo.c (revision 05439aa6caba9fab55a4dbeb8854ae2692315c16)
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 /* @section Main application configuration
128  *
129  * @text In the application configuration, L2CAP is initialized
130  */
131 
132 /* LISTING_START(PanuSetup): Panu setup */
133 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
134 
135 static void hid_host_setup(void){
136 
137     // Initialize L2CAP
138     l2cap_init();
139 
140     // Initialize HID Host
141     hid_host_init(hid_descriptor, sizeof(hid_descriptor));
142     hid_host_register_packet_handler(packet_handler);
143 
144     // Allow sniff mode requests by HID device and support role switch
145     gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH);
146 
147     // try to become master on incoming connections
148     hci_set_master_slave_policy(HCI_ROLE_MASTER);
149 
150     // register for HCI events
151     hci_event_callback_registration.callback = &packet_handler;
152     hci_add_event_handler(&hci_event_callback_registration);
153 
154     // Disable stdout buffering
155     setbuf(stdout, NULL);
156 }
157 /* LISTING_END */
158 
159 /*
160  * @section HID Report Handler
161  *
162  * @text Use BTstack's compact HID Parser to process incoming HID Report
163  * Iterate over all fields and process fields with usage page = 0x07 / Keyboard
164  * Check if SHIFT is down and process first character (don't handle multiple key presses)
165  *
166  */
167 #define NUM_KEYS 6
168 static uint8_t last_keys[NUM_KEYS];
169 static void hid_host_handle_interrupt_report(const uint8_t * report, uint16_t report_len){
170     // check if HID Input Report
171     if (report_len < 1) return;
172     if (*report != 0xa1) return;
173 
174     report++;
175     report_len--;
176 
177     btstack_hid_parser_t parser;
178     btstack_hid_parser_init(&parser,
179         hid_descriptor_storage_get_descriptor_data(hid_host_cid),
180         hid_descriptor_storage_get_descriptor_len(hid_host_cid),
181         HID_REPORT_TYPE_INPUT, report, report_len);
182 
183     int shift = 0;
184     uint8_t new_keys[NUM_KEYS];
185     memset(new_keys, 0, sizeof(new_keys));
186     int     new_keys_count = 0;
187     while (btstack_hid_parser_has_more(&parser)){
188         uint16_t usage_page;
189         uint16_t usage;
190         int32_t  value;
191         btstack_hid_parser_get_field(&parser, &usage_page, &usage, &value);
192         if (usage_page != 0x07) continue;
193         switch (usage){
194             case 0xe1:
195             case 0xe6:
196                 if (value){
197                     shift = 1;
198                 }
199                 continue;
200             case 0x00:
201                 continue;
202             default:
203                 break;
204         }
205         if (usage >= sizeof(keytable_us_none)) continue;
206 
207         // store new keys
208         new_keys[new_keys_count++] = usage;
209 
210         // check if usage was used last time (and ignore in that case)
211         int i;
212         for (i=0;i<NUM_KEYS;i++){
213             if (usage == last_keys[i]){
214                 usage = 0;
215             }
216         }
217         if (usage == 0) continue;
218 
219         uint8_t key;
220         if (shift){
221             key = keytable_us_shift[usage];
222         } else {
223             key = keytable_us_none[usage];
224         }
225         if (key == CHAR_ILLEGAL) continue;
226         if (key == CHAR_BACKSPACE){
227             printf("\b \b");    // go back one char, print space, go back one char again
228             continue;
229         }
230         printf("%c", key);
231     }
232     memcpy(last_keys, new_keys, NUM_KEYS);
233 }
234 
235 /*
236  * @section Packet Handler
237  *
238  * @text The packet handler responds to various HCI Events.
239  */
240 
241 /* LISTING_START(packetHandler): Packet Handler */
242 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
243 {
244     /* LISTING_PAUSE */
245     UNUSED(channel);
246     UNUSED(size);
247 
248     uint8_t   event;
249     bd_addr_t event_addr;
250     uint8_t   status;
251 
252     /* LISTING_RESUME */
253     switch (packet_type) {
254 		case HCI_EVENT_PACKET:
255             event = hci_event_packet_get_type(packet);
256 
257             switch (event) {
258 #ifndef HAVE_BTSTACK_STDIN
259                 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING
260                  * is received and the example is started in client mode, the remote SDP HID query is started.
261                  */
262                 case BTSTACK_EVENT_STATE:
263                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
264                         status = hid_host_connect(remote_addr, HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT, &hid_host_cid);
265                         if (status != ERROR_CODE_SUCCESS){
266                             printf("HID host connect failed, status 0x%02x\n", status);
267                         }
268                     }
269                     break;
270 #endif
271                 /* LISTING_PAUSE */
272                 case HCI_EVENT_PIN_CODE_REQUEST:
273 					// inform about pin code request
274                     printf("Pin code request - using '0000'\n");
275                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
276                     gap_pin_code_response(event_addr, "0000");
277 					break;
278 
279                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
280                     // inform about user confirmation request
281                     printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8));
282                     printf("SSP User Confirmation Auto accept\n");
283                     break;
284 
285                 /* LISTING_RESUME */
286                 case HCI_EVENT_HID_META:
287                     switch (hci_event_hid_meta_get_subevent_code(packet)){
288                         case HID_SUBEVENT_INCOMING_CONNECTION:
289                             hid_host_accept_connection(hid_subevent_incoming_connection_get_hid_cid(packet), HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT);
290                             break;
291 
292                         case HID_SUBEVENT_CONNECTION_OPENED:
293                             status = hid_subevent_connection_opened_get_status(packet);
294                             if (status) {
295                                 // outgoing connection failed
296                                 printf("Connection failed, status 0x%x\n", status);
297                                 app_state = APP_IDLE;
298                                 hid_host_cid = 0;
299                                 return;
300                             }
301                             app_state = APP_CONNECTED;
302                             hid_host_descriptor_available = false;
303                             hid_host_cid = hid_subevent_connection_opened_get_hid_cid(packet);
304                             printf("HID Host connected...\n");
305                             break;
306 
307                         case HID_SUBEVENT_DESCRIPTOR_AVAILABLE:
308                             status = hid_subevent_descriptor_available_get_status(packet);
309                             if (status == ERROR_CODE_SUCCESS){
310                                 hid_host_descriptor_available = true;
311                             }
312                             break;
313                         case HID_SUBEVENT_CONNECTION_CLOSED:
314                             hid_host_cid = 0;
315                             hid_host_descriptor_available = false;
316                             printf("HID Host disconnected..\n");
317                             break;
318 
319                         case HID_SUBEVENT_GET_REPORT_RESPONSE:
320                             status = hid_subevent_get_report_response_get_handshake_status(packet);
321                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
322                                 printf("Error get report, status 0x%02x\n", status);
323                                 break;
324                             }
325                             printf("Received report[%d]: ", hid_subevent_get_report_response_get_report_len(packet));
326                             printf_hexdump(hid_subevent_get_report_response_get_report(packet), hid_subevent_get_report_response_get_report_len(packet));
327                             printf("\n");
328                             break;
329 
330                         case HID_SUBEVENT_SET_REPORT_RESPONSE:
331                             status = hid_subevent_set_report_response_get_handshake_status(packet);
332                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
333                                 printf("Error set report, status 0x%02x\n", status);
334                                 break;
335                             }
336                             printf("Report set.\n");
337                             break;
338 
339                         case HID_SUBEVENT_GET_PROTOCOL_RESPONSE:
340                             status = hid_subevent_get_protocol_response_get_handshake_status(packet);
341                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
342                                 printf("Error get report, status 0x%02x\n", status);
343                                 break;
344                             }
345                             switch ((hid_protocol_mode_t)hid_subevent_get_protocol_response_get_protocol_mode(packet)){
346                                 case HID_PROTOCOL_MODE_BOOT:
347                                     printf("HID device is in BOOT mode.\n");
348                                     break;
349                                 case HID_PROTOCOL_MODE_REPORT:
350                                     printf("HID device is in REPORT mode.\n");
351                                     break;
352                                 default:
353                                     break;
354                             }
355                             break;
356 
357                         case HID_SUBEVENT_SET_PROTOCOL_RESPONSE:
358                             status = hid_subevent_set_report_response_get_handshake_status(packet);
359                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
360                                 printf("Error set protocol, status 0x%02x\n", status);
361                                 break;
362                             }
363                             printf("Protocol set.\n");
364                             break;
365 
366                         case HID_SUBEVENT_REPORT:
367                             printf("Received input report[%d]: \n", hid_subevent_report_get_report_len(packet));
368                             if (hid_host_descriptor_available){
369                                 hid_host_handle_interrupt_report(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
370                                 printf("\n");
371                             } else {
372                                 printf("Cannot handle input report, HID Descriptor is not available\n");
373                                 printf_hexdump(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
374                             }
375                             break;
376 
377                         default:
378                             break;
379                     }
380                     break;
381                 default:
382                     break;
383             }
384             break;
385         default:
386             break;
387     }
388 }
389 /* LISTING_END */
390 
391 #ifdef HAVE_BTSTACK_STDIN
392 static void show_usage(void){
393     bd_addr_t      iut_address;
394     gap_local_bd_addr(iut_address);
395     printf("\n--- Bluetooth HID Host Test Console %s ---\n", bd_addr_to_str(iut_address));
396     printf("c      - Connect to %s in report mode, with fallback to BOOT mode.\n", remote_addr_string);
397     printf("C      - Disconnect from %s\n", remote_addr_string);
398 
399     printf("\n");
400     printf("Ctrl-c - exit\n");
401     printf("---\n");
402 }
403 
404 static void stdin_process(char cmd){
405     uint8_t status = ERROR_CODE_SUCCESS;
406     switch (cmd){
407         case 'c':
408             printf("Connect to %s in report mode, with fallback to BOOT mode.\n", remote_addr_string);
409             status = hid_host_connect(remote_addr, HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT, &hid_host_cid);
410             break;
411 
412         case 'C':
413             printf("Disconnect from  %s...\n", remote_addr_string);
414             hid_host_disconnect(hid_host_cid);
415             break;
416         case '\n':
417         case '\r':
418             break;
419         default:
420             show_usage();
421             break;
422     }
423     if (status != ERROR_CODE_SUCCESS){
424         printf("HID host cmd \'%c\' failed, status 0x%02x\n", cmd, status);
425     }
426 }
427 #endif
428 
429 int btstack_main(int argc, const char * argv[]);
430 int btstack_main(int argc, const char * argv[]){
431 
432     (void)argc;
433     (void)argv;
434 
435     hid_host_setup();
436 
437     // parse human readable Bluetooth address
438     sscanf_bd_addr(remote_addr_string, remote_addr);
439 
440 #ifdef HAVE_BTSTACK_STDIN
441     btstack_stdin_setup(stdin_process);
442 #endif
443 
444     // Turn on the device
445     hci_power_control(HCI_POWER_ON);
446     return 0;
447 }
448 
449 /* EXAMPLE_END */
450