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