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