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