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