xref: /btstack/example/hog_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__ "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     // register for HCI events
183     hci_event_callback_registration.callback = &packet_handler;
184     hci_add_event_handler(&hci_event_callback_registration);
185 
186     l2cap_init();
187 
188     // setup le device db
189     le_device_db_init();
190 
191     // setup SM: Display only
192     sm_init();
193     sm_event_callback_registration.callback = &packet_handler;
194     sm_add_event_handler(&sm_event_callback_registration);
195     sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
196     sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);
197 
198     // setup ATT server
199     att_server_init(profile_data, NULL, NULL);
200 
201     // setup battery service
202     battery_service_server_init(battery);
203 
204     // setup device information service
205     device_information_service_server_init();
206 
207     // setup HID Device service
208     hids_device_init(0, hid_descriptor_keyboard_boot_mode, sizeof(hid_descriptor_keyboard_boot_mode));
209     hids_device_register_packet_handler(packet_handler);
210 
211     // setup advertisements
212     uint16_t adv_int_min = 0x0030;
213     uint16_t adv_int_max = 0x0030;
214     uint8_t adv_type = 0;
215     bd_addr_t null_addr;
216     memset(null_addr, 0, 6);
217     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
218     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
219     gap_advertisements_enable(1);
220 }
221 
222 // HID Keyboard lookup
223 static int lookup_keycode(uint8_t character, const uint8_t * table, int size, uint8_t * keycode){
224     int i;
225     for (i=0;i<size;i++){
226         if (table[i] != character) continue;
227         *keycode = i;
228         return 1;
229     }
230     return 0;
231 }
232 
233 static int keycode_and_modifer_us_for_character(uint8_t character, uint8_t * keycode, uint8_t * modifier){
234     int found;
235     found = lookup_keycode(character, keytable_us_none, sizeof(keytable_us_none), keycode);
236     if (found) {
237         *modifier = 0;  // none
238         return 1;
239     }
240     found = lookup_keycode(character, keytable_us_shift, sizeof(keytable_us_shift), keycode);
241     if (found) {
242         *modifier = 2;  // shift
243         return 1;
244     }
245     return 0;
246 }
247 
248 // HID Report sending
249 
250 static void send_report(int modifier, int keycode){
251     uint8_t report[] = { /* 0xa1, */ modifier, 0, 0, keycode, 0, 0, 0, 0, 0};
252     hids_device_send_input_report(con_handle, report, sizeof(report));
253 }
254 
255 // Demo Application
256 
257 #ifdef HAVE_BTSTACK_STDIN
258 
259 // On systems with STDIN, we can directly type on the console
260 static enum {
261     W4_INPUT,
262     W4_CAN_SEND_FROM_BUFFER,
263     W4_CAN_SEND_KEY_UP,
264 } state;
265 
266 // Buffer for 20 characters
267 static uint8_t ascii_input_storage[20];
268 static btstack_ring_buffer_t ascii_input_buffer;
269 
270 static void typing_can_send_now(void){
271     switch (state){
272         case W4_CAN_SEND_FROM_BUFFER:
273             while (1){
274                 uint8_t c;
275                 uint32_t num_bytes_read;
276 
277                 btstack_ring_buffer_read(&ascii_input_buffer, &c, 1, &num_bytes_read);
278                 if (num_bytes_read == 0){
279                     state = W4_INPUT;
280                     break;
281                 }
282 
283                 uint8_t modifier;
284                 uint8_t keycode;
285                 int found = keycode_and_modifer_us_for_character(c, &keycode, &modifier);
286                 if (!found) continue;
287 
288                 printf("sending: %c\n", c);
289 
290                 send_report(modifier, keycode);
291                 state = W4_CAN_SEND_KEY_UP;
292                 hids_device_request_can_send_now_event(con_handle);
293                 break;
294             }
295             break;
296         case W4_CAN_SEND_KEY_UP:
297             send_report(0, 0);
298             if (btstack_ring_buffer_bytes_available(&ascii_input_buffer)){
299                 state = W4_CAN_SEND_FROM_BUFFER;
300                 hids_device_request_can_send_now_event(con_handle);
301             } else {
302                 state = W4_INPUT;
303             }
304             break;
305         default:
306             break;
307     }
308 }
309 
310 static void stdin_process(char character){
311     uint8_t c = character;
312     btstack_ring_buffer_write(&ascii_input_buffer, &c, 1);
313     // start sending
314     if (state == W4_INPUT && con_handle != HCI_CON_HANDLE_INVALID){
315         state = W4_CAN_SEND_FROM_BUFFER;
316         hids_device_request_can_send_now_event(con_handle);
317     }
318 }
319 
320 #else
321 
322 // On embedded systems, send constant demo text with fixed period
323 
324 #define TYPING_PERIOD_MS 50
325 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n";
326 
327 static int demo_pos;
328 static btstack_timer_source_t typing_timer;
329 
330 static int send_keycode;
331 static int send_modifier;
332 static int send_keyup;
333 
334 static void send_key(int modifier, int keycode){
335     send_keycode = keycode;
336     send_modifier = modifier;
337     hids_device_request_can_send_now_event(con_handle);
338 }
339 
340 static void typing_can_send_now(void){
341    send_report(send_modifier, send_keycode);
342 }
343 
344 static void typing_timer_handler(btstack_timer_source_t * ts){
345 
346     if (send_keyup){
347         // just send key up
348         send_keyup = 0;
349         send_key(0, 0);
350     } else {
351         // get next character
352         uint8_t character = demo_text[demo_pos++];
353         if (demo_text[demo_pos] == 0){
354             demo_pos = 0;
355         }
356 
357         // get keycode and send
358         uint8_t modifier;
359         uint8_t keycode;
360         int found = keycode_and_modifer_us_for_character(character, &keycode, &modifier);
361         if (found){
362             printf("%c\n", character);
363             send_key(modifier, keycode);
364             send_keyup = 1;
365         }
366     }
367 
368     // set next timer
369     btstack_run_loop_set_timer(ts, TYPING_PERIOD_MS);
370     btstack_run_loop_add_timer(ts);
371 }
372 
373 static void hid_embedded_start_typing(void){
374     printf("Start typing..\n");
375 
376     demo_pos = 0;
377     // set one-shot timer
378     typing_timer.process = &typing_timer_handler;
379     btstack_run_loop_set_timer(&typing_timer, TYPING_PERIOD_MS);
380     btstack_run_loop_add_timer(&typing_timer);
381 }
382 
383 #endif
384 
385 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
386     UNUSED(channel);
387     UNUSED(size);
388 
389     switch (packet_type) {
390         case HCI_EVENT_PACKET:
391             switch (hci_event_packet_get_type(packet)) {
392                 case HCI_EVENT_DISCONNECTION_COMPLETE:
393                     con_handle = HCI_CON_HANDLE_INVALID;
394                     printf("Disconnected\n");
395                     break;
396                 case SM_EVENT_JUST_WORKS_REQUEST:
397                     printf("Just Works requested\n");
398                     sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
399                     break;
400                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
401                     printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
402                     sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
403                     break;
404                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
405                     printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
406                     break;
407                 case HCI_EVENT_HIDS_META:
408                     switch (hci_event_hids_meta_get_subevent_code(packet)){
409                         case HIDS_SUBEVENT_INPUT_REPORT_ENABLE:
410                             con_handle = hids_subevent_input_report_enable_get_con_handle(packet);
411                             printf("Report Characteristic Subscribed %u\n", hids_subevent_input_report_enable_get_enable(packet));
412 #ifndef HAVE_BTSTACK_STDIN
413                             hid_embedded_start_typing();
414 #endif
415                             break;
416                         case HIDS_SUBEVENT_BOOT_KEYBOARD_INPUT_REPORT_ENABLE:
417                             con_handle = hids_subevent_input_report_enable_get_con_handle(packet);
418                             printf("Boot Keyboard Characteristic Subscribed %u\n", hids_subevent_boot_keyboard_input_report_enable_get_enable(packet));
419                             break;
420                         case HIDS_SUBEVENT_PROTOCOL_MODE:
421                             printf("Protocol Mode: %s mode\n", hids_subevent_protocol_mode_get_protocol_mode(packet) ? "Report" : "Boot");
422                             break;
423                         case HIDS_SUBEVENT_CAN_SEND_NOW:
424                             typing_can_send_now();
425                             break;
426                         default:
427                             break;
428                     }
429             }
430             break;
431     }
432 }
433 
434 int btstack_main(void);
435 int btstack_main(void)
436 {
437     le_keyboard_setup();
438 
439 #ifdef HAVE_BTSTACK_STDIN
440     btstack_ring_buffer_init(&ascii_input_buffer, ascii_input_storage, sizeof(ascii_input_storage));
441     btstack_stdin_setup(stdin_process);
442 #endif
443 
444     // turn on!
445     hci_power_control(HCI_POWER_ON);
446 
447     return 0;
448 }
449 /* EXAMPLE_END */
450