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 // setup HID message: A1 = Input Report, Report ID, Payload 237 uint8_t message[] = {0xa1, REPORT_ID, modifier, 0, keycode, 0, 0, 0, 0, 0}; 238 hid_device_send_interrupt_message(hid_cid, &message[0], sizeof(message)); 239 } 240 241 static void trigger_key_up(btstack_timer_source_t * ts){ 242 UNUSED(ts); 243 hid_device_request_can_send_now_event(hid_cid); 244 } 245 246 static void send_next(btstack_timer_source_t * ts) { 247 // get next key from buffer 248 uint8_t character; 249 uint32_t num_bytes_read = 0; 250 btstack_ring_buffer_read(&send_buffer, &character, 1, &num_bytes_read); 251 if (num_bytes_read == 0) { 252 // buffer empty, nothing to send 253 send_active = false; 254 } else { 255 send_active = true; 256 // lookup keycode and modifier using US layout 257 bool found = keycode_and_modifer_us_for_character(character, &send_keycode, &send_modifier); 258 if (found) { 259 // request can send now 260 hid_device_request_can_send_now_event(hid_cid); 261 } else { 262 // restart timer for next character 263 btstack_run_loop_set_timer(ts, TYPING_DELAY_MS); 264 btstack_run_loop_add_timer(ts); 265 } 266 } 267 } 268 269 static void queue_character(char character){ 270 btstack_ring_buffer_write(&send_buffer, (uint8_t *) &character, 1); 271 if (send_active == false) { 272 send_next(&send_timer); 273 } 274 } 275 276 // Demo Application 277 278 #ifdef HAVE_BTSTACK_STDIN 279 280 // On systems with STDIN, we can directly type on the console 281 282 static void stdin_process(char character){ 283 switch (app_state){ 284 case APP_BOOTING: 285 case APP_CONNECTING: 286 // ignore 287 break; 288 case APP_CONNECTED: 289 // add char to send buffer 290 queue_character(character); 291 break; 292 case APP_NOT_CONNECTED: 293 printf("Connecting to %s...\n", bd_addr_to_str(device_addr)); 294 hid_device_connect(device_addr, &hid_cid); 295 break; 296 default: 297 btstack_assert(false); 298 break; 299 } 300 } 301 #else 302 303 // On embedded systems, send constant demo text 304 305 #define TYPING_DEMO_PERIOD_MS 100 306 307 static const char * demo_text = "\n\nHello World!\n\nThis is the BTstack HID Keyboard Demo running on an Embedded Device.\n\n"; 308 static int demo_pos; 309 static btstack_timer_source_t demo_text_timer; 310 311 static void demo_text_timer_handler(btstack_timer_source_t * ts){ 312 UNUSED(ts); 313 314 // queue character 315 uint8_t character = demo_text[demo_pos++]; 316 if (demo_text[demo_pos] == 0){ 317 demo_pos = 0; 318 } 319 queue_character(character); 320 321 // set timer for next character 322 btstack_run_loop_set_timer_handler(&demo_text_timer, demo_text_timer_handler); 323 btstack_run_loop_set_timer(&demo_text_timer, TYPING_DEMO_PERIOD_MS); 324 btstack_run_loop_add_timer(&demo_text_timer); 325 } 326 327 #endif 328 329 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t packet_size){ 330 UNUSED(channel); 331 UNUSED(packet_size); 332 uint8_t status; 333 switch (packet_type){ 334 case HCI_EVENT_PACKET: 335 switch (hci_event_packet_get_type(packet)){ 336 case BTSTACK_EVENT_STATE: 337 if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return; 338 app_state = APP_NOT_CONNECTED; 339 break; 340 341 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 342 // ssp: inform about user confirmation request 343 log_info("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", hci_event_user_confirmation_request_get_numeric_value(packet)); 344 log_info("SSP User Confirmation Auto accept\n"); 345 break; 346 347 case HCI_EVENT_HID_META: 348 switch (hci_event_hid_meta_get_subevent_code(packet)){ 349 case HID_SUBEVENT_CONNECTION_OPENED: 350 status = hid_subevent_connection_opened_get_status(packet); 351 if (status != ERROR_CODE_SUCCESS) { 352 // outgoing connection failed 353 printf("Connection failed, status 0x%x\n", status); 354 app_state = APP_NOT_CONNECTED; 355 hid_cid = 0; 356 return; 357 } 358 app_state = APP_CONNECTED; 359 hid_cid = hid_subevent_connection_opened_get_hid_cid(packet); 360 #ifdef HAVE_BTSTACK_STDIN 361 printf("HID Connected, please start typing...\n"); 362 #else 363 printf("HID Connected, sending demo text...\n"); 364 demo_text_timer_handler(NULL); 365 #endif 366 break; 367 case HID_SUBEVENT_CONNECTION_CLOSED: 368 btstack_run_loop_remove_timer(&send_timer); 369 printf("HID Disconnected\n"); 370 app_state = APP_NOT_CONNECTED; 371 hid_cid = 0; 372 break; 373 case HID_SUBEVENT_CAN_SEND_NOW: 374 if (send_keycode){ 375 send_report(send_modifier, send_keycode); 376 // schedule key up 377 send_keycode = 0; 378 send_modifier = 0; 379 btstack_run_loop_set_timer_handler(&send_timer, trigger_key_up); 380 btstack_run_loop_set_timer(&send_timer, TYPING_KEYDOWN_MS); 381 } else { 382 send_report(0, 0); 383 // schedule next key down 384 btstack_run_loop_set_timer_handler(&send_timer, send_next); 385 btstack_run_loop_set_timer(&send_timer, TYPING_DELAY_MS); 386 } 387 btstack_run_loop_add_timer(&send_timer); 388 break; 389 default: 390 break; 391 } 392 break; 393 default: 394 break; 395 } 396 break; 397 default: 398 break; 399 } 400 } 401 402 /* @section Main Application Setup 403 * 404 * @text Listing MainConfiguration shows main application code. 405 * To run a HID Device service you need to initialize the SDP, and to create and register HID Device record with it. 406 * At the end the Bluetooth stack is started. 407 */ 408 409 /* LISTING_START(MainConfiguration): Setup HID Device */ 410 411 int btstack_main(int argc, const char * argv[]); 412 int btstack_main(int argc, const char * argv[]){ 413 (void)argc; 414 (void)argv; 415 416 // allow to get found by inquiry 417 gap_discoverable_control(1); 418 // use Limited Discoverable Mode; Peripheral; Keyboard as CoD 419 gap_set_class_of_device(0x2540); 420 // set local name to be identified - zeroes will be replaced by actual BD ADDR 421 gap_set_local_name("HID Keyboard Demo 00:00:00:00:00:00"); 422 // allow for role switch in general and sniff mode 423 gap_set_default_link_policy_settings( LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE ); 424 // allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it 425 gap_set_allow_role_switch(true); 426 427 // L2CAP 428 l2cap_init(); 429 430 #ifdef ENABLE_BLE 431 // Initialize LE Security Manager. Needed for cross-transport key derivation 432 sm_init(); 433 #endif 434 435 // SDP Server 436 sdp_init(); 437 memset(hid_service_buffer, 0, sizeof(hid_service_buffer)); 438 439 uint8_t hid_virtual_cable = 0; 440 uint8_t hid_remote_wake = 1; 441 uint8_t hid_reconnect_initiate = 1; 442 uint8_t hid_normally_connectable = 1; 443 444 hid_sdp_record_t hid_params = { 445 // hid sevice subclass 2540 Keyboard, hid counntry code 33 US 446 0x2540, 33, 447 hid_virtual_cable, hid_remote_wake, 448 hid_reconnect_initiate, hid_normally_connectable, 449 hid_boot_device, 450 host_max_latency, host_min_timeout, 451 3200, 452 hid_descriptor_keyboard, 453 sizeof(hid_descriptor_keyboard), 454 hid_device_name 455 }; 456 457 hid_create_sdp_record(hid_service_buffer, sdp_create_service_record_handle(), &hid_params); 458 btstack_assert(de_get_len( hid_service_buffer) <= sizeof(hid_service_buffer)); 459 sdp_register_service(hid_service_buffer); 460 461 // 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 462 // device info: BlueKitchen GmbH, product 1, version 1 463 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); 464 btstack_assert(de_get_len( device_id_sdp_service_buffer) <= sizeof(device_id_sdp_service_buffer)); 465 sdp_register_service(device_id_sdp_service_buffer); 466 467 // HID Device 468 hid_device_init(hid_boot_device, sizeof(hid_descriptor_keyboard), hid_descriptor_keyboard); 469 470 // register for HCI events 471 hci_event_callback_registration.callback = &packet_handler; 472 hci_add_event_handler(&hci_event_callback_registration); 473 474 // register for HID events 475 hid_device_register_packet_handler(&packet_handler); 476 477 #ifdef HAVE_BTSTACK_STDIN 478 sscanf_bd_addr(device_addr_string, device_addr); 479 btstack_stdin_setup(stdin_process); 480 #endif 481 482 btstack_ring_buffer_init(&send_buffer, send_buffer_storage, sizeof(send_buffer_storage)); 483 484 // turn on! 485 hci_power_control(HCI_POWER_ON); 486 return 0; 487 } 488 /* LISTING_END */ 489 /* EXAMPLE_END */ 490