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