xref: /btstack/example/hid_host_demo.c (revision 4930cef6e21e6da2d7571b9259c7f0fb8bed3d01)
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     // 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 void hid_host_handle_interrupt_report(const uint8_t * report, uint16_t report_len){
180     // check if HID Input Report
181     if (report_len < 1) return;
182     if (*report != 0xa1) return;
183 
184     report++;
185     report_len--;
186 
187     btstack_hid_parser_t parser;
188     btstack_hid_parser_init(&parser,
189         hid_descriptor_storage_get_descriptor_data(hid_host_cid),
190         hid_descriptor_storage_get_descriptor_len(hid_host_cid),
191         HID_REPORT_TYPE_INPUT, report, report_len);
192 
193     int shift = 0;
194     uint8_t new_keys[NUM_KEYS];
195     memset(new_keys, 0, sizeof(new_keys));
196     int     new_keys_count = 0;
197     while (btstack_hid_parser_has_more(&parser)){
198         uint16_t usage_page;
199         uint16_t usage;
200         int32_t  value;
201         btstack_hid_parser_get_field(&parser, &usage_page, &usage, &value);
202         if (usage_page != 0x07) continue;
203         switch (usage){
204             case 0xe1:
205             case 0xe6:
206                 if (value){
207                     shift = 1;
208                 }
209                 continue;
210             case 0x00:
211                 continue;
212             default:
213                 break;
214         }
215         if (usage >= sizeof(keytable_us_none)) continue;
216 
217         // store new keys
218         new_keys[new_keys_count++] = (uint8_t) usage;
219 
220         // check if usage was used last time (and ignore in that case)
221         int i;
222         for (i=0;i<NUM_KEYS;i++){
223             if (usage == last_keys[i]){
224                 usage = 0;
225             }
226         }
227         if (usage == 0) continue;
228 
229         uint8_t key;
230         if (shift){
231             key = keytable_us_shift[usage];
232         } else {
233             key = keytable_us_none[usage];
234         }
235         if (key == CHAR_ILLEGAL) continue;
236         if (key == CHAR_BACKSPACE){
237             printf("\b \b");    // go back one char, print space, go back one char again
238             continue;
239         }
240         printf("%c", key);
241     }
242     memcpy(last_keys, new_keys, NUM_KEYS);
243 }
244 
245 /*
246  * @section Packet Handler
247  *
248  * @text The packet handler responds to various HID events.
249  */
250 
251 /* LISTING_START(packetHandler): Packet Handler */
252 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
253 {
254     /* LISTING_PAUSE */
255     UNUSED(channel);
256     UNUSED(size);
257 
258     uint8_t   event;
259     bd_addr_t event_addr;
260     uint8_t   status;
261 
262     /* LISTING_RESUME */
263     switch (packet_type) {
264 		case HCI_EVENT_PACKET:
265             event = hci_event_packet_get_type(packet);
266 
267             switch (event) {
268 #ifndef HAVE_BTSTACK_STDIN
269                 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING
270                  * is received and the example is started in client mode, the remote SDP HID query is started.
271                  */
272                 case BTSTACK_EVENT_STATE:
273                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
274                         status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
275                         if (status != ERROR_CODE_SUCCESS){
276                             printf("HID host connect failed, status 0x%02x.\n", status);
277                         }
278                     }
279                     break;
280 #endif
281                 /* LISTING_PAUSE */
282                 case HCI_EVENT_PIN_CODE_REQUEST:
283 					// inform about pin code request
284                     printf("Pin code request - using '0000'\n");
285                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
286                     gap_pin_code_response(event_addr, "0000");
287 					break;
288 
289                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
290                     // inform about user confirmation request
291                     printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8));
292                     printf("SSP User Confirmation Auto accept\n");
293                     break;
294 
295                 /* LISTING_RESUME */
296                 case HCI_EVENT_HID_META:
297                     switch (hci_event_hid_meta_get_subevent_code(packet)){
298 
299                         case HID_SUBEVENT_INCOMING_CONNECTION:
300                             // There is an incoming connection: we can accept it or decline it.
301                             // The hid_host_report_mode in the hid_host_accept_connection function
302                             // allows the application to request a protocol mode.
303                             // For available protocol modes, see hid_protocol_mode_t in btstack_hid.h file.
304                             hid_host_accept_connection(hid_subevent_incoming_connection_get_hid_cid(packet), hid_host_report_mode);
305                             break;
306 
307                         case HID_SUBEVENT_CONNECTION_OPENED:
308                             // The status field of this event indicates if the control and interrupt
309                             // connections were opened successfully.
310                             status = hid_subevent_connection_opened_get_status(packet);
311                             if (status != ERROR_CODE_SUCCESS) {
312                                 printf("Connection failed, status 0x%x\n", status);
313                                 app_state = APP_IDLE;
314                                 hid_host_cid = 0;
315                                 return;
316                             }
317                             app_state = APP_CONNECTED;
318                             hid_host_descriptor_available = false;
319                             hid_host_cid = hid_subevent_connection_opened_get_hid_cid(packet);
320                             printf("HID Host connected.\n");
321                             break;
322 
323                         case HID_SUBEVENT_DESCRIPTOR_AVAILABLE:
324                             // This event will follows HID_SUBEVENT_CONNECTION_OPENED event.
325                             // For incoming connections, i.e. HID Device initiating the connection,
326                             // the HID_SUBEVENT_DESCRIPTOR_AVAILABLE is delayed, and some HID
327                             // reports may be received via HID_SUBEVENT_REPORT event. It is up to
328                             // the application if these reports should be buffered or ignored until
329                             // the HID descriptor is available.
330                             status = hid_subevent_descriptor_available_get_status(packet);
331                             if (status == ERROR_CODE_SUCCESS){
332                                 hid_host_descriptor_available = true;
333                                 printf("HID Descriptor available, please start typing.\n");
334                             } else {
335                                 printf("Cannot handle input report, HID Descriptor is not available.\n");
336                             }
337                             break;
338 
339                         case HID_SUBEVENT_REPORT:
340                             // Handle input report.
341                             if (hid_host_descriptor_available){
342                                 hid_host_handle_interrupt_report(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
343                             } else {
344                                 printf_hexdump(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
345                             }
346                             break;
347 
348                         case HID_SUBEVENT_SET_PROTOCOL_RESPONSE:
349                             // For incoming connections, the library will set the protocol mode of the
350                             // HID Device as requested in the call to hid_host_accept_connection. The event
351                             // reports the result. For connections initiated by calling hid_host_connect,
352                             // this event will occur only if the established report mode is boot mode.
353                             status = hid_subevent_set_protocol_response_get_handshake_status(packet);
354                             if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
355                                 printf("Error set protocol, status 0x%02x\n", status);
356                                 break;
357                             }
358                             switch ((hid_protocol_mode_t)hid_subevent_set_protocol_response_get_protocol_mode(packet)){
359                                 case HID_PROTOCOL_MODE_BOOT:
360                                     printf("Protocol mode set: BOOT.\n");
361                                     break;
362                                 case HID_PROTOCOL_MODE_REPORT:
363                                     printf("Protocol mode set: REPORT.\n");
364                                     break;
365                                 default:
366                                     printf("Unknown protocol mode.\n");
367                                     break;
368                             }
369                             break;
370 
371                         case HID_SUBEVENT_CONNECTION_CLOSED:
372                             // The connection was closed.
373                             hid_host_cid = 0;
374                             hid_host_descriptor_available = false;
375                             printf("HID Host disconnected.\n");
376                             break;
377 
378                         default:
379                             break;
380                     }
381                     break;
382                 default:
383                     break;
384             }
385             break;
386         default:
387             break;
388     }
389 }
390 /* LISTING_END */
391 
392 #ifdef HAVE_BTSTACK_STDIN
393 static void show_usage(void){
394     bd_addr_t      iut_address;
395     gap_local_bd_addr(iut_address);
396     printf("\n--- Bluetooth HID Host Console %s ---\n", bd_addr_to_str(iut_address));
397     printf("c      - Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string);
398     printf("C      - Disconnect\n");
399 
400     printf("\n");
401     printf("Ctrl-c - exit\n");
402     printf("---\n");
403 }
404 
405 static void stdin_process(char cmd){
406     uint8_t status = ERROR_CODE_SUCCESS;
407     switch (cmd){
408         case 'c':
409             printf("Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string);
410             status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
411             break;
412         case 'C':
413             printf("Disconnect...\n");
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