xref: /btstack/example/hid_keyboard_demo.c (revision d40c9ac6cf1a34ffc9b2aba4e96744f8a621b6b1)
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  * @text This HID Device example demonstrates how to implement
44  * an HID keyboard. Without a HAVE_POSIX_STDIN, a fixed demo text is sent
45  * If HAVE_POSIX_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 <unistd.h>
55 #include <inttypes.h>
56 
57 #include "btstack.h"
58 
59 #undef HAVE_POSIX_STDIN
60 
61 #ifdef HAVE_POSIX_STDIN
62 #include "stdin_support.h"
63 #endif
64 
65 uint8_t hid_service_buffer[250];
66 const char hid_device_name[] = "BTstack HID Keyboard";
67 static btstack_packet_callback_registration_t hci_event_callback_registration;
68 
69 // hid device state
70 static uint16_t hid_control_cid;
71 static uint16_t hid_interrupt_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     l2cap_request_can_send_now_event(hid_interrupt_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     l2cap_send(hid_interrupt_cid, &report[0], sizeof(report));
213 }
214 
215 static int hid_connected(void){
216     return hid_control_cid && hid_interrupt_cid;
217 }
218 
219 #ifdef HAVE_POSIX_STDIN
220 
221 // prototypes
222 static void show_usage(void);
223 
224 // Testig User Interface
225 static void show_usage(void){
226     bd_addr_t iut_address;
227     gap_local_bd_addr(iut_address);
228 
229     printf("\n--- Bluetooth HID Device Test Console %s ---\n", bd_addr_to_str(iut_address));
230     printf("\n");
231     printf("---\n");
232     printf("Ctrl-c - exit\n");
233     printf("---\n");
234 }
235 
236 static void stdin_process(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
237     UNUSED(ds);
238     UNUSED(callback_type);
239 
240     char character = btstack_stdin_read();
241 
242     uint8_t modifier;
243     uint8_t keycode;
244     int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
245     if (found){
246         send_key(modifier, keycode);
247         return;
248     }
249     show_usage();
250 }
251 #else
252 
253 // On embedded systems, send constant demo text with fixed period
254 
255 #define TYPING_PERIOD_MS 100
256 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n";
257 
258 static int demo_pos;
259 static btstack_timer_source_t typing_timer;
260 
261 static void typing_timer_handler(btstack_timer_source_t * ts){
262 
263     // abort if not connected
264     if (!hid_connected()) return;
265 
266     // get next character
267     uint8_t character = demo_text[demo_pos++];
268     if (demo_text[demo_pos] == 0){
269         demo_pos = 0;
270     }
271 
272     // get keycodeand send
273     uint8_t modifier;
274     uint8_t keycode;
275     int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
276     if (found){
277         send_key(modifier, keycode);
278     }
279 
280     // set next timer
281     btstack_run_loop_set_timer(ts, TYPING_PERIOD_MS);
282     btstack_run_loop_add_timer(ts);
283 }
284 
285 static void hid_start_typing(void){
286     demo_pos = 0;
287     // set one-shot timer
288     typing_timer.process = &typing_timer_handler;
289     btstack_run_loop_set_timer(&typing_timer, TYPING_PERIOD_MS);
290     btstack_run_loop_add_timer(&typing_timer);
291 }
292 
293 #endif
294 
295 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t packet_size){
296     UNUSED(channel);
297     UNUSED(packet_size);
298     int connected_before;
299     switch (packet_type){
300         case HCI_EVENT_PACKET:
301             switch (packet[0]){
302                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
303                     // ssp: inform about user confirmation request
304                     log_info("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", hci_event_user_confirmation_request_get_numeric_value(packet));
305                     log_info("SSP User Confirmation Auto accept\n");
306                     break;
307 
308                 // into HID Device/Server
309                 case L2CAP_EVENT_INCOMING_CONNECTION:
310                     switch (l2cap_event_incoming_connection_get_psm(packet)){
311                         case PSM_HID_CONTROL:
312                         case PSM_HID_INTERRUPT:
313                             l2cap_accept_connection(channel);
314                             break;
315                         default:
316                             l2cap_decline_connection(channel);
317                             break;
318                     }
319                     break;
320                 case L2CAP_EVENT_CHANNEL_OPENED:
321                     if (packet[2]) return;
322                     connected_before = hid_connected();
323                     switch (l2cap_event_channel_opened_get_psm(packet)){
324                         case PSM_HID_CONTROL:
325                             hid_control_cid = l2cap_event_channel_opened_get_local_cid(packet);
326                             log_info("HID Control opened, cid 0x%02x", hid_control_cid);
327                             break;
328                         case PSM_HID_INTERRUPT:
329                             hid_interrupt_cid = l2cap_event_channel_opened_get_local_cid(packet);
330                             log_info("HID Interrupt opened, cid 0x%02x", hid_interrupt_cid);
331                             break;
332                         default:
333                             break;
334                     }
335                     if (!connected_before && hid_connected()){
336                         printf("HID Connected\n");
337 #ifndef HAVE_POSIX_STDIN
338                         hid_start_typing();
339 #endif
340                     }
341                     break;
342                 case L2CAP_EVENT_CHANNEL_CLOSED:
343                     connected_before = hid_connected();
344                     if (l2cap_event_channel_closed_get_local_cid(packet) == hid_control_cid){
345                         log_info("HID Control closed");
346                         hid_control_cid = 0;
347                     }
348                     if (l2cap_event_channel_closed_get_local_cid(packet) == hid_interrupt_cid){
349                         log_info("HID Interrupt closed");
350                         hid_interrupt_cid = 0;
351                     }
352                     if (connected_before && !hid_connected()){
353                         printf("HID Disconnected\n");
354                     }
355                     break;
356                 case L2CAP_EVENT_CAN_SEND_NOW:
357                     if (send_keycode){
358                         send_report(send_modifier, send_keycode);
359                         send_keycode = 0;
360                         send_modifier = 0;
361                         l2cap_request_can_send_now_event(hid_interrupt_cid);
362                     } else {
363                         send_report(0, 0);
364                     }
365                 default:
366                     break;
367             }
368             break;
369         default:
370             break;
371     }
372 }
373 
374 /* @section Main Application Setup
375  *
376  * @text Listing MainConfiguration shows main application code.
377  * To run a HID Device service you need to initialize the SDP, and to create and register HID Device record with it.
378  * At the end the Bluetooth stack is started.
379  */
380 
381 /* LISTING_START(MainConfiguration): Setup HID Device */
382 
383 int btstack_main(int argc, const char * argv[]);
384 int btstack_main(int argc, const char * argv[]){
385     (void)argc;
386     (void)argv;
387 
388     // register for HCI events
389     hci_event_callback_registration.callback = &packet_handler;
390     hci_add_event_handler(&hci_event_callback_registration);
391     hci_register_sco_packet_handler(&packet_handler);
392 
393     gap_discoverable_control(1);
394     gap_set_class_of_device(0x2540);
395     gap_set_local_name(hid_device_name);
396 
397     // L2CAP
398     l2cap_init();
399     l2cap_register_service(packet_handler, PSM_HID_INTERRUPT, 100, LEVEL_0);
400     l2cap_register_service(packet_handler, PSM_HID_CONTROL,   100, LEVEL_0);
401 
402     // SDP Server
403     sdp_init();
404     memset(hid_service_buffer, 0, sizeof(hid_service_buffer));
405     // hid sevice subclass 2540 Keyboard, hid counntry code 33 US, hid virtual cable off, hid reconnect initiate off, hid boot device off
406     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);
407     printf("SDP service record size: %u\n", de_get_len( hid_service_buffer));
408     sdp_register_service(hid_service_buffer);
409 
410 #ifdef HAVE_POSIX_STDIN
411     btstack_stdin_setup(stdin_process);
412 #endif
413     // turn on!
414     hci_power_control(HCI_POWER_ON);
415     return 0;
416 }
417 /* LISTING_END */
418 /* EXAMPLE_END */
419