xref: /btstack/example/hog_keyboard_demo.c (revision be78df3b6c7394390fa6d2bc04f991dd7ac2de2c)
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__ "hog_keyboard_demo.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(hog_keyboard_demo): HID Keyboard LE
42  */
43 // *****************************************************************************
44 
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <inttypes.h>
50 
51 #include "hog_keyboard_demo.h"
52 
53 #include "btstack.h"
54 
55 #include "ble/gatt-service/battery_service_server.h"
56 #include "ble/gatt-service/device_information_service_server.h"
57 #include "ble/gatt-service/hids_device.h"
58 
59 // from USB HID Specification 1.1, Appendix B.1
60 const uint8_t hid_descriptor_keyboard_boot_mode[] = {
61 
62     0x05, 0x01,                    // Usage Page (Generic Desktop)
63     0x09, 0x06,                    // Usage (Keyboard)
64     0xa1, 0x01,                    // Collection (Application)
65 
66     0x85,  0x01,                   // Report ID 1
67 
68     // Modifier byte
69 
70     0x75, 0x01,                    //   Report Size (1)
71     0x95, 0x08,                    //   Report Count (8)
72     0x05, 0x07,                    //   Usage Page (Key codes)
73     0x19, 0xe0,                    //   Usage Minimum (Keyboard LeftControl)
74     0x29, 0xe7,                    //   Usage Maxium (Keyboard Right GUI)
75     0x15, 0x00,                    //   Logical Minimum (0)
76     0x25, 0x01,                    //   Logical Maximum (1)
77     0x81, 0x02,                    //   Input (Data, Variable, Absolute)
78 
79     // Reserved byte
80 
81     0x75, 0x01,                    //   Report Size (1)
82     0x95, 0x08,                    //   Report Count (8)
83     0x81, 0x03,                    //   Input (Constant, Variable, Absolute)
84 
85     // LED report + padding
86 
87     0x95, 0x05,                    //   Report Count (5)
88     0x75, 0x01,                    //   Report Size (1)
89     0x05, 0x08,                    //   Usage Page (LEDs)
90     0x19, 0x01,                    //   Usage Minimum (Num Lock)
91     0x29, 0x05,                    //   Usage Maxium (Kana)
92     0x91, 0x02,                    //   Output (Data, Variable, Absolute)
93 
94     0x95, 0x01,                    //   Report Count (1)
95     0x75, 0x03,                    //   Report Size (3)
96     0x91, 0x03,                    //   Output (Constant, Variable, Absolute)
97 
98     // Keycodes
99 
100     0x95, 0x06,                    //   Report Count (6)
101     0x75, 0x08,                    //   Report Size (8)
102     0x15, 0x00,                    //   Logical Minimum (0)
103     0x25, 0xff,                    //   Logical Maximum (1)
104     0x05, 0x07,                    //   Usage Page (Key codes)
105     0x19, 0x00,                    //   Usage Minimum (Reserved (no event indicated))
106     0x29, 0xff,                    //   Usage Maxium (Reserved)
107     0x81, 0x00,                    //   Input (Data, Array)
108 
109     0xc0,                          // End collection
110 };
111 
112 
113 
114 //
115 #define CHAR_ILLEGAL     0xff
116 #define CHAR_RETURN     '\n'
117 #define CHAR_ESCAPE      27
118 #define CHAR_TAB         '\t'
119 #define CHAR_BACKSPACE   0x7f
120 
121 // Simplified US Keyboard with Shift modifier
122 
123 /**
124  * English (US)
125  */
126 static const uint8_t keytable_us_none [] = {
127     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*   0-3 */
128     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                   /*  4-13 */
129     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',                   /* 14-23 */
130     'u', 'v', 'w', 'x', 'y', 'z',                                       /* 24-29 */
131     '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',                   /* 30-39 */
132     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
133     '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',',       /* 45-54 */
134     '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
135     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
136     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
137     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
138     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
139     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
140     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
141     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
142     '6', '7', '8', '9', '0', '.', 0xa7,                                 /* 97-100 */
143 };
144 
145 static const uint8_t keytable_us_shift[] = {
146     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*  0-3  */
147     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',                   /*  4-13 */
148     'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',                   /* 14-23 */
149     'U', 'V', 'W', 'X', 'Y', 'Z',                                       /* 24-29 */
150     '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',                   /* 30-39 */
151     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
152     '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<',         /* 45-54 */
153     '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
154     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
155     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
156     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
157     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
158     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
159     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
160     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
161     '6', '7', '8', '9', '0', '.', 0xb1,                                 /* 97-100 */
162 };
163 
164 // static btstack_timer_source_t heartbeat;
165 static btstack_packet_callback_registration_t hci_event_callback_registration;
166 static btstack_packet_callback_registration_t sm_event_callback_registration;
167 static uint8_t battery = 100;
168 static hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
169 static uint8_t protocol_mode = 1;
170 
171 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
172 
173 const uint8_t adv_data[] = {
174     // Flags general discoverable, BR/EDR not supported
175     0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
176     // Name
177     0x0d, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'H', 'I', 'D', ' ', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd',
178     // 16-bit Service UUIDs
179     0x03, BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE & 0xff, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE >> 8,
180     // Appearance HID - Keyboard (Category 15, Sub-Category 1)
181     0x03, BLUETOOTH_DATA_TYPE_APPEARANCE, 0xC1, 0x03,
182 };
183 const uint8_t adv_data_len = sizeof(adv_data);
184 
185 static void le_keyboard_setup(void){
186 
187     l2cap_init();
188 
189     // setup SM: Display only
190     sm_init();
191     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
192     sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);
193 
194     // setup ATT server
195     att_server_init(profile_data, NULL, NULL);
196 
197     // setup battery service
198     battery_service_server_init(battery);
199 
200     // setup device information service
201     device_information_service_server_init();
202 
203     // setup HID Device service
204     hids_device_init(0, hid_descriptor_keyboard_boot_mode, sizeof(hid_descriptor_keyboard_boot_mode));
205 
206     // setup advertisements
207     uint16_t adv_int_min = 0x0030;
208     uint16_t adv_int_max = 0x0030;
209     uint8_t adv_type = 0;
210     bd_addr_t null_addr;
211     memset(null_addr, 0, 6);
212     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
213     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
214     gap_advertisements_enable(1);
215 
216     // register for HCI events
217     hci_event_callback_registration.callback = &packet_handler;
218     hci_add_event_handler(&hci_event_callback_registration);
219 
220     // register for SM events
221     sm_event_callback_registration.callback = &packet_handler;
222     sm_add_event_handler(&sm_event_callback_registration);
223 
224     // register for HIDS
225     hids_device_register_packet_handler(packet_handler);
226 }
227 
228 // HID Keyboard lookup
229 static int lookup_keycode(uint8_t character, const uint8_t * table, int size, uint8_t * keycode){
230     int i;
231     for (i=0;i<size;i++){
232         if (table[i] != character) continue;
233         *keycode = i;
234         return 1;
235     }
236     return 0;
237 }
238 
239 static int keycode_and_modifer_us_for_character(uint8_t character, uint8_t * keycode, uint8_t * modifier){
240     int found;
241     found = lookup_keycode(character, keytable_us_none, sizeof(keytable_us_none), keycode);
242     if (found) {
243         *modifier = 0;  // none
244         return 1;
245     }
246     found = lookup_keycode(character, keytable_us_shift, sizeof(keytable_us_shift), keycode);
247     if (found) {
248         *modifier = 2;  // shift
249         return 1;
250     }
251     return 0;
252 }
253 
254 // HID Report sending
255 static void send_report(int modifier, int keycode){
256     uint8_t report[] = {  modifier, 0, keycode, 0, 0, 0, 0, 0};
257     switch (protocol_mode){
258         case 0:
259             hids_device_send_boot_keyboard_input_report(con_handle, report, sizeof(report));
260             break;
261         case 1:
262            hids_device_send_input_report(con_handle, report, sizeof(report));
263            break;
264         default:
265             break;
266     }
267 }
268 
269 // Demo Application
270 
271 #ifdef HAVE_BTSTACK_STDIN
272 
273 // On systems with STDIN, we can directly type on the console
274 static enum {
275     W4_INPUT,
276     W4_CAN_SEND_FROM_BUFFER,
277     W4_CAN_SEND_KEY_UP,
278 } state;
279 
280 // Buffer for 20 characters
281 static uint8_t ascii_input_storage[20];
282 static btstack_ring_buffer_t ascii_input_buffer;
283 
284 static void typing_can_send_now(void){
285     switch (state){
286         case W4_CAN_SEND_FROM_BUFFER:
287             while (1){
288                 uint8_t c;
289                 uint32_t num_bytes_read;
290 
291                 btstack_ring_buffer_read(&ascii_input_buffer, &c, 1, &num_bytes_read);
292                 if (num_bytes_read == 0){
293                     state = W4_INPUT;
294                     break;
295                 }
296 
297                 uint8_t modifier;
298                 uint8_t keycode;
299                 int found = keycode_and_modifer_us_for_character(c, &keycode, &modifier);
300                 if (!found) continue;
301 
302                 printf("sending: %c\n", c);
303 
304                 send_report(modifier, keycode);
305                 state = W4_CAN_SEND_KEY_UP;
306                 hids_device_request_can_send_now_event(con_handle);
307                 break;
308             }
309             break;
310         case W4_CAN_SEND_KEY_UP:
311             send_report(0, 0);
312             if (btstack_ring_buffer_bytes_available(&ascii_input_buffer)){
313                 state = W4_CAN_SEND_FROM_BUFFER;
314                 hids_device_request_can_send_now_event(con_handle);
315             } else {
316                 state = W4_INPUT;
317             }
318             break;
319         default:
320             break;
321     }
322 }
323 
324 static void stdin_process(char character){
325     uint8_t c = character;
326     btstack_ring_buffer_write(&ascii_input_buffer, &c, 1);
327     // start sending
328     if (state == W4_INPUT && con_handle != HCI_CON_HANDLE_INVALID){
329         state = W4_CAN_SEND_FROM_BUFFER;
330         hids_device_request_can_send_now_event(con_handle);
331     }
332 }
333 
334 #else
335 
336 // On embedded systems, send constant demo text with fixed period
337 
338 #define TYPING_PERIOD_MS 50
339 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n";
340 
341 static int demo_pos;
342 static btstack_timer_source_t typing_timer;
343 
344 static int send_keycode;
345 static int send_modifier;
346 static int send_keyup;
347 
348 static void send_key(int modifier, int keycode){
349     send_keycode = keycode;
350     send_modifier = modifier;
351     hids_device_request_can_send_now_event(con_handle);
352 }
353 
354 static void typing_can_send_now(void){
355    send_report(send_modifier, send_keycode);
356 }
357 
358 static void typing_timer_handler(btstack_timer_source_t * ts){
359 
360     if (send_keyup){
361         // just send key up
362         send_keyup = 0;
363         send_key(0, 0);
364     } else {
365         // get next character
366         uint8_t character = demo_text[demo_pos++];
367         if (demo_text[demo_pos] == 0){
368             demo_pos = 0;
369         }
370 
371         // get keycode and send
372         uint8_t modifier;
373         uint8_t keycode;
374         int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
375         if (found){
376             printf("%c\n", character);
377             send_key(modifier, keycode);
378             send_keyup = 1;
379         }
380     }
381 
382     // set next timer
383     btstack_run_loop_set_timer(ts, TYPING_PERIOD_MS);
384     btstack_run_loop_add_timer(ts);
385 }
386 
387 static void hid_embedded_start_typing(void){
388     printf("Start typing..\n");
389 
390     demo_pos = 0;
391     // set one-shot timer
392     typing_timer.process = &typing_timer_handler;
393     btstack_run_loop_set_timer(&typing_timer, TYPING_PERIOD_MS);
394     btstack_run_loop_add_timer(&typing_timer);
395 }
396 
397 #endif
398 
399 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
400     UNUSED(channel);
401     UNUSED(size);
402 
403     if (packet_type != HCI_EVENT_PACKET) return;
404 
405     switch (hci_event_packet_get_type(packet)) {
406         case HCI_EVENT_DISCONNECTION_COMPLETE:
407             con_handle = HCI_CON_HANDLE_INVALID;
408             printf("Disconnected\n");
409             break;
410         case SM_EVENT_JUST_WORKS_REQUEST:
411             printf("Just Works requested\n");
412             sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
413             break;
414         case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
415             printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
416             sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
417             break;
418         case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
419             printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
420             break;
421         case HCI_EVENT_HIDS_META:
422             switch (hci_event_hids_meta_get_subevent_code(packet)){
423                 case HIDS_SUBEVENT_INPUT_REPORT_ENABLE:
424                     con_handle = hids_subevent_input_report_enable_get_con_handle(packet);
425                     printf("Report Characteristic Subscribed %u\n", hids_subevent_input_report_enable_get_enable(packet));
426 #ifndef HAVE_BTSTACK_STDIN
427                     hid_embedded_start_typing();
428 #endif
429                     break;
430                 case HIDS_SUBEVENT_BOOT_KEYBOARD_INPUT_REPORT_ENABLE:
431                     con_handle = hids_subevent_boot_keyboard_input_report_enable_get_con_handle(packet);
432                     printf("Boot Keyboard Characteristic Subscribed %u\n", hids_subevent_boot_keyboard_input_report_enable_get_enable(packet));
433                     break;
434                 case HIDS_SUBEVENT_PROTOCOL_MODE:
435                     protocol_mode = hids_subevent_protocol_mode_get_protocol_mode(packet);
436                     printf("Protocol Mode: %s mode\n", hids_subevent_protocol_mode_get_protocol_mode(packet) ? "Report" : "Boot");
437                     break;
438                 case HIDS_SUBEVENT_CAN_SEND_NOW:
439                     typing_can_send_now();
440                     break;
441                 default:
442                     break;
443             }
444             break;
445 
446         default:
447             break;
448     }
449 }
450 
451 int btstack_main(void);
452 int btstack_main(void)
453 {
454     le_keyboard_setup();
455 
456 #ifdef HAVE_BTSTACK_STDIN
457     btstack_ring_buffer_init(&ascii_input_buffer, ascii_input_storage, sizeof(ascii_input_storage));
458     btstack_stdin_setup(stdin_process);
459 #endif
460 
461     // turn on!
462     hci_power_control(HCI_POWER_ON);
463 
464     return 0;
465 }
466 /* EXAMPLE_END */
467