1 /* 2 * Copyright (C) 2017 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_host_demo.c" 39 40 /* 41 * hid_host_demo.c 42 */ 43 44 /* EXAMPLE_START(hid_host_demo): HID Host Classic 45 * 46 * @text This example implements a HID Host. For now, it connects to a fixed device. 47 * It will connect in Report protocol mode if this mode is supported by the HID Device, 48 * otherwise it will fall back to BOOT protocol mode. 49 */ 50 51 #include <inttypes.h> 52 #include <stdio.h> 53 54 #include "btstack_config.h" 55 #include "btstack.h" 56 57 #define MAX_ATTRIBUTE_VALUE_SIZE 300 58 59 static const char * remote_addr_string = "00:1A:7D:DA:71:01"; 60 61 static bd_addr_t remote_addr; 62 63 static btstack_packet_callback_registration_t hci_event_callback_registration; 64 65 // Simplified US Keyboard with Shift modifier 66 67 #define CHAR_ILLEGAL 0xff 68 #define CHAR_RETURN '\n' 69 #define CHAR_ESCAPE 27 70 #define CHAR_TAB '\t' 71 #define CHAR_BACKSPACE 0x7f 72 73 /** 74 * English (US) 75 */ 76 static const uint8_t keytable_us_none [] = { 77 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */ 78 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 4-13 */ 79 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', /* 14-23 */ 80 'u', 'v', 'w', 'x', 'y', 'z', /* 24-29 */ 81 '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', /* 30-39 */ 82 CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */ 83 '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',', /* 45-54 */ 84 '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */ 85 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */ 86 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */ 87 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */ 88 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */ 89 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */ 90 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */ 91 '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */ 92 '6', '7', '8', '9', '0', '.', 0xa7, /* 97-100 */ 93 }; 94 95 static const uint8_t keytable_us_shift[] = { 96 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */ 97 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 4-13 */ 98 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 14-23 */ 99 'U', 'V', 'W', 'X', 'Y', 'Z', /* 24-29 */ 100 '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', /* 30-39 */ 101 CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */ 102 '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<', /* 45-54 */ 103 '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */ 104 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */ 105 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */ 106 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */ 107 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */ 108 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */ 109 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */ 110 '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */ 111 '6', '7', '8', '9', '0', '.', 0xb1, /* 97-100 */ 112 }; 113 114 // SDP 115 static uint8_t hid_descriptor_storage[MAX_ATTRIBUTE_VALUE_SIZE]; 116 117 // App 118 static enum { 119 APP_IDLE, 120 APP_CONNECTED 121 } app_state = APP_IDLE; 122 123 static uint16_t hid_host_cid = 0; 124 static bool hid_host_descriptor_available = false; 125 static hid_protocol_mode_t hid_host_report_mode = HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT; 126 127 /* @section Main application configuration 128 * 129 * @text In the application configuration, L2CAP and HID host are initialized, and the link policies 130 * are set to allow sniff mode and role change. 131 */ 132 133 /* LISTING_START(PanuSetup): Panu setup */ 134 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 135 136 static void hid_host_setup(void){ 137 138 // Initialize L2CAP 139 l2cap_init(); 140 141 #ifdef ENABLE_BLE 142 // Initialize LE Security Manager. Needed for cross-transport key derivation 143 sm_init(); 144 #endif 145 146 // Initialize HID Host 147 hid_host_init(hid_descriptor_storage, sizeof(hid_descriptor_storage)); 148 hid_host_register_packet_handler(packet_handler); 149 150 // Allow sniff mode requests by HID device and support role switch 151 gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH); 152 153 // try to become master on incoming connections 154 hci_set_master_slave_policy(HCI_ROLE_MASTER); 155 156 // register for HCI events 157 hci_event_callback_registration.callback = &packet_handler; 158 hci_add_event_handler(&hci_event_callback_registration); 159 160 // make discoverable to allow HID device to initiate connection 161 gap_discoverable_control(1); 162 163 // Disable stdout buffering 164 setvbuf(stdin, NULL, _IONBF, 0); 165 } 166 /* LISTING_END */ 167 168 /* 169 * @section HID Report Handler 170 * 171 * @text Use BTstack's compact HID Parser to process incoming HID Report in Report protocol mode. 172 * Iterate over all fields and process fields with usage page = 0x07 / Keyboard 173 * Check if SHIFT is down and process first character (don't handle multiple key presses) 174 * 175 */ 176 177 #define NUM_KEYS 6 178 static uint8_t last_keys[NUM_KEYS]; 179 static bool hid_host_caps_lock; 180 181 static uint16_t hid_host_led_report_id; 182 static uint8_t hid_host_led_report_len; 183 static uint8_t hid_host_led_caps_lock_bit; 184 185 static void hid_host_set_leds(void){ 186 if (hid_host_led_report_len == 0) return; 187 188 uint8_t output_report[8]; 189 190 uint8_t caps_lock_report_offset = hid_host_led_caps_lock_bit >> 3; 191 if (caps_lock_report_offset >= sizeof(output_report)) return; 192 193 memset(output_report, 0, sizeof(output_report)); 194 if (hid_host_caps_lock){ 195 output_report[caps_lock_report_offset] = 1 << (hid_host_led_caps_lock_bit & 0x07); 196 } 197 hid_host_send_set_report(hid_host_cid, HID_REPORT_TYPE_OUTPUT, hid_host_led_report_id, output_report, hid_host_led_report_len); 198 } 199 200 static void hid_host_handle_interrupt_report(const uint8_t * report, uint16_t report_len){ 201 // check if HID Input Report 202 if (report_len < 1) return; 203 if (*report != 0xa1) return; 204 205 report++; 206 report_len--; 207 208 btstack_hid_parser_t parser; 209 btstack_hid_parser_init(&parser, 210 hid_descriptor_storage_get_descriptor_data(hid_host_cid), 211 hid_descriptor_storage_get_descriptor_len(hid_host_cid), 212 HID_REPORT_TYPE_INPUT, report, report_len); 213 214 bool shift = hid_host_caps_lock; 215 uint8_t new_keys[NUM_KEYS]; 216 memset(new_keys, 0, sizeof(new_keys)); 217 int new_keys_count = 0; 218 219 while (btstack_hid_parser_has_more(&parser)){ 220 uint16_t usage_page; 221 uint16_t usage; 222 int32_t value; 223 btstack_hid_parser_get_field(&parser, &usage_page, &usage, &value); 224 if (usage_page != 0x07) continue; 225 switch (usage){ 226 case 0x39: 227 // Toggle Caps Lock 228 hid_host_caps_lock = !hid_host_caps_lock; 229 // update LEDs 230 hid_host_set_leds(); 231 break; 232 case 0xe1: 233 case 0xe6: 234 if (value){ 235 shift = 1; 236 } 237 continue; 238 case 0x00: 239 continue; 240 default: 241 break; 242 } 243 if (usage >= sizeof(keytable_us_none)) continue; 244 245 // store new keys 246 new_keys[new_keys_count++] = (uint8_t) usage; 247 248 // check if usage was used last time (and ignore in that case) 249 int i; 250 for (i=0;i<NUM_KEYS;i++){ 251 if (usage == last_keys[i]){ 252 usage = 0; 253 } 254 } 255 if (usage == 0) continue; 256 257 uint8_t key; 258 if (shift){ 259 key = keytable_us_shift[usage]; 260 } else { 261 key = keytable_us_none[usage]; 262 } 263 if (key == CHAR_ILLEGAL) continue; 264 if (key == CHAR_BACKSPACE){ 265 printf("\b \b"); // go back one char, print space, go back one char again 266 continue; 267 } 268 printf("%c", key); 269 } 270 memcpy(last_keys, new_keys, NUM_KEYS); 271 } 272 273 static void hid_host_demo_lookup_caps_lock_led(void){ 274 btstack_hid_usage_iterator_t iterator; 275 const uint8_t *hid_descriptor = hid_descriptor_storage_get_descriptor_data(hid_host_cid); 276 const uint16_t hid_descriptor_len = hid_descriptor_storage_get_descriptor_len(hid_host_cid); 277 btstack_hid_usage_iterator_init(&iterator, hid_descriptor, hid_descriptor_len, HID_REPORT_TYPE_OUTPUT); 278 while (btstack_hid_usage_iterator_has_more(&iterator)){ 279 btstack_hid_usage_item_t item; 280 btstack_hid_usage_iterator_get_item(&iterator, &item); 281 if (item.usage_page == 0x0008){ 282 if (item.usage == 0x0001){ 283 hid_host_led_report_id = item.report_id; 284 hid_host_led_report_len = btstack_hid_get_report_size_for_id(hid_host_led_report_id, HID_REPORT_TYPE_OUTPUT, hid_descriptor, hid_descriptor_len); 285 hid_host_led_caps_lock_bit = item.bit_pos; 286 printf("Found CAPS LOCK in Output Report with ID 0x%04x at bitpos %3u\n", hid_host_led_report_id, hid_host_led_caps_lock_bit); 287 } 288 } 289 } 290 } 291 292 /* 293 * @section Packet Handler 294 * 295 * @text The packet handler responds to various HID events. 296 */ 297 298 /* LISTING_START(packetHandler): Packet Handler */ 299 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) 300 { 301 /* LISTING_PAUSE */ 302 UNUSED(channel); 303 UNUSED(size); 304 305 uint8_t event; 306 bd_addr_t event_addr; 307 uint8_t status; 308 309 /* LISTING_RESUME */ 310 switch (packet_type) { 311 case HCI_EVENT_PACKET: 312 event = hci_event_packet_get_type(packet); 313 314 switch (event) { 315 #ifndef HAVE_BTSTACK_STDIN 316 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING 317 * is received and the example is started in client mode, the remote SDP HID query is started. 318 */ 319 case BTSTACK_EVENT_STATE: 320 if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){ 321 status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid); 322 if (status != ERROR_CODE_SUCCESS){ 323 printf("HID host connect failed, status 0x%02x.\n", status); 324 } 325 } 326 break; 327 #endif 328 /* LISTING_PAUSE */ 329 case HCI_EVENT_PIN_CODE_REQUEST: 330 // inform about pin code request 331 printf("Pin code request - using '0000'\n"); 332 hci_event_pin_code_request_get_bd_addr(packet, event_addr); 333 gap_pin_code_response(event_addr, "0000"); 334 break; 335 336 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 337 // inform about user confirmation request 338 printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8)); 339 printf("SSP User Confirmation Auto accept\n"); 340 break; 341 342 /* LISTING_RESUME */ 343 case HCI_EVENT_HID_META: 344 switch (hci_event_hid_meta_get_subevent_code(packet)){ 345 346 case HID_SUBEVENT_INCOMING_CONNECTION: 347 // There is an incoming connection: we can accept it or decline it. 348 // The hid_host_report_mode in the hid_host_accept_connection function 349 // allows the application to request a protocol mode. 350 // For available protocol modes, see hid_protocol_mode_t in btstack_hid.h file. 351 hid_host_accept_connection(hid_subevent_incoming_connection_get_hid_cid(packet), hid_host_report_mode); 352 break; 353 354 case HID_SUBEVENT_CONNECTION_OPENED: 355 // The status field of this event indicates if the control and interrupt 356 // connections were opened successfully. 357 status = hid_subevent_connection_opened_get_status(packet); 358 if (status != ERROR_CODE_SUCCESS) { 359 printf("Connection failed, status 0x%02x\n", status); 360 app_state = APP_IDLE; 361 hid_host_cid = 0; 362 return; 363 } 364 app_state = APP_CONNECTED; 365 hid_host_descriptor_available = false; 366 hid_host_cid = hid_subevent_connection_opened_get_hid_cid(packet); 367 hid_host_caps_lock = false; 368 hid_host_led_report_len = 0; 369 printf("HID Host connected.\n"); 370 break; 371 372 case HID_SUBEVENT_DESCRIPTOR_AVAILABLE: 373 // This event will follows HID_SUBEVENT_CONNECTION_OPENED event. 374 // For incoming connections, i.e. HID Device initiating the connection, 375 // the HID_SUBEVENT_DESCRIPTOR_AVAILABLE is delayed, and some HID 376 // reports may be received via HID_SUBEVENT_REPORT event. It is up to 377 // the application if these reports should be buffered or ignored until 378 // the HID descriptor is available. 379 status = hid_subevent_descriptor_available_get_status(packet); 380 if (status == ERROR_CODE_SUCCESS){ 381 hid_host_descriptor_available = true; 382 printf("HID Descriptor available, please start typing.\n"); 383 hid_host_demo_lookup_caps_lock_led(); 384 } else { 385 printf("Cannot handle input report, HID Descriptor is not available, status 0x%02x\n", status); 386 } 387 break; 388 389 case HID_SUBEVENT_REPORT: 390 // Handle input report. 391 if (hid_host_descriptor_available){ 392 hid_host_handle_interrupt_report(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet)); 393 } else { 394 printf_hexdump(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet)); 395 } 396 break; 397 398 case HID_SUBEVENT_SET_PROTOCOL_RESPONSE: 399 // For incoming connections, the library will set the protocol mode of the 400 // HID Device as requested in the call to hid_host_accept_connection. The event 401 // reports the result. For connections initiated by calling hid_host_connect, 402 // this event will occur only if the established report mode is boot mode. 403 status = hid_subevent_set_protocol_response_get_handshake_status(packet); 404 if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){ 405 printf("Error set protocol, status 0x%02x\n", status); 406 break; 407 } 408 switch ((hid_protocol_mode_t)hid_subevent_set_protocol_response_get_protocol_mode(packet)){ 409 case HID_PROTOCOL_MODE_BOOT: 410 printf("Protocol mode set: BOOT.\n"); 411 break; 412 case HID_PROTOCOL_MODE_REPORT: 413 printf("Protocol mode set: REPORT.\n"); 414 break; 415 default: 416 printf("Unknown protocol mode.\n"); 417 break; 418 } 419 break; 420 421 case HID_SUBEVENT_CONNECTION_CLOSED: 422 // The connection was closed. 423 hid_host_cid = 0; 424 hid_host_descriptor_available = false; 425 printf("HID Host disconnected.\n"); 426 break; 427 428 default: 429 break; 430 } 431 break; 432 default: 433 break; 434 } 435 break; 436 default: 437 break; 438 } 439 } 440 /* LISTING_END */ 441 442 #ifdef HAVE_BTSTACK_STDIN 443 static void show_usage(void){ 444 bd_addr_t iut_address; 445 gap_local_bd_addr(iut_address); 446 printf("\n--- Bluetooth HID Host Console %s ---\n", bd_addr_to_str(iut_address)); 447 printf("c - Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string); 448 printf("C - Disconnect\n"); 449 450 printf("\n"); 451 printf("Ctrl-c - exit\n"); 452 printf("---\n"); 453 } 454 455 static void stdin_process(char cmd){ 456 uint8_t status = ERROR_CODE_SUCCESS; 457 switch (cmd){ 458 case 'c': 459 printf("Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string); 460 status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid); 461 break; 462 case 'C': 463 printf("Disconnect...\n"); 464 hid_host_disconnect(hid_host_cid); 465 break; 466 case '\n': 467 case '\r': 468 break; 469 default: 470 show_usage(); 471 break; 472 } 473 if (status != ERROR_CODE_SUCCESS){ 474 printf("HID host cmd \'%c\' failed, status 0x%02x\n", cmd, status); 475 } 476 } 477 #endif 478 479 int btstack_main(int argc, const char * argv[]); 480 int btstack_main(int argc, const char * argv[]){ 481 482 (void)argc; 483 (void)argv; 484 485 hid_host_setup(); 486 487 // parse human readable Bluetooth address 488 sscanf_bd_addr(remote_addr_string, remote_addr); 489 490 #ifdef HAVE_BTSTACK_STDIN 491 btstack_stdin_setup(stdin_process); 492 #endif 493 494 // Turn on the device 495 hci_power_control(HCI_POWER_ON); 496 return 0; 497 } 498 499 /* EXAMPLE_END */ 500