xref: /btstack/example/hid_keyboard_demo.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
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 
190 // HID Keyboard lookup
191 static int lookup_keycode(uint8_t character, const uint8_t * table, int size, uint8_t * keycode){
192     int i;
193     for (i=0;i<size;i++){
194         if (table[i] != character) continue;
195         *keycode = i;
196         return 1;
197     }
198     return 0;
199 }
200 
201 static int keycode_and_modifer_us_for_character(uint8_t character, uint8_t * keycode, uint8_t * modifier){
202     int found;
203     found = lookup_keycode(character, keytable_us_none, sizeof(keytable_us_none), keycode);
204     if (found) {
205         *modifier = 0;  // none
206         return 1;
207     }
208     found = lookup_keycode(character, keytable_us_shift, sizeof(keytable_us_shift), keycode);
209     if (found) {
210         *modifier = 2;  // shift
211         return 1;
212     }
213     return 0;
214 }
215 
216 // HID Report sending
217 static int send_keycode;
218 static int send_modifier;
219 
220 static void send_key(int modifier, int keycode){
221     send_keycode = keycode;
222     send_modifier = modifier;
223     hid_device_request_can_send_now_event(hid_cid);
224 }
225 
226 static void send_report(int modifier, int keycode){
227     uint8_t report[] = { 0xa1, modifier, 0, 0, keycode, 0, 0, 0, 0, 0};
228     hid_device_send_interrupt_message(hid_cid, &report[0], sizeof(report));
229 }
230 
231 // Demo Application
232 
233 #ifdef HAVE_BTSTACK_STDIN
234 
235 // On systems with STDIN, we can directly type on the console
236 
237 static void stdin_process(char character){
238     uint8_t modifier;
239     uint8_t keycode;
240     int found;
241 
242     switch (app_state){
243         case APP_BOOTING:
244         case APP_CONNECTING:
245             // ignore
246             break;
247 
248         case APP_CONNECTED:
249             // send keyu
250             found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
251             if (found){
252                 send_key(modifier, keycode);
253                 return;
254             }
255             break;
256         case APP_NOT_CONNECTED:
257             printf("Connecting to %s...\n", bd_addr_to_str(device_addr));
258             hid_device_connect(device_addr, &hid_cid);
259             break;
260         default:
261             btstack_assert(false);
262             break;
263     }
264 }
265 #else
266 
267 // On embedded systems, send constant demo text with fixed period
268 
269 #define TYPING_PERIOD_MS 100
270 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n";
271 
272 static int demo_pos;
273 static btstack_timer_source_t typing_timer;
274 
275 static void typing_timer_handler(btstack_timer_source_t * ts){
276 
277     // abort if not connected
278     if (!hid_cid) return;
279 
280     // get next character
281     uint8_t character = demo_text[demo_pos++];
282     if (demo_text[demo_pos] == 0){
283         demo_pos = 0;
284     }
285 
286     // get keycodeand send
287     uint8_t modifier;
288     uint8_t keycode;
289     int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
290     if (found){
291         send_key(modifier, keycode);
292     }
293 
294     // set next timer
295     btstack_run_loop_set_timer(ts, TYPING_PERIOD_MS);
296     btstack_run_loop_add_timer(ts);
297 }
298 
299 static void hid_embedded_start_typing(void){
300     demo_pos = 0;
301     // set one-shot timer
302     typing_timer.process = &typing_timer_handler;
303     btstack_run_loop_set_timer(&typing_timer, TYPING_PERIOD_MS);
304     btstack_run_loop_add_timer(&typing_timer);
305 }
306 
307 #endif
308 
309 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t packet_size){
310     UNUSED(channel);
311     UNUSED(packet_size);
312     uint8_t status;
313     switch (packet_type){
314         case HCI_EVENT_PACKET:
315             switch (packet[0]){
316                 case BTSTACK_EVENT_STATE:
317                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
318                     app_state = APP_NOT_CONNECTED;
319                     break;
320 
321                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
322                     // ssp: inform about user confirmation request
323                     log_info("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", hci_event_user_confirmation_request_get_numeric_value(packet));
324                     log_info("SSP User Confirmation Auto accept\n");
325                     break;
326 
327                 case HCI_EVENT_HID_META:
328                     switch (hci_event_hid_meta_get_subevent_code(packet)){
329                         case HID_SUBEVENT_CONNECTION_OPENED:
330                             status = hid_subevent_connection_opened_get_status(packet);
331                             if (status) {
332                                 // outgoing connection failed
333                                 printf("Connection failed, status 0x%x\n", status);
334                                 app_state = APP_NOT_CONNECTED;
335                                 hid_cid = 0;
336                                 return;
337                             }
338                             app_state = APP_CONNECTED;
339                             hid_cid = hid_subevent_connection_opened_get_hid_cid(packet);
340 #ifdef HAVE_BTSTACK_STDIN
341                             printf("HID Connected, please start typing...\n");
342 #else
343                             printf("HID Connected, sending demo text...\n");
344                             hid_embedded_start_typing();
345 #endif
346                             break;
347                         case HID_SUBEVENT_CONNECTION_CLOSED:
348                             printf("HID Disconnected\n");
349                             app_state = APP_NOT_CONNECTED;
350                             hid_cid = 0;
351                             break;
352                         case HID_SUBEVENT_CAN_SEND_NOW:
353                             if (send_keycode){
354                                 send_report(send_modifier, send_keycode);
355                                 send_keycode = 0;
356                                 send_modifier = 0;
357                                 hid_device_request_can_send_now_event(hid_cid);
358                             } else {
359                                 send_report(0, 0);
360                             }
361                             break;
362                         default:
363                             break;
364                     }
365                     break;
366                 default:
367                     break;
368             }
369             break;
370         default:
371             break;
372     }
373 }
374 
375 /* @section Main Application Setup
376  *
377  * @text Listing MainConfiguration shows main application code.
378  * To run a HID Device service you need to initialize the SDP, and to create and register HID Device record with it.
379  * At the end the Bluetooth stack is started.
380  */
381 
382 /* LISTING_START(MainConfiguration): Setup HID Device */
383 
384 int btstack_main(int argc, const char * argv[]);
385 int btstack_main(int argc, const char * argv[]){
386     (void)argc;
387     (void)argv;
388 
389     // allow to get found by inquiry
390     gap_discoverable_control(1);
391     // use Limited Discoverable Mode; Peripheral; Keyboard as CoD
392     gap_set_class_of_device(0x2540);
393     // set local name to be identified - zeroes will be replaced by actual BD ADDR
394     gap_set_local_name("HID Keyboard Demo 00:00:00:00:00:00");
395     // allow for role switch in general and sniff mode
396     gap_set_default_link_policy_settings( LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE );
397     // allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it
398     gap_set_allow_role_switch(true);
399 
400     // L2CAP
401     l2cap_init();
402 
403     // SDP Server
404     sdp_init();
405     memset(hid_service_buffer, 0, sizeof(hid_service_buffer));
406     // hid sevice subclass 2540 Keyboard, hid counntry code 33 US, hid virtual cable off, hid reconnect initiate off, hid boot device off
407     hid_create_sdp_record(hid_service_buffer, 0x10001, 0x2540, 33, 0, 0, hid_boot_device, hid_descriptor_keyboard_boot_mode, sizeof(hid_descriptor_keyboard_boot_mode), hid_device_name);
408     printf("HID service record size: %u\n", de_get_len( hid_service_buffer));
409     sdp_register_service(hid_service_buffer);
410 
411     // 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
412     // device info: BlueKitchen GmbH, product 1, version 1
413     device_id_create_sdp_record(device_id_sdp_service_buffer, 0x10003, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
414     printf("Device ID SDP service record size: %u\n", de_get_len((uint8_t*)device_id_sdp_service_buffer));
415     sdp_register_service(device_id_sdp_service_buffer);
416 
417     // HID Device
418     hid_device_init(hid_boot_device, sizeof(hid_descriptor_keyboard_boot_mode), hid_descriptor_keyboard_boot_mode);
419 
420     // register for HCI events
421     hci_event_callback_registration.callback = &packet_handler;
422     hci_add_event_handler(&hci_event_callback_registration);
423 
424     // register for HID events
425     hid_device_register_packet_handler(&packet_handler);
426 
427 #ifdef HAVE_BTSTACK_STDIN
428     sscanf_bd_addr(device_addr_string, device_addr);
429     btstack_stdin_setup(stdin_process);
430 #endif
431     // turn on!
432     hci_power_control(HCI_POWER_ON);
433     return 0;
434 }
435 /* LISTING_END */
436 /* EXAMPLE_END */
437