xref: /btstack/example/hid_keyboard_demo.c (revision 1ad99f3bd30dfda1f1d3c25ba34069bcf3cdff8c)
1 /*
2  * Copyright (C) 2014 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_keyboard_demo.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(hid_keyboard_demo): HID Keyboard Classic
42  *
43  * @text This HID Device example demonstrates how to implement
44  * an HID keyboard. Without a HAVE_BTSTACK_STDIN, a fixed demo text is sent
45  * If HAVE_BTSTACK_STDIN is defined, you can type from the terminal
46  *
47  * @text Status: Basic implementation. HID Request from Host are not answered yet. Works with iOS.
48  */
49 // *****************************************************************************
50 
51 
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <inttypes.h>
57 
58 #include "btstack.h"
59 
60 #ifdef HAVE_BTSTACK_STDIN
61 #include "btstack_stdin.h"
62 #endif
63 
64 // to enable demo text on POSIX systems
65 // #undef HAVE_BTSTACK_STDIN
66 
67 // from USB HID Specification 1.1, Appendix B.1
68 const uint8_t hid_descriptor_keyboard_boot_mode[] = {
69 
70     0x05, 0x01,                    // Usage Page (Generic Desktop)
71     0x09, 0x06,                    // Usage (Keyboard)
72     0xa1, 0x01,                    // Collection (Application)
73 
74     // Modifier byte
75 
76     0x75, 0x01,                    //   Report Size (1)
77     0x95, 0x08,                    //   Report Count (8)
78     0x05, 0x07,                    //   Usage Page (Key codes)
79     0x19, 0xe0,                    //   Usage Minimum (Keyboard LeftControl)
80     0x29, 0xe7,                    //   Usage Maxium (Keyboard Right GUI)
81     0x15, 0x00,                    //   Logical Minimum (0)
82     0x25, 0x01,                    //   Logical Maximum (1)
83     0x81, 0x02,                    //   Input (Data, Variable, Absolute)
84 
85     // Reserved byte
86 
87     0x75, 0x01,                    //   Report Size (1)
88     0x95, 0x08,                    //   Report Count (8)
89     0x81, 0x03,                    //   Input (Constant, Variable, Absolute)
90 
91     // LED report + padding
92 
93     0x95, 0x05,                    //   Report Count (5)
94     0x75, 0x01,                    //   Report Size (1)
95     0x05, 0x08,                    //   Usage Page (LEDs)
96     0x19, 0x01,                    //   Usage Minimum (Num Lock)
97     0x29, 0x05,                    //   Usage Maxium (Kana)
98     0x91, 0x02,                    //   Output (Data, Variable, Absolute)
99 
100     0x95, 0x01,                    //   Report Count (1)
101     0x75, 0x03,                    //   Report Size (3)
102     0x91, 0x03,                    //   Output (Constant, Variable, Absolute)
103 
104     // Keycodes
105 
106     0x95, 0x06,                    //   Report Count (6)
107     0x75, 0x08,                    //   Report Size (8)
108     0x15, 0x00,                    //   Logical Minimum (0)
109     0x25, 0xff,                    //   Logical Maximum (1)
110     0x05, 0x07,                    //   Usage Page (Key codes)
111     0x19, 0x00,                    //   Usage Minimum (Reserved (no event indicated))
112     0x29, 0xff,                    //   Usage Maxium (Reserved)
113     0x81, 0x00,                    //   Input (Data, Array)
114 
115     0xc0,                          // End collection
116 };
117 
118 //
119 #define CHAR_ILLEGAL     0xff
120 #define CHAR_RETURN     '\n'
121 #define CHAR_ESCAPE      27
122 #define CHAR_TAB         '\t'
123 #define CHAR_BACKSPACE   0x7f
124 
125 // Simplified US Keyboard with Shift modifier
126 
127 /**
128  * English (US)
129  */
130 static const uint8_t keytable_us_none [] = {
131     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*   0-3 */
132     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                   /*  4-13 */
133     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',                   /* 14-23 */
134     'u', 'v', 'w', 'x', 'y', 'z',                                       /* 24-29 */
135     '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',                   /* 30-39 */
136     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
137     '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',',       /* 45-54 */
138     '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
139     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
140     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
141     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
142     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
143     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
144     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
145     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
146     '6', '7', '8', '9', '0', '.', 0xa7,                                 /* 97-100 */
147 };
148 
149 static const uint8_t keytable_us_shift[] = {
150     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*  0-3  */
151     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',                   /*  4-13 */
152     'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',                   /* 14-23 */
153     'U', 'V', 'W', 'X', 'Y', 'Z',                                       /* 24-29 */
154     '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',                   /* 30-39 */
155     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
156     '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<',         /* 45-54 */
157     '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
158     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
159     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
160     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
161     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
162     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
163     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
164     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
165     '6', '7', '8', '9', '0', '.', 0xb1,                                 /* 97-100 */
166 };
167 
168 // STATE
169 
170 static uint8_t hid_service_buffer[250];
171 static uint8_t device_id_sdp_service_buffer[100];
172 static const char hid_device_name[] = "BTstack HID Keyboard";
173 static btstack_packet_callback_registration_t hci_event_callback_registration;
174 static uint16_t hid_cid;
175 static bd_addr_t device_addr;
176 static uint8_t hid_boot_device = 0;
177 
178 #ifdef HAVE_BTSTACK_STDIN
179 static const char * device_addr_string = "BC:EC:5D:E6:15:03";
180 #endif
181 
182 static enum {
183     APP_BOOTING,
184     APP_NOT_CONNECTED,
185     APP_CONNECTING,
186     APP_CONNECTED
187 } app_state = APP_BOOTING;
188 
189 // HID Keyboard lookup
190 static int lookup_keycode(uint8_t character, const uint8_t * table, int size, uint8_t * keycode){
191     int i;
192     for (i=0;i<size;i++){
193         if (table[i] != character) continue;
194         *keycode = i;
195         return 1;
196     }
197     return 0;
198 }
199 
200 static int keycode_and_modifer_us_for_character(uint8_t character, uint8_t * keycode, uint8_t * modifier){
201     int found;
202     found = lookup_keycode(character, keytable_us_none, sizeof(keytable_us_none), keycode);
203     if (found) {
204         *modifier = 0;  // none
205         return 1;
206     }
207     found = lookup_keycode(character, keytable_us_shift, sizeof(keytable_us_shift), keycode);
208     if (found) {
209         *modifier = 2;  // shift
210         return 1;
211     }
212     return 0;
213 }
214 
215 // HID Report sending
216 static int send_keycode;
217 static int send_modifier;
218 
219 static void send_key(int modifier, int keycode){
220     send_keycode = keycode;
221     send_modifier = modifier;
222     hid_device_request_can_send_now_event(hid_cid);
223 }
224 
225 static void send_report(int modifier, int keycode){
226     uint8_t report[] = { 0xa1, modifier, 0, 0, keycode, 0, 0, 0, 0, 0};
227     hid_device_send_interrupt_message(hid_cid, &report[0], sizeof(report));
228 }
229 
230 // Demo Application
231 
232 #ifdef HAVE_BTSTACK_STDIN
233 
234 // On systems with STDIN, we can directly type on the console
235 
236 static void stdin_process(char character){
237     uint8_t modifier;
238     uint8_t keycode;
239     int found;
240 
241     switch (app_state){
242         case APP_BOOTING:
243         case APP_CONNECTING:
244             // ignore
245             break;
246 
247         case APP_CONNECTED:
248             // send keyu
249             found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
250             if (found){
251                 send_key(modifier, keycode);
252                 return;
253             }
254             break;
255         case APP_NOT_CONNECTED:
256             printf("Connecting to %s...\n", bd_addr_to_str(device_addr));
257             hid_device_connect(device_addr, &hid_cid);
258             break;
259         default:
260             btstack_assert(false);
261             break;
262     }
263 }
264 #else
265 
266 // On embedded systems, send constant demo text with fixed period
267 
268 #define TYPING_PERIOD_MS 100
269 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n";
270 
271 static int demo_pos;
272 static btstack_timer_source_t typing_timer;
273 
274 static void typing_timer_handler(btstack_timer_source_t * ts){
275 
276     // abort if not connected
277     if (!hid_cid) return;
278 
279     // get next character
280     uint8_t character = demo_text[demo_pos++];
281     if (demo_text[demo_pos] == 0){
282         demo_pos = 0;
283     }
284 
285     // get keycodeand send
286     uint8_t modifier;
287     uint8_t keycode;
288     int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
289     if (found){
290         send_key(modifier, keycode);
291     }
292 
293     // set next timer
294     btstack_run_loop_set_timer(ts, TYPING_PERIOD_MS);
295     btstack_run_loop_add_timer(ts);
296 }
297 
298 static void hid_embedded_start_typing(void){
299     demo_pos = 0;
300     // set one-shot timer
301     typing_timer.process = &typing_timer_handler;
302     btstack_run_loop_set_timer(&typing_timer, TYPING_PERIOD_MS);
303     btstack_run_loop_add_timer(&typing_timer);
304 }
305 
306 #endif
307 
308 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t packet_size){
309     UNUSED(channel);
310     UNUSED(packet_size);
311     uint8_t status;
312     switch (packet_type){
313         case HCI_EVENT_PACKET:
314             switch (packet[0]){
315                 case BTSTACK_EVENT_STATE:
316                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
317                     app_state = APP_NOT_CONNECTED;
318                     break;
319 
320                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
321                     // ssp: inform about user confirmation request
322                     log_info("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", hci_event_user_confirmation_request_get_numeric_value(packet));
323                     log_info("SSP User Confirmation Auto accept\n");
324                     break;
325 
326                 case HCI_EVENT_HID_META:
327                     switch (hci_event_hid_meta_get_subevent_code(packet)){
328                         case HID_SUBEVENT_CONNECTION_OPENED:
329                             status = hid_subevent_connection_opened_get_status(packet);
330                             if (status) {
331                                 // outgoing connection failed
332                                 printf("Connection failed, status 0x%x\n", status);
333                                 app_state = APP_NOT_CONNECTED;
334                                 hid_cid = 0;
335                                 return;
336                             }
337                             app_state = APP_CONNECTED;
338                             hid_cid = hid_subevent_connection_opened_get_hid_cid(packet);
339 #ifdef HAVE_BTSTACK_STDIN
340                             printf("HID Connected, please start typing...\n");
341 #else
342                             printf("HID Connected, sending demo text...\n");
343                             hid_embedded_start_typing();
344 #endif
345                             break;
346                         case HID_SUBEVENT_CONNECTION_CLOSED:
347                             printf("HID Disconnected\n");
348                             app_state = APP_NOT_CONNECTED;
349                             hid_cid = 0;
350                             break;
351                         case HID_SUBEVENT_CAN_SEND_NOW:
352                             if (send_keycode){
353                                 send_report(send_modifier, send_keycode);
354                                 send_keycode = 0;
355                                 send_modifier = 0;
356                                 hid_device_request_can_send_now_event(hid_cid);
357                             } else {
358                                 send_report(0, 0);
359                             }
360                             break;
361                         default:
362                             break;
363                     }
364                     break;
365                 default:
366                     break;
367             }
368             break;
369         default:
370             break;
371     }
372 }
373 
374 /* @section Main Application Setup
375  *
376  * @text Listing MainConfiguration shows main application code.
377  * To run a HID Device service you need to initialize the SDP, and to create and register HID Device record with it.
378  * At the end the Bluetooth stack is started.
379  */
380 
381 /* LISTING_START(MainConfiguration): Setup HID Device */
382 
383 int btstack_main(int argc, const char * argv[]);
384 int btstack_main(int argc, const char * argv[]){
385     (void)argc;
386     (void)argv;
387 
388     // allow to get found by inquiry
389     gap_discoverable_control(1);
390     // use Limited Discoverable Mode; Peripheral; Keyboard as CoD
391     gap_set_class_of_device(0x2540);
392     // set local name to be identified - zeroes will be replaced by actual BD ADDR
393     gap_set_local_name("HID Keyboard Demo 00:00:00:00:00:00");
394     // allow for role switch in general and sniff mode
395     gap_set_default_link_policy_settings( LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE );
396     // allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it
397     gap_set_allow_role_switch(true);
398 
399     // L2CAP
400     l2cap_init();
401 
402     // SDP Server
403     sdp_init();
404     memset(hid_service_buffer, 0, sizeof(hid_service_buffer));
405 
406     uint8_t hid_virtual_cable = 0;
407     uint8_t hid_remote_wake = 1;
408     uint8_t hid_reconnect_initiate = 1;
409 
410     // hid sevice subclass 2540 Keyboard, hid counntry code 33 US, hid virtual cable off, hid reconnect initiate off, hid boot device off
411     hid_create_sdp_record(hid_service_buffer, 0x10001, 0x2540, 33,
412         hid_virtual_cable, hid_remote_wake, hid_reconnect_initiate,
413         hid_boot_device, hid_descriptor_keyboard_boot_mode, sizeof(hid_descriptor_keyboard_boot_mode), hid_device_name);
414     printf("HID service record size: %u\n", de_get_len( hid_service_buffer));
415     sdp_register_service(hid_service_buffer);
416 
417     // See https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers if you don't have a USB Vendor ID and need a Bluetooth Vendor ID
418     // device info: BlueKitchen GmbH, product 1, version 1
419     device_id_create_sdp_record(device_id_sdp_service_buffer, 0x10003, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
420     printf("Device ID SDP service record size: %u\n", de_get_len((uint8_t*)device_id_sdp_service_buffer));
421     sdp_register_service(device_id_sdp_service_buffer);
422 
423     // HID Device
424     hid_device_init(hid_boot_device, sizeof(hid_descriptor_keyboard_boot_mode), hid_descriptor_keyboard_boot_mode);
425 
426     // register for HCI events
427     hci_event_callback_registration.callback = &packet_handler;
428     hci_add_event_handler(&hci_event_callback_registration);
429 
430     // register for HID events
431     hid_device_register_packet_handler(&packet_handler);
432 
433 #ifdef HAVE_BTSTACK_STDIN
434     sscanf_bd_addr(device_addr_string, device_addr);
435     btstack_stdin_setup(stdin_process);
436 #endif
437     // turn on!
438     hci_power_control(HCI_POWER_ON);
439     return 0;
440 }
441 /* LISTING_END */
442 /* EXAMPLE_END */
443