xref: /btstack/example/hid_keyboard_demo.c (revision d40c3de009bce6994e726da5a427e08951b353d9)
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_device_demo.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(hid_device_demo): HID Device (Server) Demo
42  *
43  * Status: Basic implementation. HID Request from Host are not answered yet. Works with iOS.
44  *
45  * @text This HID Device example demonstrates how to implement
46  * an HID keyboard. Without a HAVE_BTSTACK_STDIN, a fixed demo text is sent
47  * If HAVE_BTSTACK_STDIN is defined, you can type from the terminal
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 static uint8_t hid_service_buffer[250];
68 static const char hid_device_name[] = "BTstack HID Keyboard";
69 static btstack_packet_callback_registration_t hci_event_callback_registration;
70 static uint16_t hid_cid;
71 
72 // from USB HID Specification 1.1, Appendix B.1
73 const uint8_t hid_descriptor_keyboard_boot_mode[] = {
74 
75     0x05, 0x01,                    // Usage Page (Generic Desktop)
76     0x09, 0x06,                    // Usage (Keyboard)
77     0xa1, 0x01,                    // Collection (Application)
78 
79     // Modifier byte
80 
81     0x75, 0x01,                    //   Report Size (1)
82     0x95, 0x08,                    //   Report Count (8)
83     0x05, 0x07,                    //   Usage Page (Key codes)
84     0x19, 0xe0,                    //   Usage Minimum (Keyboard LeftControl)
85     0x29, 0xe7,                    //   Usage Maxium (Keyboard Right GUI)
86     0x15, 0x00,                    //   Logical Minimum (0)
87     0x25, 0x01,                    //   Logical Maximum (1)
88     0x81, 0x02,                    //   Input (Data, Variable, Absolute)
89 
90     // Reserved byte
91 
92     0x75, 0x01,                    //   Report Size (1)
93     0x95, 0x08,                    //   Report Count (8)
94     0x81, 0x03,                    //   Input (Constant, Variable, Absolute)
95 
96     // LED report + padding
97 
98     0x95, 0x05,                    //   Report Count (5)
99     0x75, 0x01,                    //   Report Size (1)
100     0x05, 0x08,                    //   Usage Page (LEDs)
101     0x19, 0x01,                    //   Usage Minimum (Num Lock)
102     0x29, 0x05,                    //   Usage Maxium (Kana)
103     0x91, 0x02,                    //   Output (Data, Variable, Absolute)
104 
105     0x95, 0x01,                    //   Report Count (1)
106     0x75, 0x03,                    //   Report Size (3)
107     0x91, 0x03,                    //   Output (Constant, Variable, Absolute)
108 
109     // Keycodes
110 
111     0x95, 0x06,                    //   Report Count (6)
112     0x75, 0x08,                    //   Report Size (8)
113     0x15, 0x00,                    //   Logical Minimum (0)
114     0x25, 0xff,                    //   Logical Maximum (1)
115     0x05, 0x07,                    //   Usage Page (Key codes)
116     0x19, 0x00,                    //   Usage Minimum (Reserved (no event indicated))
117     0x29, 0xff,                    //   Usage Maxium (Reserved)
118     0x81, 0x00,                    //   Input (Data, Array)
119 
120     0xc0,                          // End collection
121 };
122 
123 //
124 #define CHAR_ILLEGAL     0xff
125 #define CHAR_RETURN     '\n'
126 #define CHAR_ESCAPE      27
127 #define CHAR_TAB         '\t'
128 #define CHAR_BACKSPACE   0x7f
129 
130 // Simplified US Keyboard with Shift modifier
131 
132 /**
133  * English (US)
134  */
135 static const uint8_t keytable_us_none [] = {
136     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*   0-3 */
137     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                   /*  4-13 */
138     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',                   /* 14-23 */
139     'u', 'v', 'w', 'x', 'y', 'z',                                       /* 24-29 */
140     '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',                   /* 30-39 */
141     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
142     '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',',       /* 45-54 */
143     '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
144     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
145     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
146     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
147     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
148     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
149     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
150     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
151     '6', '7', '8', '9', '0', '.', 0xa7,                                 /* 97-100 */
152 };
153 
154 static const uint8_t keytable_us_shift[] = {
155     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*  0-3  */
156     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',                   /*  4-13 */
157     'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',                   /* 14-23 */
158     'U', 'V', 'W', 'X', 'Y', 'Z',                                       /* 24-29 */
159     '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',                   /* 30-39 */
160     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
161     '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<',         /* 45-54 */
162     '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
163     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
164     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
165     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
166     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
167     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
168     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
169     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
170     '6', '7', '8', '9', '0', '.', 0xb1,                                 /* 97-100 */
171 };
172 
173 // HID Keyboard lookup
174 static int lookup_keycode(uint8_t character, const uint8_t * table, int size, uint8_t * keycode){
175     int i;
176     for (i=0;i<size;i++){
177         if (table[i] != character) continue;
178         *keycode = i;
179         return 1;
180     }
181     return 0;
182 }
183 
184 static int keycode_and_modifer_us_for_character(uint8_t character, uint8_t * keycode, uint8_t * modifier){
185     int found;
186     found = lookup_keycode(character, keytable_us_none, sizeof(keytable_us_none), keycode);
187     if (found) {
188         *modifier = 0;  // none
189         return 1;
190     }
191     found = lookup_keycode(character, keytable_us_shift, sizeof(keytable_us_shift), keycode);
192     if (found) {
193         *modifier = 2;  // shift
194         return 1;
195     }
196     return 0;
197 }
198 
199 // HID Report sending
200 static int send_keycode;
201 static int send_modifier;
202 
203 static void send_key(int modifier, int keycode){
204     send_keycode = keycode;
205     send_modifier = modifier;
206     hid_device_request_can_send_now_event(hid_cid);
207 }
208 
209 static void send_report(int modifier, int keycode){
210     uint8_t report[] = { 0xa1, modifier, 0, 0, keycode, 0, 0, 0, 0, 0};
211     hid_device_send_interrupt_message(hid_cid, &report[0], sizeof(report));
212 }
213 
214 // Demo Application
215 
216 #ifdef HAVE_BTSTACK_STDIN
217 
218 // On systems with STDIN, we can directly type on the console
219 
220 static void stdin_process(char character){
221     uint8_t modifier;
222     uint8_t keycode;
223     int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
224     if (found){
225         send_key(modifier, keycode);
226         return;
227     }
228 }
229 #else
230 
231 // On embedded systems, send constant demo text with fixed period
232 
233 #define TYPING_PERIOD_MS 100
234 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n";
235 
236 static int demo_pos;
237 static btstack_timer_source_t typing_timer;
238 
239 static void typing_timer_handler(btstack_timer_source_t * ts){
240 
241     // abort if not connected
242     if (!hid_cid) return;
243 
244     // get next character
245     uint8_t character = demo_text[demo_pos++];
246     if (demo_text[demo_pos] == 0){
247         demo_pos = 0;
248     }
249 
250     // get keycodeand send
251     uint8_t modifier;
252     uint8_t keycode;
253     int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
254     if (found){
255         send_key(modifier, keycode);
256     }
257 
258     // set next timer
259     btstack_run_loop_set_timer(ts, TYPING_PERIOD_MS);
260     btstack_run_loop_add_timer(ts);
261 }
262 
263 static void hid_embedded_start_typing(void){
264     demo_pos = 0;
265     // set one-shot timer
266     typing_timer.process = &typing_timer_handler;
267     btstack_run_loop_set_timer(&typing_timer, TYPING_PERIOD_MS);
268     btstack_run_loop_add_timer(&typing_timer);
269 }
270 
271 #endif
272 
273 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t packet_size){
274     UNUSED(channel);
275     UNUSED(packet_size);
276     switch (packet_type){
277         case HCI_EVENT_PACKET:
278             switch (packet[0]){
279                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
280                     // ssp: inform about user confirmation request
281                     log_info("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", hci_event_user_confirmation_request_get_numeric_value(packet));
282                     log_info("SSP User Confirmation Auto accept\n");
283                     break;
284 
285                 case HCI_EVENT_HID_META:
286                     switch (hci_event_hid_meta_get_subevent_code(packet)){
287                         case HID_SUBEVENT_CONNECTION_OPENED:
288                             if (hid_subevent_connection_opened_get_status(packet)) return;
289                             hid_cid = hid_subevent_connection_opened_get_hid_cid(packet);
290 #ifdef HAVE_BTSTACK_STDIN
291                             printf("HID Connected, please start typing...\n");
292 #else
293                             printf("HID Connected, sending demo text...\n");
294                             hid_embedded_start_typing();
295 #endif
296                             break;
297                         case HID_SUBEVENT_CONNECTION_CLOSED:
298                             printf("HID Disconnected\n");
299                             hid_cid = 0;
300                             break;
301                         case HID_SUBEVENT_CAN_SEND_NOW:
302                             if (send_keycode){
303                                 send_report(send_modifier, send_keycode);
304                                 send_keycode = 0;
305                                 send_modifier = 0;
306                                 hid_device_request_can_send_now_event(hid_cid);
307                             } else {
308                                 send_report(0, 0);
309                             }
310                             break;
311                         default:
312                             break;
313                     }
314                     break;
315                 default:
316                     break;
317             }
318             break;
319         default:
320             break;
321     }
322 }
323 
324 /* @section Main Application Setup
325  *
326  * @text Listing MainConfiguration shows main application code.
327  * To run a HID Device service you need to initialize the SDP, and to create and register HID Device record with it.
328  * At the end the Bluetooth stack is started.
329  */
330 
331 /* LISTING_START(MainConfiguration): Setup HID Device */
332 
333 int btstack_main(int argc, const char * argv[]);
334 int btstack_main(int argc, const char * argv[]){
335     (void)argc;
336     (void)argv;
337 
338     // register for HCI events
339     hci_event_callback_registration.callback = &packet_handler;
340     hci_add_event_handler(&hci_event_callback_registration);
341     hci_register_sco_packet_handler(&packet_handler);
342 
343     gap_discoverable_control(1);
344     gap_set_class_of_device(0x2540);
345     gap_set_local_name(hid_device_name);
346 
347     // L2CAP
348     l2cap_init();
349 
350     // SDP Server
351     sdp_init();
352     memset(hid_service_buffer, 0, sizeof(hid_service_buffer));
353     // hid sevice subclass 2540 Keyboard, hid counntry code 33 US, hid virtual cable off, hid reconnect initiate off, hid boot device off
354     hid_create_sdp_record(hid_service_buffer, 0x10001, 0x2540, 33, 0, 0, 0, hid_descriptor_keyboard_boot_mode, sizeof(hid_descriptor_keyboard_boot_mode), hid_device_name);
355     printf("SDP service record size: %u\n", de_get_len( hid_service_buffer));
356     sdp_register_service(hid_service_buffer);
357 
358     // HID Device
359     hid_device_init();
360     hid_device_register_packet_handler(&packet_handler);
361 
362 #ifdef HAVE_BTSTACK_STDIN
363     btstack_stdin_setup(stdin_process);
364 #endif
365     // turn on!
366     hci_power_control(HCI_POWER_ON);
367     return 0;
368 }
369 /* LISTING_END */
370 /* EXAMPLE_END */
371