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 0x05, 0x07, // Usage Page (Key Codes) 89 0x75, 0x01, // Report Size (1) 90 0x95, 0x08, // Report Count (8) 91 0x05, 0x07, // Usage Page (Key codes) 92 0x19, 0xe0, // Usage Minimum (Keyboard LeftControl) 93 0x29, 0xe7, // Usage Maxium (Keyboard Right GUI) 94 0x15, 0x00, // Logical Minimum (0) 95 0x25, 0x01, // Logical Maximum (1) 96 0x81, 0x02, // Input (Data, Variable, Absolute) 97 98 // Reserved byte (input) 99 100 0x75, 0x01, // Report Size (1) 101 0x95, 0x08, // Report Count (8) 102 0x81, 0x03, // Input (Constant, Variable, Absolute) 103 104 // LED report + padding (output) 105 106 0x95, 0x05, // Report Count (5) 107 0x75, 0x01, // Report Size (1) 108 0x05, 0x08, // Usage Page (LEDs) 109 0x19, 0x01, // Usage Minimum (Num Lock) 110 0x29, 0x05, // Usage Maxium (Kana) 111 0x91, 0x02, // Output (Data, Variable, Absolute) 112 113 0x95, 0x01, // Report Count (1) 114 0x75, 0x03, // Report Size (3) 115 0x91, 0x03, // Output (Constant, Variable, Absolute) 116 117 // Keycodes (input) 118 119 0x95, 0x06, // Report Count (6) 120 0x75, 0x08, // Report Size (8) 121 0x15, 0x00, // Logical Minimum (0) 122 0x25, 0xff, // Logical Maximum (1) 123 0x05, 0x07, // Usage Page (Key codes) 124 0x19, 0x00, // Usage Minimum (Reserved (no event indicated)) 125 0x29, 0xff, // Usage Maxium (Reserved) 126 0x81, 0x00, // Input (Data, Array) 127 128 0xc0, // End collection 129 }; 130 131 // 132 #define CHAR_ILLEGAL 0xff 133 #define CHAR_RETURN '\n' 134 #define CHAR_ESCAPE 27 135 #define CHAR_TAB '\t' 136 #define CHAR_BACKSPACE 0x7f 137 138 // Simplified US Keyboard with Shift modifier 139 140 /** 141 * English (US) 142 */ 143 static const uint8_t keytable_us_none [] = { 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 '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', /* 30-39 */ 149 CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */ 150 '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',', /* 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', '.', 0xa7, /* 97-100 */ 160 }; 161 162 static const uint8_t keytable_us_shift[] = { 163 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */ 164 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 4-13 */ 165 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 14-23 */ 166 'U', 'V', 'W', 'X', 'Y', 'Z', /* 24-29 */ 167 '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', /* 30-39 */ 168 CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */ 169 '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<', /* 45-54 */ 170 '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */ 171 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */ 172 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */ 173 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */ 174 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */ 175 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */ 176 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */ 177 '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */ 178 '6', '7', '8', '9', '0', '.', 0xb1, /* 97-100 */ 179 }; 180 181 // STATE 182 183 static uint8_t hid_service_buffer[300]; 184 static uint8_t device_id_sdp_service_buffer[100]; 185 static const char hid_device_name[] = "BTstack HID Keyboard"; 186 static btstack_packet_callback_registration_t hci_event_callback_registration; 187 static uint16_t hid_cid; 188 static uint8_t hid_boot_device = 0; 189 190 // HID Report sending 191 static uint8_t send_buffer_storage[16]; 192 static btstack_ring_buffer_t send_buffer; 193 static btstack_timer_source_t send_timer; 194 static uint8_t send_modifier; 195 static uint8_t send_keycode; 196 static bool send_active; 197 198 #ifdef HAVE_BTSTACK_STDIN 199 static bd_addr_t device_addr; 200 static const char * device_addr_string = "BC:EC:5D:E6:15:03"; 201 #endif 202 203 static enum { 204 APP_BOOTING, 205 APP_NOT_CONNECTED, 206 APP_CONNECTING, 207 APP_CONNECTED 208 } app_state = APP_BOOTING; 209 210 // HID Keyboard lookup 211 static bool lookup_keycode(uint8_t character, const uint8_t * table, int size, uint8_t * keycode){ 212 int i; 213 for (i=0;i<size;i++){ 214 if (table[i] != character) continue; 215 *keycode = i; 216 return true; 217 } 218 return false; 219 } 220 221 static bool keycode_and_modifer_us_for_character(uint8_t character, uint8_t * keycode, uint8_t * modifier){ 222 bool found; 223 found = lookup_keycode(character, keytable_us_none, sizeof(keytable_us_none), keycode); 224 if (found) { 225 *modifier = 0; // none 226 return true; 227 } 228 found = lookup_keycode(character, keytable_us_shift, sizeof(keytable_us_shift), keycode); 229 if (found) { 230 *modifier = 2; // shift 231 return true; 232 } 233 return false; 234 } 235 236 static void send_report(int modifier, int keycode){ 237 uint8_t report[] = { 0xa1, REPORT_ID, modifier, 0, keycode, 0, 0, 0, 0, 0}; 238 hid_device_send_interrupt_message(hid_cid, &report[0], sizeof(report)); 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, 0x10001, &hid_params); 458 459 printf("HID service record size: %u\n", de_get_len( hid_service_buffer)); 460 sdp_register_service(hid_service_buffer); 461 462 // 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 463 // device info: BlueKitchen GmbH, product 1, version 1 464 device_id_create_sdp_record(device_id_sdp_service_buffer, 0x10003, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1); 465 printf("Device ID SDP service record size: %u\n", de_get_len((uint8_t*)device_id_sdp_service_buffer)); 466 sdp_register_service(device_id_sdp_service_buffer); 467 468 // HID Device 469 hid_device_init(hid_boot_device, sizeof(hid_descriptor_keyboard), hid_descriptor_keyboard); 470 471 // register for HCI events 472 hci_event_callback_registration.callback = &packet_handler; 473 hci_add_event_handler(&hci_event_callback_registration); 474 475 // register for HID events 476 hid_device_register_packet_handler(&packet_handler); 477 478 #ifdef HAVE_BTSTACK_STDIN 479 sscanf_bd_addr(device_addr_string, device_addr); 480 btstack_stdin_setup(stdin_process); 481 #endif 482 483 btstack_ring_buffer_init(&send_buffer, send_buffer_storage, sizeof(send_buffer_storage)); 484 485 // turn on! 486 hci_power_control(HCI_POWER_ON); 487 return 0; 488 } 489 /* LISTING_END */ 490 /* EXAMPLE_END */ 491