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 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__ "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 an HID Host. For now, it connnects to a fixed device, queries the HID SDP 47 * record and opens the HID Control + Interrupt channels 48 */ 49 50 #include <inttypes.h> 51 #include <stdio.h> 52 53 #include "btstack_config.h" 54 #include "btstack.h" 55 56 #define MAX_ATTRIBUTE_VALUE_SIZE 300 57 58 // SDP 59 static uint8_t hid_descriptor[MAX_ATTRIBUTE_VALUE_SIZE]; 60 static uint16_t hid_descriptor_len; 61 62 static uint16_t hid_control_psm; 63 static uint16_t hid_interrupt_psm; 64 65 static uint8_t attribute_value[MAX_ATTRIBUTE_VALUE_SIZE]; 66 static const unsigned int attribute_value_buffer_size = MAX_ATTRIBUTE_VALUE_SIZE; 67 68 // L2CAP 69 static uint16_t l2cap_hid_control_cid; 70 static uint16_t l2cap_hid_interrupt_cid; 71 72 // MBP 2016 73 static const char * remote_addr_string = "F4-0F-24-3B-1B-E1"; 74 // iMpulse static const char * remote_addr_string = "64:6E:6C:C1:AA:B5"; 75 76 static bd_addr_t remote_addr; 77 78 static btstack_packet_callback_registration_t hci_event_callback_registration; 79 80 // Simplified US Keyboard with Shift modifier 81 82 #define CHAR_ILLEGAL 0xff 83 #define CHAR_RETURN '\n' 84 #define CHAR_ESCAPE 27 85 #define CHAR_TAB '\t' 86 #define CHAR_BACKSPACE 0x7f 87 88 /** 89 * English (US) 90 */ 91 static const uint8_t keytable_us_none [] = { 92 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */ 93 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 4-13 */ 94 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', /* 14-23 */ 95 'u', 'v', 'w', 'x', 'y', 'z', /* 24-29 */ 96 '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', /* 30-39 */ 97 CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */ 98 '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',', /* 45-54 */ 99 '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */ 100 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */ 101 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */ 102 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */ 103 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */ 104 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */ 105 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */ 106 '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */ 107 '6', '7', '8', '9', '0', '.', 0xa7, /* 97-100 */ 108 }; 109 110 static const uint8_t keytable_us_shift[] = { 111 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */ 112 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 4-13 */ 113 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 14-23 */ 114 'U', 'V', 'W', 'X', 'Y', 'Z', /* 24-29 */ 115 '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', /* 30-39 */ 116 CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */ 117 '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<', /* 45-54 */ 118 '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */ 119 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */ 120 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */ 121 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */ 122 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */ 123 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */ 124 CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */ 125 '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */ 126 '6', '7', '8', '9', '0', '.', 0xb1, /* 97-100 */ 127 }; 128 129 130 /* @section Main application configuration 131 * 132 * @text In the application configuration, L2CAP is initialized 133 */ 134 135 /* LISTING_START(PanuSetup): Panu setup */ 136 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 137 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 138 139 static void hid_host_setup(void){ 140 141 // Initialize L2CAP 142 l2cap_init(); 143 144 // register L2CAP Services for reconnections 145 l2cap_register_service(packet_handler, PSM_HID_INTERRUPT, 0xffff, gap_get_security_level()); 146 l2cap_register_service(packet_handler, PSM_HID_CONTROL, 0xffff, gap_get_security_level()); 147 148 // Allow sniff mode requests by HID device and support role switch 149 gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH); 150 151 // try to become master on incoming connections 152 hci_set_master_slave_policy(HCI_ROLE_MASTER); 153 154 // register for HCI events 155 hci_event_callback_registration.callback = &packet_handler; 156 hci_add_event_handler(&hci_event_callback_registration); 157 158 // Disable stdout buffering 159 setbuf(stdout, NULL); 160 } 161 /* LISTING_END */ 162 163 /* @section SDP parser callback 164 * 165 * @text The SDP parsers retrieves the BNEP PAN UUID as explained in 166 * Section [on SDP BNEP Query example](#sec:sdpbnepqueryExample}. 167 */ 168 169 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) { 170 171 UNUSED(packet_type); 172 UNUSED(channel); 173 UNUSED(size); 174 175 des_iterator_t attribute_list_it; 176 des_iterator_t additional_des_it; 177 des_iterator_t prot_it; 178 uint8_t *des_element; 179 uint8_t *element; 180 uint32_t uuid; 181 uint8_t status; 182 183 switch (hci_event_packet_get_type(packet)){ 184 case SDP_EVENT_QUERY_ATTRIBUTE_VALUE: 185 if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= attribute_value_buffer_size) { 186 attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet); 187 if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) { 188 switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) { 189 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST: 190 for (des_iterator_init(&attribute_list_it, attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) { 191 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue; 192 des_element = des_iterator_get_element(&attribute_list_it); 193 des_iterator_init(&prot_it, des_element); 194 element = des_iterator_get_element(&prot_it); 195 if (!element) continue; 196 if (de_get_element_type(element) != DE_UUID) continue; 197 uuid = de_get_uuid32(element); 198 des_iterator_next(&prot_it); 199 switch (uuid){ 200 case BLUETOOTH_PROTOCOL_L2CAP: 201 if (!des_iterator_has_more(&prot_it)) continue; 202 de_element_get_uint16(des_iterator_get_element(&prot_it), &hid_control_psm); 203 printf("HID Control PSM: 0x%04x\n", (int) hid_control_psm); 204 break; 205 default: 206 break; 207 } 208 } 209 break; 210 case BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS: 211 for (des_iterator_init(&attribute_list_it, attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) { 212 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue; 213 des_element = des_iterator_get_element(&attribute_list_it); 214 for (des_iterator_init(&additional_des_it, des_element); des_iterator_has_more(&additional_des_it); des_iterator_next(&additional_des_it)) { 215 if (des_iterator_get_type(&additional_des_it) != DE_DES) continue; 216 des_element = des_iterator_get_element(&additional_des_it); 217 des_iterator_init(&prot_it, des_element); 218 element = des_iterator_get_element(&prot_it); 219 if (!element) continue; 220 if (de_get_element_type(element) != DE_UUID) continue; 221 uuid = de_get_uuid32(element); 222 des_iterator_next(&prot_it); 223 switch (uuid){ 224 case BLUETOOTH_PROTOCOL_L2CAP: 225 if (!des_iterator_has_more(&prot_it)) continue; 226 de_element_get_uint16(des_iterator_get_element(&prot_it), &hid_interrupt_psm); 227 printf("HID Interrupt PSM: 0x%04x\n", (int) hid_interrupt_psm); 228 break; 229 default: 230 break; 231 } 232 } 233 } 234 break; 235 case BLUETOOTH_ATTRIBUTE_HID_DESCRIPTOR_LIST: 236 for (des_iterator_init(&attribute_list_it, attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) { 237 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue; 238 des_element = des_iterator_get_element(&attribute_list_it); 239 for (des_iterator_init(&additional_des_it, des_element); des_iterator_has_more(&additional_des_it); des_iterator_next(&additional_des_it)) { 240 if (des_iterator_get_type(&additional_des_it) != DE_STRING) continue; 241 element = des_iterator_get_element(&additional_des_it); 242 const uint8_t * descriptor = de_get_string(element); 243 hid_descriptor_len = de_get_data_size(element); 244 memcpy(hid_descriptor, descriptor, hid_descriptor_len); 245 printf("HID Descriptor:\n"); 246 printf_hexdump(hid_descriptor, hid_descriptor_len); 247 } 248 } 249 break; 250 default: 251 break; 252 } 253 } 254 } else { 255 fprintf(stderr, "SDP attribute value buffer size exceeded: available %d, required %d\n", attribute_value_buffer_size, sdp_event_query_attribute_byte_get_attribute_length(packet)); 256 } 257 break; 258 259 case SDP_EVENT_QUERY_COMPLETE: 260 if (sdp_event_query_complete_get_status(packet) != ERROR_CODE_SUCCESS){ 261 printf("SDP Query failed\n"); 262 break; 263 } 264 if ((l2cap_hid_interrupt_cid != 0) && (l2cap_hid_control_cid != 0)){ 265 printf("HID device re-connected\n"); 266 break; 267 } 268 if (!hid_control_psm) { 269 hid_control_psm = BLUETOOTH_PSM_HID_CONTROL; 270 printf("HID Control PSM missing, using default 0x%04x\n", hid_control_psm); 271 } 272 if (!hid_interrupt_psm) { 273 hid_interrupt_psm = BLUETOOTH_PSM_HID_INTERRUPT; 274 printf("HID Interrupt PSM missing, using default 0x%04x\n", hid_interrupt_psm); 275 break; 276 } 277 printf("Setup HID\n"); 278 status = l2cap_create_channel(packet_handler, remote_addr, hid_control_psm, 48, &l2cap_hid_control_cid); 279 if (status){ 280 printf("Connecting to HID Control failed: 0x%02x\n", status); 281 } 282 break; 283 284 default: 285 break; 286 } 287 } 288 289 /* 290 * @section HID Report Handler 291 * 292 * @text Use BTstack's compact HID Parser to process incoming HID Report 293 * Iterate over all fields and process fields with usage page = 0x07 / Keyboard 294 * Check if SHIFT is down and process first character (don't handle multiple key presses) 295 * 296 */ 297 #define NUM_KEYS 6 298 static uint8_t last_keys[NUM_KEYS]; 299 static void hid_host_handle_interrupt_report(const uint8_t * report, uint16_t report_len){ 300 // check if HID Input Report 301 if (report_len < 1) return; 302 if (*report != 0xa1) return; 303 report++; 304 report_len--; 305 btstack_hid_parser_t parser; 306 btstack_hid_parser_init(&parser, hid_descriptor, hid_descriptor_len, HID_REPORT_TYPE_INPUT, report, report_len); 307 int shift = 0; 308 uint8_t new_keys[NUM_KEYS]; 309 memset(new_keys, 0, sizeof(new_keys)); 310 int new_keys_count = 0; 311 while (btstack_hid_parser_has_more(&parser)){ 312 uint16_t usage_page; 313 uint16_t usage; 314 int32_t value; 315 btstack_hid_parser_get_field(&parser, &usage_page, &usage, &value); 316 if (usage_page != 0x07) continue; 317 switch (usage){ 318 case 0xe1: 319 case 0xe6: 320 if (value){ 321 shift = 1; 322 } 323 continue; 324 case 0x00: 325 continue; 326 default: 327 break; 328 } 329 if (usage >= sizeof(keytable_us_none)) continue; 330 331 // store new keys 332 new_keys[new_keys_count++] = usage; 333 334 // check if usage was used last time (and ignore in that case) 335 int i; 336 for (i=0;i<NUM_KEYS;i++){ 337 if (usage == last_keys[i]){ 338 usage = 0; 339 } 340 } 341 if (usage == 0) continue; 342 343 uint8_t key; 344 if (shift){ 345 key = keytable_us_shift[usage]; 346 } else { 347 key = keytable_us_none[usage]; 348 } 349 if (key == CHAR_ILLEGAL) continue; 350 if (key == CHAR_BACKSPACE){ 351 printf("\b \b"); // go back one char, print space, go back one char again 352 continue; 353 } 354 printf("%c", key); 355 } 356 memcpy(last_keys, new_keys, NUM_KEYS); 357 } 358 359 /* 360 * @section Packet Handler 361 * 362 * @text The packet handler responds to various HCI Events. 363 */ 364 365 /* LISTING_START(packetHandler): Packet Handler */ 366 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) 367 { 368 /* LISTING_PAUSE */ 369 uint8_t event; 370 bd_addr_t event_addr; 371 uint8_t status; 372 uint16_t l2cap_cid; 373 374 /* LISTING_RESUME */ 375 switch (packet_type) { 376 case HCI_EVENT_PACKET: 377 event = hci_event_packet_get_type(packet); 378 switch (event) { 379 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING 380 * is received and the example is started in client mode, the remote SDP HID query is started. 381 */ 382 case BTSTACK_EVENT_STATE: 383 if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){ 384 printf("Start SDP HID query for remote HID Device %s.\n", bd_addr_to_str(remote_addr)); 385 sdp_client_query_uuid16(&handle_sdp_client_query_result, remote_addr, BLUETOOTH_SERVICE_CLASS_HUMAN_INTERFACE_DEVICE_SERVICE); 386 } 387 break; 388 389 /* LISTING_PAUSE */ 390 case HCI_EVENT_PIN_CODE_REQUEST: 391 // inform about pin code request 392 printf("Pin code request - using '0000'\n"); 393 hci_event_pin_code_request_get_bd_addr(packet, event_addr); 394 gap_pin_code_response(event_addr, "0000"); 395 break; 396 397 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 398 // inform about user confirmation request 399 printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8)); 400 printf("SSP User Confirmation Auto accept\n"); 401 break; 402 403 /* LISTING_RESUME */ 404 case L2CAP_EVENT_INCOMING_CONNECTION: 405 l2cap_cid = l2cap_event_incoming_connection_get_local_cid(packet); 406 switch (l2cap_event_incoming_connection_get_psm(packet)){ 407 case PSM_HID_CONTROL: 408 case PSM_HID_INTERRUPT: 409 l2cap_accept_connection(l2cap_cid); 410 break; 411 default: 412 l2cap_decline_connection(l2cap_cid); 413 break; 414 } 415 break; 416 case L2CAP_EVENT_CHANNEL_OPENED: 417 status = packet[2]; 418 if (status){ 419 printf("L2CAP Connection failed: 0x%02x\n", status); 420 break; 421 } 422 l2cap_cid = l2cap_event_channel_opened_get_local_cid(packet); 423 switch (l2cap_event_channel_opened_get_psm(packet)){ 424 case PSM_HID_CONTROL: 425 if (l2cap_event_channel_opened_get_incoming(packet) == 0) { 426 status = l2cap_create_channel(packet_handler, remote_addr, hid_interrupt_psm, 48, &l2cap_hid_interrupt_cid); 427 if (status){ 428 printf("Connecting to HID Interrupt failed: 0x%02x\n", status); 429 break; 430 } 431 } 432 l2cap_hid_control_cid = l2cap_cid; 433 break; 434 case PSM_HID_INTERRUPT: 435 l2cap_hid_interrupt_cid = l2cap_cid; 436 break; 437 default: 438 break; 439 } 440 441 if ((l2cap_hid_control_cid != 0) && (l2cap_hid_interrupt_cid != 0)){ 442 if (hid_descriptor_len == 0){ 443 printf("Start SDP HID query to get HID Descriptor\n"); 444 sdp_client_query_uuid16(&handle_sdp_client_query_result, remote_addr, BLUETOOTH_SERVICE_CLASS_HUMAN_INTERFACE_DEVICE_SERVICE); 445 } else { 446 printf("HID Connection established\n"); 447 } 448 } 449 break; 450 case L2CAP_EVENT_CHANNEL_CLOSED: 451 if ((l2cap_hid_control_cid != 0) && (l2cap_hid_interrupt_cid != 0)){ 452 printf("HID Connection closed\n"); 453 hid_descriptor_len = 0; 454 } 455 l2cap_cid = l2cap_event_channel_closed_get_local_cid(packet); 456 if (l2cap_cid == l2cap_hid_control_cid){ 457 l2cap_hid_control_cid = 0; 458 } 459 if (l2cap_cid == l2cap_hid_interrupt_cid){ 460 l2cap_hid_interrupt_cid = 0; 461 } 462 default: 463 break; 464 } 465 break; 466 case L2CAP_DATA_PACKET: 467 // for now, just dump incoming data 468 if (channel == l2cap_hid_interrupt_cid){ 469 hid_host_handle_interrupt_report(packet, size); 470 } else if (channel == l2cap_hid_control_cid){ 471 printf("HID Control: "); 472 printf_hexdump(packet, size); 473 } else { 474 break; 475 } 476 default: 477 break; 478 } 479 } 480 /* LISTING_END */ 481 482 int btstack_main(int argc, const char * argv[]); 483 int btstack_main(int argc, const char * argv[]){ 484 485 (void)argc; 486 (void)argv; 487 488 hid_host_setup(); 489 490 // parse human readable Bluetooth address 491 sscanf_bd_addr(remote_addr_string, remote_addr); 492 493 // Turn on the device 494 hci_power_control(HCI_POWER_ON); 495 return 0; 496 } 497 498 /* EXAMPLE_END */ 499