xref: /btstack/example/hid_host_demo.c (revision 6897da5c53aac5b1f90f41b5b15d0bd43d61dfff)
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 
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 
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 
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 
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     }
287     memcpy(last_keys, new_keys, NUM_KEYS);
288 }
289 
290 /*
291  * @section Packet Handler
292  *
293  * @text The packet handler responds to various HID events.
294  */
295 
296 /* LISTING_START(packetHandler): Packet Handler */
297 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
298 {
299     /* LISTING_PAUSE */
300     UNUSED(channel);
301     UNUSED(size);
302 
303     uint8_t   event;
304     bd_addr_t event_addr;
305     uint8_t   status;
306 
307     /* LISTING_RESUME */
308     switch (packet_type) {
309 		case HCI_EVENT_PACKET:
310             event = hci_event_packet_get_type(packet);
311 
312             switch (event) {
313 #ifndef HAVE_BTSTACK_STDIN
314                 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING
315                  * is received and the example is started in client mode, the remote SDP HID query is started.
316                  */
317                 case BTSTACK_EVENT_STATE:
318                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
319                         status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
320                         if (status != ERROR_CODE_SUCCESS){
321                             printf("HID host connect failed, status 0x%02x.\n", status);
322                         }
323                     }
324                     break;
325 #endif
326                 /* LISTING_PAUSE */
327                 case HCI_EVENT_PIN_CODE_REQUEST:
328 					// inform about pin code request
329                     printf("Pin code request - using '0000'\n");
330                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
331                     gap_pin_code_response(event_addr, "0000");
332 					break;
333 
334                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
335                     // inform about user confirmation request
336                     printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8));
337                     printf("SSP User Confirmation Auto accept\n");
338                     break;
339 
340                 /* LISTING_RESUME */
341                 case HCI_EVENT_HID_META:
342                     switch (hci_event_hid_meta_get_subevent_code(packet)){
343 
344                         case HID_SUBEVENT_INCOMING_CONNECTION:
345                             // There is an incoming connection: we can accept it or decline it.
346                             // The hid_host_report_mode in the hid_host_accept_connection function
347                             // allows the application to request a protocol mode.
348                             // For available protocol modes, see hid_protocol_mode_t in btstack_hid.h file.
349                             hid_host_accept_connection(hid_subevent_incoming_connection_get_hid_cid(packet), hid_host_report_mode);
350                             break;
351 
352                         case HID_SUBEVENT_CONNECTION_OPENED:
353                             // The status field of this event indicates if the control and interrupt
354                             // connections were opened successfully.
355                             status = hid_subevent_connection_opened_get_status(packet);
356                             if (status != ERROR_CODE_SUCCESS) {
357                                 printf("Connection failed, status 0x%02x\n", status);
358                                 app_state = APP_IDLE;
359                                 hid_host_cid = 0;
360                                 return;
361                             }
362                             app_state = APP_CONNECTED;
363                             hid_host_descriptor_available = false;
364                             hid_host_cid = hid_subevent_connection_opened_get_hid_cid(packet);
365                             hid_host_caps_lock = false;
366                             hid_host_led_report_len = 0;
367                             printf("HID Host connected.\n");
368                             break;
369 
370                         case HID_SUBEVENT_DESCRIPTOR_AVAILABLE:
371                             // This event will follows HID_SUBEVENT_CONNECTION_OPENED event.
372                             // For incoming connections, i.e. HID Device initiating the connection,
373                             // the HID_SUBEVENT_DESCRIPTOR_AVAILABLE is delayed, and some HID
374                             // reports may be received via HID_SUBEVENT_REPORT event. It is up to
375                             // the application if these reports should be buffered or ignored until
376                             // the HID descriptor is available.
377                             status = hid_subevent_descriptor_available_get_status(packet);
378                             if (status == ERROR_CODE_SUCCESS){
379                                 hid_host_descriptor_available = true;
380                                 printf("HID Descriptor available, please start typing.\n");
381                                 hid_host_demo_lookup_caps_lock_led();
382                             } else {
383                                 printf("Cannot handle input report, HID Descriptor is not available, status 0x%02x\n", status);
384                             }
385                             break;
386 
387                         case HID_SUBEVENT_REPORT:
388                             // Handle input report.
389                             if (hid_host_descriptor_available){
390                                 hid_host_handle_interrupt_report(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
391                             } else {
392                                 printf_hexdump(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
393                             }
394                             break;
395 
396                         case HID_SUBEVENT_SET_PROTOCOL_RESPONSE:
397                             // For incoming connections, the library will set the protocol mode of the
398                             // HID Device as requested in the call to hid_host_accept_connection. The event
399                             // reports the result. For connections initiated by calling hid_host_connect,
400                             // this event will occur only if the established report mode is boot mode.
401                             status = hid_subevent_set_protocol_response_get_handshake_status(packet);
402                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
403                                 printf("Error set protocol, status 0x%02x\n", status);
404                                 break;
405                             }
406                             switch ((hid_protocol_mode_t)hid_subevent_set_protocol_response_get_protocol_mode(packet)){
407                                 case HID_PROTOCOL_MODE_BOOT:
408                                     printf("Protocol mode set: BOOT.\n");
409                                     break;
410                                 case HID_PROTOCOL_MODE_REPORT:
411                                     printf("Protocol mode set: REPORT.\n");
412                                     break;
413                                 default:
414                                     printf("Unknown protocol mode.\n");
415                                     break;
416                             }
417                             break;
418 
419                         case HID_SUBEVENT_CONNECTION_CLOSED:
420                             // The connection was closed.
421                             hid_host_cid = 0;
422                             hid_host_descriptor_available = false;
423                             printf("HID Host disconnected.\n");
424                             break;
425 
426                         default:
427                             break;
428                     }
429                     break;
430                 default:
431                     break;
432             }
433             break;
434         default:
435             break;
436     }
437 }
438 /* LISTING_END */
439 
440 #ifdef HAVE_BTSTACK_STDIN
441 static void show_usage(void){
442     bd_addr_t      iut_address;
443     gap_local_bd_addr(iut_address);
444     printf("\n--- Bluetooth HID Host Console %s ---\n", bd_addr_to_str(iut_address));
445     printf("c      - Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string);
446     printf("C      - Disconnect\n");
447 
448     printf("\n");
449     printf("Ctrl-c - exit\n");
450     printf("---\n");
451 }
452 
453 static void stdin_process(char cmd){
454     uint8_t status = ERROR_CODE_SUCCESS;
455     switch (cmd){
456         case 'c':
457             printf("Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string);
458             status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
459             break;
460         case 'C':
461             printf("Disconnect...\n");
462             hid_host_disconnect(hid_host_cid);
463             break;
464         case '\n':
465         case '\r':
466             break;
467         default:
468             show_usage();
469             break;
470     }
471     if (status != ERROR_CODE_SUCCESS){
472         printf("HID host cmd \'%c\' failed, status 0x%02x\n", cmd, status);
473     }
474 }
475 #endif
476 
477 int btstack_main(int argc, const char * argv[]);
478 int btstack_main(int argc, const char * argv[]){
479 
480     (void)argc;
481     (void)argv;
482 
483     hid_host_setup();
484 
485     // parse human readable Bluetooth address
486     sscanf_bd_addr(remote_addr_string, remote_addr);
487 
488 #ifdef HAVE_BTSTACK_STDIN
489     btstack_stdin_setup(stdin_process);
490 #endif
491 
492     // Turn on the device
493     hci_power_control(HCI_POWER_ON);
494     return 0;
495 }
496 
497 /* EXAMPLE_END */
498