xref: /btstack/example/hid_keyboard_demo.c (revision 7ea7688a8f341f3783e40a238546a118134c6d1b)
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(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
221     UNUSED(ds);
222     UNUSED(callback_type);
223 
224     char character = btstack_stdin_read();
225 
226     uint8_t modifier;
227     uint8_t keycode;
228     int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
229     if (found){
230         send_key(modifier, keycode);
231         return;
232     }
233 }
234 #else
235 
236 // On embedded systems, send constant demo text with fixed period
237 
238 #define TYPING_PERIOD_MS 100
239 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n";
240 
241 static int demo_pos;
242 static btstack_timer_source_t typing_timer;
243 
244 static void typing_timer_handler(btstack_timer_source_t * ts){
245 
246     // abort if not connected
247     if (!hid_cid) return;
248 
249     // get next character
250     uint8_t character = demo_text[demo_pos++];
251     if (demo_text[demo_pos] == 0){
252         demo_pos = 0;
253     }
254 
255     // get keycodeand send
256     uint8_t modifier;
257     uint8_t keycode;
258     int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
259     if (found){
260         send_key(modifier, keycode);
261     }
262 
263     // set next timer
264     btstack_run_loop_set_timer(ts, TYPING_PERIOD_MS);
265     btstack_run_loop_add_timer(ts);
266 }
267 
268 static void hid_embedded_start_typing(void){
269     demo_pos = 0;
270     // set one-shot timer
271     typing_timer.process = &typing_timer_handler;
272     btstack_run_loop_set_timer(&typing_timer, TYPING_PERIOD_MS);
273     btstack_run_loop_add_timer(&typing_timer);
274 }
275 
276 #endif
277 
278 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t packet_size){
279     UNUSED(channel);
280     UNUSED(packet_size);
281     switch (packet_type){
282         case HCI_EVENT_PACKET:
283             switch (packet[0]){
284                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
285                     // ssp: inform about user confirmation request
286                     log_info("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", hci_event_user_confirmation_request_get_numeric_value(packet));
287                     log_info("SSP User Confirmation Auto accept\n");
288                     break;
289 
290                 case HCI_EVENT_HID_META:
291                     switch (hci_event_hid_meta_get_subevent_code(packet)){
292                         case HID_SUBEVENT_CONNECTION_OPENED:
293                             if (hid_subevent_connection_opened_get_status(packet)) return;
294                             hid_cid = hid_subevent_connection_opened_get_hid_cid(packet);
295 #ifdef HAVE_BTSTACK_STDIN
296                             printf("HID Connected, please start typing...\n");
297 #else
298                             printf("HID Connected, sending demo text...\n");
299                             hid_embedded_start_typing();
300 #endif
301                             break;
302                         case HID_SUBEVENT_CONNECTION_CLOSED:
303                             printf("HID Disconnected\n");
304                             hid_cid = 0;
305                             break;
306                         case HID_SUBEVENT_CAN_SEND_NOW:
307                             if (send_keycode){
308                                 send_report(send_modifier, send_keycode);
309                                 send_keycode = 0;
310                                 send_modifier = 0;
311                                 hid_device_request_can_send_now_event(hid_cid);
312                             } else {
313                                 send_report(0, 0);
314                             }
315                             break;
316                         default:
317                             break;
318                     }
319                     break;
320                 default:
321                     break;
322             }
323             break;
324         default:
325             break;
326     }
327 }
328 
329 /* @section Main Application Setup
330  *
331  * @text Listing MainConfiguration shows main application code.
332  * To run a HID Device service you need to initialize the SDP, and to create and register HID Device record with it.
333  * At the end the Bluetooth stack is started.
334  */
335 
336 /* LISTING_START(MainConfiguration): Setup HID Device */
337 
338 int btstack_main(int argc, const char * argv[]);
339 int btstack_main(int argc, const char * argv[]){
340     (void)argc;
341     (void)argv;
342 
343     // register for HCI events
344     hci_event_callback_registration.callback = &packet_handler;
345     hci_add_event_handler(&hci_event_callback_registration);
346     hci_register_sco_packet_handler(&packet_handler);
347 
348     gap_discoverable_control(1);
349     gap_set_class_of_device(0x2540);
350     gap_set_local_name(hid_device_name);
351 
352     // L2CAP
353     l2cap_init();
354 
355     // SDP Server
356     sdp_init();
357     memset(hid_service_buffer, 0, sizeof(hid_service_buffer));
358     // hid sevice subclass 2540 Keyboard, hid counntry code 33 US, hid virtual cable off, hid reconnect initiate off, hid boot device off
359     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);
360     printf("SDP service record size: %u\n", de_get_len( hid_service_buffer));
361     sdp_register_service(hid_service_buffer);
362 
363     // HID Device
364     hid_device_init();
365     hid_device_register_packet_handler(&packet_handler);
366 
367 #ifdef HAVE_BTSTACK_STDIN
368     btstack_stdin_setup(stdin_process);
369 #endif
370     // turn on!
371     hci_power_control(HCI_POWER_ON);
372     return 0;
373 }
374 /* LISTING_END */
375 /* EXAMPLE_END */
376