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