xref: /btstack/example/hid_host_demo.c (revision 5d4d8cc7b1d35a90bbd6d5ffd2d3050b2bfc861c)
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 BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "hid_host_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 a HID Host. For now, it connects to a fixed device.
47  * It will connect in Report protocol mode if this mode is supported by the HID Device,
48  * otherwise it will fall back to BOOT protocol mode.
49  */
50 
51 #include <inttypes.h>
52 #include <stdio.h>
53 
54 #include "btstack_config.h"
55 #include "btstack.h"
56 
57 #define MAX_ATTRIBUTE_VALUE_SIZE 300
58 
59 static const char * remote_addr_string = "00:1A:7D:DA:71:01";
60 
61 static bd_addr_t remote_addr;
62 
63 static btstack_packet_callback_registration_t hci_event_callback_registration;
64 
65 // Simplified US Keyboard with Shift modifier
66 
67 #define CHAR_ILLEGAL     0xff
68 #define CHAR_RETURN     '\n'
69 #define CHAR_ESCAPE      27
70 #define CHAR_TAB         '\t'
71 #define CHAR_BACKSPACE   0x7f
72 
73 /**
74  * English (US)
75  */
76 static const uint8_t keytable_us_none [] = {
77     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*   0-3 */
78     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                   /*  4-13 */
79     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',                   /* 14-23 */
80     'u', 'v', 'w', 'x', 'y', 'z',                                       /* 24-29 */
81     '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',                   /* 30-39 */
82     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
83     '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',',       /* 45-54 */
84     '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
85     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
86     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
87     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
88     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
89     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
90     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
91     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
92     '6', '7', '8', '9', '0', '.', 0xa7,                                 /* 97-100 */
93 };
94 
95 static const uint8_t keytable_us_shift[] = {
96     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*  0-3  */
97     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',                   /*  4-13 */
98     'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',                   /* 14-23 */
99     'U', 'V', 'W', 'X', 'Y', 'Z',                                       /* 24-29 */
100     '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',                   /* 30-39 */
101     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
102     '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<',         /* 45-54 */
103     '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
104     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
105     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
106     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
107     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
108     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
109     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
110     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
111     '6', '7', '8', '9', '0', '.', 0xb1,                                 /* 97-100 */
112 };
113 
114 // SDP
115 static uint8_t hid_descriptor_storage[MAX_ATTRIBUTE_VALUE_SIZE];
116 
117 // App
118 static enum {
119     APP_IDLE,
120     APP_CONNECTED
121 } app_state = APP_IDLE;
122 
123 static uint16_t hid_host_cid = 0;
124 static bool     hid_host_descriptor_available = false;
125 static hid_protocol_mode_t hid_host_report_mode = HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT;
126 
127 /* @section Main application configuration
128  *
129  * @text In the application configuration, L2CAP and HID host are initialized, and the link policies
130  * are set to allow sniff mode and role change.
131  */
132 
133 /* LISTING_START(PanuSetup): Panu setup */
134 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
135 
hid_host_setup(void)136 static void hid_host_setup(void){
137 
138     // Initialize L2CAP
139     l2cap_init();
140 
141 #ifdef ENABLE_BLE
142     // Initialize LE Security Manager. Needed for cross-transport key derivation
143     sm_init();
144 #endif
145 
146     // Initialize HID Host
147     hid_host_init(hid_descriptor_storage, sizeof(hid_descriptor_storage));
148     hid_host_register_packet_handler(packet_handler);
149 
150     // Allow sniff mode requests by HID device and support role switch
151     gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH);
152 
153     // try to become master on incoming connections
154     hci_set_master_slave_policy(HCI_ROLE_MASTER);
155 
156     // register for HCI events
157     hci_event_callback_registration.callback = &packet_handler;
158     hci_add_event_handler(&hci_event_callback_registration);
159 
160     // make discoverable to allow HID device to initiate connection
161     gap_discoverable_control(1);
162 
163     // Disable stdout buffering
164     setvbuf(stdin, NULL, _IONBF, 0);
165 }
166 /* LISTING_END */
167 
168 /*
169  * @section HID Report Handler
170  *
171  * @text Use BTstack's compact HID Parser to process incoming HID Report in Report protocol mode.
172  * Iterate over all fields and process fields with usage page = 0x07 / Keyboard
173  * Check if SHIFT is down and process first character (don't handle multiple key presses)
174  *
175  */
176 
177 #define NUM_KEYS 6
178 static uint8_t last_keys[NUM_KEYS];
179 static bool hid_host_caps_lock;
180 
181 static uint16_t hid_host_led_report_id;
182 static uint8_t  hid_host_led_report_len;
183 static uint8_t  hid_host_led_caps_lock_bit;
184 
hid_host_set_leds(void)185 static void hid_host_set_leds(void){
186     if (hid_host_led_report_len == 0) return;
187 
188     uint8_t output_report[8];
189 
190     uint8_t caps_lock_report_offset = hid_host_led_caps_lock_bit >> 3;
191     if (caps_lock_report_offset >= sizeof(output_report)) return;
192 
193     memset(output_report, 0, sizeof(output_report));
194     if (hid_host_caps_lock){
195         output_report[caps_lock_report_offset] = 1 << (hid_host_led_caps_lock_bit & 0x07);
196     }
197     hid_host_send_set_report(hid_host_cid, HID_REPORT_TYPE_OUTPUT, hid_host_led_report_id, output_report, hid_host_led_report_len);
198 }
199 
hid_host_demo_lookup_caps_lock_led(void)200 static void hid_host_demo_lookup_caps_lock_led(void){
201     btstack_hid_usage_iterator_t iterator;
202     const uint8_t *hid_descriptor = hid_descriptor_storage_get_descriptor_data(hid_host_cid);
203     const uint16_t hid_descriptor_len = hid_descriptor_storage_get_descriptor_len(hid_host_cid);
204     btstack_hid_usage_iterator_init(&iterator, hid_descriptor, hid_descriptor_len, HID_REPORT_TYPE_OUTPUT);
205     while (btstack_hid_usage_iterator_has_more(&iterator)){
206         btstack_hid_usage_item_t item;
207         btstack_hid_usage_iterator_get_item(&iterator, &item);
208         if (item.usage_page == HID_USAGE_PAGE_LED && item.usage == HID_USAGE_LED_CAPS_LOCK){
209             hid_host_led_report_id     = item.report_id;
210             hid_host_led_report_len    = btstack_hid_get_report_size_for_id(hid_host_led_report_id, HID_REPORT_TYPE_OUTPUT, hid_descriptor, hid_descriptor_len);
211             hid_host_led_caps_lock_bit = (uint8_t) item.bit_pos;
212             printf("Found CAPS LOCK in Output Report with ID 0x%04x at bit %3u\n", hid_host_led_report_id, hid_host_led_caps_lock_bit);
213         }
214     }
215 }
216 
hid_host_handle_interrupt_report(const uint8_t * report,uint16_t report_len)217 static void hid_host_handle_interrupt_report(const uint8_t * report, uint16_t report_len){
218     // check if HID Input Report
219     if (report_len < 1) return;
220     if (*report != 0xa1) return;
221 
222     report++;
223     report_len--;
224 
225     btstack_hid_parser_t parser;
226     btstack_hid_parser_init(&parser,
227         hid_descriptor_storage_get_descriptor_data(hid_host_cid),
228         hid_descriptor_storage_get_descriptor_len(hid_host_cid),
229         HID_REPORT_TYPE_INPUT, report, report_len);
230 
231     bool shift = hid_host_caps_lock;
232     uint8_t new_keys[NUM_KEYS];
233     memset(new_keys, 0, sizeof(new_keys));
234     int     new_keys_count = 0;
235 
236     while (btstack_hid_parser_has_more(&parser)){
237         uint16_t usage_page;
238         uint16_t usage;
239         int32_t  value;
240         btstack_hid_parser_get_field(&parser, &usage_page, &usage, &value);
241         if (usage_page != 0x07) continue;
242         switch (usage){
243             case HID_USAGE_KEY_KEYBOARD_CAPS_LOCK:
244                 // Toggle Caps Lock
245                 hid_host_caps_lock = !hid_host_caps_lock;
246                 // update LEDs
247                 hid_host_set_leds();
248                 break;
249             case HID_USAGE_KEY_KEYBOARD_LEFTSHIFT:
250             case HID_USAGE_KEY_KEYBOARD_RIGHTSHIFT:
251                 if (value){
252                     shift = 1;
253                 }
254                 continue;
255             case HID_USAGE_KEY_RESERVED:
256                 continue;
257             default:
258                 break;
259         }
260         if (usage >= sizeof(keytable_us_none)) continue;
261 
262         // store new keys
263         new_keys[new_keys_count++] = (uint8_t) usage;
264 
265         // check if usage was used last time (and ignore in that case)
266         int i;
267         for (i=0;i<NUM_KEYS;i++){
268             if (usage == last_keys[i]){
269                 usage = 0;
270             }
271         }
272         if (usage == 0) continue;
273 
274         uint8_t key;
275         if (shift){
276             key = keytable_us_shift[usage];
277         } else {
278             key = keytable_us_none[usage];
279         }
280         if (key == CHAR_ILLEGAL) continue;
281         if (key == CHAR_BACKSPACE){
282             printf("\b \b");    // go back one char, print space, go back one char again
283             continue;
284         }
285         printf("%c", key);
286         fflush(stdout);
287     }
288     memcpy(last_keys, new_keys, NUM_KEYS);
289 }
290 
291 /*
292  * @section Packet Handler
293  *
294  * @text The packet handler responds to various HID events.
295  */
296 
297 /* LISTING_START(packetHandler): Packet Handler */
packet_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)298 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
299 {
300     /* LISTING_PAUSE */
301     UNUSED(channel);
302     UNUSED(size);
303 
304     uint8_t   event;
305     bd_addr_t event_addr;
306     uint8_t   status;
307 
308     /* LISTING_RESUME */
309     switch (packet_type) {
310 		case HCI_EVENT_PACKET:
311             event = hci_event_packet_get_type(packet);
312 
313             switch (event) {
314 #ifndef HAVE_BTSTACK_STDIN
315                 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING
316                  * is received and the example is started in client mode, the remote SDP HID query is started.
317                  */
318                 case BTSTACK_EVENT_STATE:
319                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
320                         status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
321                         if (status != ERROR_CODE_SUCCESS){
322                             printf("HID host connect failed, status 0x%02x.\n", status);
323                         }
324                     }
325                     break;
326 #endif
327                 /* LISTING_PAUSE */
328                 case HCI_EVENT_PIN_CODE_REQUEST:
329 					// inform about pin code request
330                     printf("Pin code request - using '0000'\n");
331                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
332                     gap_pin_code_response(event_addr, "0000");
333 					break;
334 
335                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
336                     // inform about user confirmation request
337                     printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8));
338                     printf("SSP User Confirmation Auto accept\n");
339                     break;
340 
341                 /* LISTING_RESUME */
342                 case HCI_EVENT_HID_META:
343                     switch (hci_event_hid_meta_get_subevent_code(packet)){
344 
345                         case HID_SUBEVENT_INCOMING_CONNECTION:
346                             // There is an incoming connection: we can accept it or decline it.
347                             // The hid_host_report_mode in the hid_host_accept_connection function
348                             // allows the application to request a protocol mode.
349                             // For available protocol modes, see hid_protocol_mode_t in btstack_hid.h file.
350                             hid_host_accept_connection(hid_subevent_incoming_connection_get_hid_cid(packet), hid_host_report_mode);
351                             break;
352 
353                         case HID_SUBEVENT_CONNECTION_OPENED:
354                             // The status field of this event indicates if the control and interrupt
355                             // connections were opened successfully.
356                             status = hid_subevent_connection_opened_get_status(packet);
357                             if (status != ERROR_CODE_SUCCESS) {
358                                 printf("Connection failed, status 0x%02x\n", status);
359                                 app_state = APP_IDLE;
360                                 hid_host_cid = 0;
361                                 return;
362                             }
363                             app_state = APP_CONNECTED;
364                             hid_host_descriptor_available = false;
365                             hid_host_cid = hid_subevent_connection_opened_get_hid_cid(packet);
366                             hid_host_caps_lock = false;
367                             hid_host_led_report_len = 0;
368                             printf("HID Host connected.\n");
369                             break;
370 
371                         case HID_SUBEVENT_DESCRIPTOR_AVAILABLE:
372                             // This event will follows HID_SUBEVENT_CONNECTION_OPENED event.
373                             // For incoming connections, i.e. HID Device initiating the connection,
374                             // the HID_SUBEVENT_DESCRIPTOR_AVAILABLE is delayed, and some HID
375                             // reports may be received via HID_SUBEVENT_REPORT event. It is up to
376                             // the application if these reports should be buffered or ignored until
377                             // the HID descriptor is available.
378                             status = hid_subevent_descriptor_available_get_status(packet);
379                             if (status == ERROR_CODE_SUCCESS){
380                                 hid_host_descriptor_available = true;
381                                 printf("HID Descriptor available, please start typing.\n");
382                                 hid_host_demo_lookup_caps_lock_led();
383                             } else {
384                                 printf("Cannot handle input report, HID Descriptor is not available, status 0x%02x\n", status);
385                             }
386                             break;
387 
388                         case HID_SUBEVENT_REPORT:
389                             // Handle input report.
390                             if (hid_host_descriptor_available){
391                                 hid_host_handle_interrupt_report(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
392                             } else {
393                                 printf_hexdump(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
394                             }
395                             break;
396 
397                         case HID_SUBEVENT_SET_PROTOCOL_RESPONSE:
398                             // For incoming connections, the library will set the protocol mode of the
399                             // HID Device as requested in the call to hid_host_accept_connection. The event
400                             // reports the result. For connections initiated by calling hid_host_connect,
401                             // this event will occur only if the established report mode is boot mode.
402                             status = hid_subevent_set_protocol_response_get_handshake_status(packet);
403                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
404                                 printf("Error set protocol, status 0x%02x\n", status);
405                                 break;
406                             }
407                             switch ((hid_protocol_mode_t)hid_subevent_set_protocol_response_get_protocol_mode(packet)){
408                                 case HID_PROTOCOL_MODE_BOOT:
409                                     printf("Protocol mode set: BOOT.\n");
410                                     break;
411                                 case HID_PROTOCOL_MODE_REPORT:
412                                     printf("Protocol mode set: REPORT.\n");
413                                     break;
414                                 default:
415                                     printf("Unknown protocol mode.\n");
416                                     break;
417                             }
418                             break;
419 
420                         case HID_SUBEVENT_CONNECTION_CLOSED:
421                             // The connection was closed.
422                             hid_host_cid = 0;
423                             hid_host_descriptor_available = false;
424                             printf("HID Host disconnected.\n");
425                             break;
426 
427                         default:
428                             break;
429                     }
430                     break;
431                 default:
432                     break;
433             }
434             break;
435         default:
436             break;
437     }
438 }
439 /* LISTING_END */
440 
441 #ifdef HAVE_BTSTACK_STDIN
show_usage(void)442 static void show_usage(void){
443     bd_addr_t      iut_address;
444     gap_local_bd_addr(iut_address);
445     printf("\n--- Bluetooth HID Host Console %s ---\n", bd_addr_to_str(iut_address));
446     printf("c      - Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string);
447     printf("C      - Disconnect\n");
448 
449     printf("\n");
450     printf("Ctrl-c - exit\n");
451     printf("---\n");
452 }
453 
stdin_process(char cmd)454 static void stdin_process(char cmd){
455     uint8_t status = ERROR_CODE_SUCCESS;
456     switch (cmd){
457         case 'c':
458             printf("Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string);
459             status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
460             break;
461         case 'C':
462             printf("Disconnect...\n");
463             hid_host_disconnect(hid_host_cid);
464             break;
465         case '\n':
466         case '\r':
467             break;
468         default:
469             show_usage();
470             break;
471     }
472     if (status != ERROR_CODE_SUCCESS){
473         printf("HID host cmd \'%c\' failed, status 0x%02x\n", cmd, status);
474     }
475 }
476 #endif
477 
478 int btstack_main(int argc, const char * argv[]);
btstack_main(int argc,const char * argv[])479 int btstack_main(int argc, const char * argv[]){
480 
481     (void)argc;
482     (void)argv;
483 
484     hid_host_setup();
485 
486     // parse human readable Bluetooth address
487     sscanf_bd_addr(remote_addr_string, remote_addr);
488 
489 #ifdef HAVE_BTSTACK_STDIN
490     btstack_stdin_setup(stdin_process);
491 #endif
492 
493     // Turn on the device
494     hci_power_control(HCI_POWER_ON);
495     return 0;
496 }
497 
498 /* EXAMPLE_END */
499