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