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__ "hid_keyboard_demo.c" 39 40 // ***************************************************************************** 41 /* EXAMPLE_START(hid_keyboard_demo): HID Keyboard Classic 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 // ***************************************************************************** 48 49 50 #include <stdint.h> 51 #include <stdio.h> 52 #include <stdlib.h> 53 #include <string.h> 54 #include <inttypes.h> 55 56 #include "btstack.h" 57 58 #ifdef HAVE_BTSTACK_STDIN 59 #include "btstack_stdin.h" 60 #endif 61 62 // to enable demo text on POSIX systems 63 // #undef HAVE_BTSTACK_STDIN 64 65 // timing of keypresses 66 #define TYPING_KEYDOWN_MS 20 67 #define TYPING_DELAY_MS 20 68 69 // When not set to 0xffff, sniff and sniff subrating are enabled 70 static uint16_t host_max_latency = 1600; 71 static uint16_t host_min_timeout = 3200; 72 73 #define REPORT_ID 0x01 74 75 // close to USB HID Specification 1.1, Appendix B.1 76 const uint8_t hid_descriptor_keyboard[] = { 77 78 0x05, 0x01, // Usage Page (Generic Desktop) 79 0x09, 0x06, // Usage (Keyboard) 80 0xa1, 0x01, // Collection (Application) 81 82 // Report ID 83 84 0x85, REPORT_ID, // Report ID 85 86 // Modifier byte (input) 87 88 0x75, 0x01, // Report Size (1) 89 0x95, 0x08, // Report Count (8) 90 0x05, 0x07, // Usage Page (Key codes) 91 0x19, 0xe0, // Usage Minimum (Keyboard LeftControl) 92 0x29, 0xe7, // Usage Maximum (Keyboard Right GUI) 93 0x15, 0x00, // Logical Minimum (0) 94 0x25, 0x01, // Logical Maximum (1) 95 0x81, 0x02, // Input (Data, Variable, Absolute) 96 97 // Reserved byte (input) 98 99 0x75, 0x01, // Report Size (1) 100 0x95, 0x08, // Report Count (8) 101 0x81, 0x03, // Input (Constant, Variable, Absolute) 102 103 // LED report + padding (output) 104 105 0x95, 0x05, // Report Count (5) 106 0x75, 0x01, // Report Size (1) 107 0x05, 0x08, // Usage Page (LEDs) 108 0x19, 0x01, // Usage Minimum (Num Lock) 109 0x29, 0x05, // Usage Maximum (Kana) 110 0x91, 0x02, // Output (Data, Variable, Absolute) 111 112 0x95, 0x01, // Report Count (1) 113 0x75, 0x03, // Report Size (3) 114 0x91, 0x03, // Output (Constant, Variable, Absolute) 115 116 // Keycodes (input) 117 118 0x95, 0x06, // Report Count (6) 119 0x75, 0x08, // Report Size (8) 120 0x15, 0x00, // Logical Minimum (0) 121 0x25, 0xff, // Logical Maximum (1) 122 0x05, 0x07, // Usage Page (Key codes) 123 0x19, 0x00, // Usage Minimum (Reserved (no event indicated)) 124 0x29, 0xff, // Usage Maximum (Reserved) 125 0x81, 0x00, // Input (Data, Array) 126 127 0xc0, // End collection 128 }; 129 130 // 131 #define CHAR_ILLEGAL 0xff 132 #define CHAR_RETURN '\n' 133 #define CHAR_ESCAPE 27 134 #define CHAR_TAB '\t' 135 #define CHAR_BACKSPACE 0x7f 136 137 // Simplified US Keyboard with Shift modifier 138 139 /** 140 * English (US) 141 */ 142 static const uint8_t keytable_us_none [] = { 143 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */ 144 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 4-13 */ 145 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', /* 14-23 */ 146 'u', 'v', 'w', 'x', 'y', 'z', /* 24-29 */ 147 '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', /* 30-39 */ 148 CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */ 149 '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',', /* 45-54 */ 150 '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */ 151 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */ 152 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */ 153 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */ 154 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */ 155 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */ 156 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */ 157 '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */ 158 '6', '7', '8', '9', '0', '.', 0xa7, /* 97-100 */ 159 }; 160 161 static const uint8_t keytable_us_shift[] = { 162 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */ 163 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 4-13 */ 164 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 14-23 */ 165 'U', 'V', 'W', 'X', 'Y', 'Z', /* 24-29 */ 166 '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', /* 30-39 */ 167 CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */ 168 '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<', /* 45-54 */ 169 '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */ 170 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */ 171 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */ 172 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */ 173 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */ 174 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */ 175 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */ 176 '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */ 177 '6', '7', '8', '9', '0', '.', 0xb1, /* 97-100 */ 178 }; 179 180 // STATE 181 182 static uint8_t hid_service_buffer[300]; 183 static uint8_t device_id_sdp_service_buffer[100]; 184 static const char hid_device_name[] = "BTstack HID Keyboard"; 185 static btstack_packet_callback_registration_t hci_event_callback_registration; 186 static uint16_t hid_cid; 187 static uint8_t hid_boot_device = 0; 188 189 // HID Report sending 190 static uint8_t send_buffer_storage[16]; 191 static btstack_ring_buffer_t send_buffer; 192 static btstack_timer_source_t send_timer; 193 static uint8_t send_modifier; 194 static uint8_t send_keycode; 195 static bool send_active; 196 197 #ifdef HAVE_BTSTACK_STDIN 198 static bd_addr_t device_addr; 199 static const char * device_addr_string = "BC:EC:5D:E6:15:03"; 200 #endif 201 202 static enum { 203 APP_BOOTING, 204 APP_NOT_CONNECTED, 205 APP_CONNECTING, 206 APP_CONNECTED 207 } app_state = APP_BOOTING; 208 209 // HID Keyboard lookup 210 static bool lookup_keycode(uint8_t character, const uint8_t * table, int size, uint8_t * keycode){ 211 int i; 212 for (i=0;i<size;i++){ 213 if (table[i] != character) continue; 214 *keycode = i; 215 return true; 216 } 217 return false; 218 } 219 220 static bool keycode_and_modifer_us_for_character(uint8_t character, uint8_t * keycode, uint8_t * modifier){ 221 bool found; 222 found = lookup_keycode(character, keytable_us_none, sizeof(keytable_us_none), keycode); 223 if (found) { 224 *modifier = 0; // none 225 return true; 226 } 227 found = lookup_keycode(character, keytable_us_shift, sizeof(keytable_us_shift), keycode); 228 if (found) { 229 *modifier = 2; // shift 230 return true; 231 } 232 return false; 233 } 234 235 static void send_report(int modifier, int keycode){ 236 uint8_t report[] = { 0xa1, REPORT_ID, modifier, 0, keycode, 0, 0, 0, 0, 0}; 237 hid_device_send_interrupt_message(hid_cid, &report[0], sizeof(report)); 238 } 239 240 static void trigger_key_up(btstack_timer_source_t * ts){ 241 UNUSED(ts); 242 hid_device_request_can_send_now_event(hid_cid); 243 } 244 245 static void send_next(btstack_timer_source_t * ts) { 246 // get next key from buffer 247 uint8_t character; 248 uint32_t num_bytes_read = 0; 249 btstack_ring_buffer_read(&send_buffer, &character, 1, &num_bytes_read); 250 if (num_bytes_read == 0) { 251 // buffer empty, nothing to send 252 send_active = false; 253 } else { 254 send_active = true; 255 // lookup keycode and modifier using US layout 256 bool found = keycode_and_modifer_us_for_character(character, &send_keycode, &send_modifier); 257 if (found) { 258 // request can send now 259 hid_device_request_can_send_now_event(hid_cid); 260 } else { 261 // restart timer for next character 262 btstack_run_loop_set_timer(ts, TYPING_DELAY_MS); 263 btstack_run_loop_add_timer(ts); 264 } 265 } 266 } 267 268 static void queue_character(char character){ 269 btstack_ring_buffer_write(&send_buffer, (uint8_t *) &character, 1); 270 if (send_active == false) { 271 send_next(&send_timer); 272 } 273 } 274 275 // Demo Application 276 277 #ifdef HAVE_BTSTACK_STDIN 278 279 // On systems with STDIN, we can directly type on the console 280 281 static void stdin_process(char character){ 282 switch (app_state){ 283 case APP_BOOTING: 284 case APP_CONNECTING: 285 // ignore 286 break; 287 case APP_CONNECTED: 288 // add char to send buffer 289 queue_character(character); 290 break; 291 case APP_NOT_CONNECTED: 292 printf("Connecting to %s...\n", bd_addr_to_str(device_addr)); 293 hid_device_connect(device_addr, &hid_cid); 294 break; 295 default: 296 btstack_assert(false); 297 break; 298 } 299 } 300 #else 301 302 // On embedded systems, send constant demo text 303 304 #define TYPING_DEMO_PERIOD_MS 100 305 306 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n"; 307 static int demo_pos; 308 static btstack_timer_source_t demo_text_timer; 309 310 static void demo_text_timer_handler(btstack_timer_source_t * ts){ 311 UNUSED(ts); 312 313 // queue character 314 uint8_t character = demo_text[demo_pos++]; 315 if (demo_text[demo_pos] == 0){ 316 demo_pos = 0; 317 } 318 queue_character(character); 319 320 // set timer for next character 321 btstack_run_loop_set_timer_handler(&demo_text_timer, demo_text_timer_handler); 322 btstack_run_loop_set_timer(&demo_text_timer, TYPING_DEMO_PERIOD_MS); 323 btstack_run_loop_add_timer(&demo_text_timer); 324 } 325 326 #endif 327 328 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t packet_size){ 329 UNUSED(channel); 330 UNUSED(packet_size); 331 uint8_t status; 332 switch (packet_type){ 333 case HCI_EVENT_PACKET: 334 switch (hci_event_packet_get_type(packet)){ 335 case BTSTACK_EVENT_STATE: 336 if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return; 337 app_state = APP_NOT_CONNECTED; 338 break; 339 340 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 341 // ssp: inform about user confirmation request 342 log_info("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", hci_event_user_confirmation_request_get_numeric_value(packet)); 343 log_info("SSP User Confirmation Auto accept\n"); 344 break; 345 346 case HCI_EVENT_HID_META: 347 switch (hci_event_hid_meta_get_subevent_code(packet)){ 348 case HID_SUBEVENT_CONNECTION_OPENED: 349 status = hid_subevent_connection_opened_get_status(packet); 350 if (status != ERROR_CODE_SUCCESS) { 351 // outgoing connection failed 352 printf("Connection failed, status 0x%x\n", status); 353 app_state = APP_NOT_CONNECTED; 354 hid_cid = 0; 355 return; 356 } 357 app_state = APP_CONNECTED; 358 hid_cid = hid_subevent_connection_opened_get_hid_cid(packet); 359 #ifdef HAVE_BTSTACK_STDIN 360 printf("HID Connected, please start typing...\n"); 361 #else 362 printf("HID Connected, sending demo text...\n"); 363 demo_text_timer_handler(NULL); 364 #endif 365 break; 366 case HID_SUBEVENT_CONNECTION_CLOSED: 367 btstack_run_loop_remove_timer(&send_timer); 368 printf("HID Disconnected\n"); 369 app_state = APP_NOT_CONNECTED; 370 hid_cid = 0; 371 break; 372 case HID_SUBEVENT_CAN_SEND_NOW: 373 if (send_keycode){ 374 send_report(send_modifier, send_keycode); 375 // schedule key up 376 send_keycode = 0; 377 send_modifier = 0; 378 btstack_run_loop_set_timer_handler(&send_timer, trigger_key_up); 379 btstack_run_loop_set_timer(&send_timer, TYPING_KEYDOWN_MS); 380 } else { 381 send_report(0, 0); 382 // schedule next key down 383 btstack_run_loop_set_timer_handler(&send_timer, send_next); 384 btstack_run_loop_set_timer(&send_timer, TYPING_DELAY_MS); 385 } 386 btstack_run_loop_add_timer(&send_timer); 387 break; 388 default: 389 break; 390 } 391 break; 392 default: 393 break; 394 } 395 break; 396 default: 397 break; 398 } 399 } 400 401 /* @section Main Application Setup 402 * 403 * @text Listing MainConfiguration shows main application code. 404 * To run a HID Device service you need to initialize the SDP, and to create and register HID Device record with it. 405 * At the end the Bluetooth stack is started. 406 */ 407 408 /* LISTING_START(MainConfiguration): Setup HID Device */ 409 410 int btstack_main(int argc, const char * argv[]); 411 int btstack_main(int argc, const char * argv[]){ 412 (void)argc; 413 (void)argv; 414 415 // allow to get found by inquiry 416 gap_discoverable_control(1); 417 // use Limited Discoverable Mode; Peripheral; Keyboard as CoD 418 gap_set_class_of_device(0x2540); 419 // set local name to be identified - zeroes will be replaced by actual BD ADDR 420 gap_set_local_name("HID Keyboard Demo 00:00:00:00:00:00"); 421 // allow for role switch in general and sniff mode 422 gap_set_default_link_policy_settings( LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE ); 423 // allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it 424 gap_set_allow_role_switch(true); 425 426 // L2CAP 427 l2cap_init(); 428 429 #ifdef ENABLE_BLE 430 // Initialize LE Security Manager. Needed for cross-transport key derivation 431 sm_init(); 432 #endif 433 434 // SDP Server 435 sdp_init(); 436 memset(hid_service_buffer, 0, sizeof(hid_service_buffer)); 437 438 uint8_t hid_virtual_cable = 0; 439 uint8_t hid_remote_wake = 1; 440 uint8_t hid_reconnect_initiate = 1; 441 uint8_t hid_normally_connectable = 1; 442 443 hid_sdp_record_t hid_params = { 444 // hid sevice subclass 2540 Keyboard, hid counntry code 33 US 445 0x2540, 33, 446 hid_virtual_cable, hid_remote_wake, 447 hid_reconnect_initiate, hid_normally_connectable, 448 hid_boot_device, 449 host_max_latency, host_min_timeout, 450 3200, 451 hid_descriptor_keyboard, 452 sizeof(hid_descriptor_keyboard), 453 hid_device_name 454 }; 455 456 hid_create_sdp_record(hid_service_buffer, sdp_create_service_record_handle(), &hid_params); 457 btstack_assert(de_get_len( hid_service_buffer) <= sizeof(hid_service_buffer)); 458 sdp_register_service(hid_service_buffer); 459 460 // 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 461 // device info: BlueKitchen GmbH, product 1, version 1 462 device_id_create_sdp_record(device_id_sdp_service_buffer, sdp_create_service_record_handle(), DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1); 463 btstack_assert(de_get_len( device_id_sdp_service_buffer) <= sizeof(device_id_sdp_service_buffer)); 464 sdp_register_service(device_id_sdp_service_buffer); 465 466 // HID Device 467 hid_device_init(hid_boot_device, sizeof(hid_descriptor_keyboard), hid_descriptor_keyboard); 468 469 // register for HCI events 470 hci_event_callback_registration.callback = &packet_handler; 471 hci_add_event_handler(&hci_event_callback_registration); 472 473 // register for HID events 474 hid_device_register_packet_handler(&packet_handler); 475 476 #ifdef HAVE_BTSTACK_STDIN 477 sscanf_bd_addr(device_addr_string, device_addr); 478 btstack_stdin_setup(stdin_process); 479 #endif 480 481 btstack_ring_buffer_init(&send_buffer, send_buffer_storage, sizeof(send_buffer_storage)); 482 483 // turn on! 484 hci_power_control(HCI_POWER_ON); 485 return 0; 486 } 487 /* LISTING_END */ 488 /* EXAMPLE_END */ 489