1 /* 2 * Copyright (C) 2009-2012 by Matthias Ringwald 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 MATTHIAS RINGWALD 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 [email protected] 34 * 35 */ 36 37 /* 38 * hci.c 39 * 40 * Created by Matthias Ringwald on 4/29/09. 41 * 42 */ 43 44 #include "config.h" 45 46 #include "hci.h" 47 #include "gap.h" 48 49 #include <stdarg.h> 50 #include <string.h> 51 #include <stdio.h> 52 53 #ifndef EMBEDDED 54 #include <unistd.h> // gethostbyname 55 #include <btstack/version.h> 56 #endif 57 58 #include "btstack_memory.h" 59 #include "debug.h" 60 #include "hci_dump.h" 61 62 #include <btstack/hci_cmds.h> 63 64 #define HCI_CONNECTION_TIMEOUT_MS 10000 65 66 #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11 67 68 #ifdef USE_BLUETOOL 69 #include "bt_control_iphone.h" 70 #endif 71 72 static void hci_update_scan_enable(void); 73 74 // the STACK is here 75 static hci_stack_t hci_stack; 76 77 /** 78 * get connection for a given handle 79 * 80 * @return connection OR NULL, if not found 81 */ 82 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){ 83 linked_item_t *it; 84 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 85 if ( ((hci_connection_t *) it)->con_handle == con_handle){ 86 return (hci_connection_t *) it; 87 } 88 } 89 return NULL; 90 } 91 92 static void hci_connection_timeout_handler(timer_source_t *timer){ 93 hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item); 94 #ifdef HAVE_TIME 95 struct timeval tv; 96 gettimeofday(&tv, NULL); 97 if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) { 98 // connections might be timed out 99 hci_emit_l2cap_check_timeout(connection); 100 } 101 #endif 102 #ifdef HAVE_TICK 103 if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 104 // connections might be timed out 105 hci_emit_l2cap_check_timeout(connection); 106 } 107 #endif 108 run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS); 109 run_loop_add_timer(timer); 110 } 111 112 static void hci_connection_timestamp(hci_connection_t *connection){ 113 #ifdef HAVE_TIME 114 gettimeofday(&connection->timestamp, NULL); 115 #endif 116 #ifdef HAVE_TICK 117 connection->timestamp = embedded_get_ticks(); 118 #endif 119 } 120 121 /** 122 * create connection for given address 123 * 124 * @return connection OR NULL, if no memory left 125 */ 126 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){ 127 hci_connection_t * conn = (hci_connection_t *) btstack_memory_hci_connection_get(); 128 if (!conn) return NULL; 129 BD_ADDR_COPY(conn->address, addr); 130 conn->con_handle = 0xffff; 131 conn->authentication_flags = AUTH_FLAGS_NONE; 132 conn->bonding_flags = 0; 133 linked_item_set_user(&conn->timeout.item, conn); 134 conn->timeout.process = hci_connection_timeout_handler; 135 hci_connection_timestamp(conn); 136 conn->acl_recombination_length = 0; 137 conn->acl_recombination_pos = 0; 138 conn->num_acl_packets_sent = 0; 139 linked_list_add(&hci_stack.connections, (linked_item_t *) conn); 140 return conn; 141 } 142 143 /** 144 * get connection for given address 145 * 146 * @return connection OR NULL, if not found 147 */ 148 static hci_connection_t * connection_for_address(bd_addr_t address){ 149 linked_item_t *it; 150 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 151 if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){ 152 return (hci_connection_t *) it; 153 } 154 } 155 return NULL; 156 } 157 158 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 159 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags); 160 } 161 162 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 163 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags); 164 } 165 166 167 /** 168 * add authentication flags and reset timer 169 */ 170 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 171 bd_addr_t addr; 172 bt_flip_addr(addr, *(bd_addr_t *) bd_addr); 173 hci_connection_t * conn = connection_for_address(addr); 174 if (conn) { 175 connectionSetAuthenticationFlags(conn, flags); 176 hci_connection_timestamp(conn); 177 } 178 } 179 180 int hci_authentication_active_for_handle(hci_con_handle_t handle){ 181 hci_connection_t * conn = hci_connection_for_handle(handle); 182 if (!conn) return 0; 183 if (!conn->authentication_flags) return 0; 184 if (conn->authentication_flags & SENT_LINK_KEY_REPLY) return 0; 185 if (conn->authentication_flags & RECV_LINK_KEY_NOTIFICATION) return 0; 186 return 1; 187 } 188 189 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){ 190 if (hci_stack.remote_device_db) { 191 hci_stack.remote_device_db->delete_link_key(addr); 192 } 193 } 194 195 196 /** 197 * count connections 198 */ 199 static int nr_hci_connections(void){ 200 int count = 0; 201 linked_item_t *it; 202 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++); 203 return count; 204 } 205 206 /** 207 * Dummy handler called by HCI 208 */ 209 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 210 } 211 212 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){ 213 hci_connection_t * connection = hci_connection_for_handle(handle); 214 if (!connection) { 215 log_error("hci_number_outgoing_packets connectino for handle %u does not exist!\n", handle); 216 return 0; 217 } 218 return connection->num_acl_packets_sent; 219 } 220 221 uint8_t hci_number_free_acl_slots(){ 222 uint8_t free_slots = hci_stack.total_num_acl_packets; 223 linked_item_t *it; 224 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 225 hci_connection_t * connection = (hci_connection_t *) it; 226 if (free_slots < connection->num_acl_packets_sent) { 227 log_error("hci_number_free_acl_slots: sum of outgoing packets > total acl packets!\n"); 228 return 0; 229 } 230 free_slots -= connection->num_acl_packets_sent; 231 } 232 return free_slots; 233 } 234 235 int hci_can_send_packet_now(uint8_t packet_type){ 236 237 // check for async hci transport implementations 238 if (hci_stack.hci_transport->can_send_packet_now){ 239 if (!hci_stack.hci_transport->can_send_packet_now(packet_type)){ 240 return 0; 241 } 242 } 243 244 // check regular Bluetooth flow control 245 switch (packet_type) { 246 case HCI_ACL_DATA_PACKET: 247 return hci_number_free_acl_slots(); 248 case HCI_COMMAND_DATA_PACKET: 249 return hci_stack.num_cmd_packets; 250 default: 251 return 0; 252 } 253 } 254 255 int hci_send_acl_packet(uint8_t *packet, int size){ 256 257 // check for free places on BT module 258 if (!hci_number_free_acl_slots()) return BTSTACK_ACL_BUFFERS_FULL; 259 260 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 261 hci_connection_t *connection = hci_connection_for_handle( con_handle); 262 if (!connection) return 0; 263 hci_connection_timestamp(connection); 264 265 // count packet 266 connection->num_acl_packets_sent++; 267 // log_info("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent); 268 269 // send packet 270 int err = hci_stack.hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 271 272 return err; 273 } 274 275 static void acl_handler(uint8_t *packet, int size){ 276 277 // log_info("acl_handler: size %u", size); 278 279 // get info 280 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 281 hci_connection_t *conn = hci_connection_for_handle(con_handle); 282 uint8_t acl_flags = READ_ACL_FLAGS(packet); 283 uint16_t acl_length = READ_ACL_LENGTH(packet); 284 285 // ignore non-registered handle 286 if (!conn){ 287 log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle); 288 return; 289 } 290 291 // assert packet is complete 292 if (acl_length + 4 != size){ 293 log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4); 294 return; 295 } 296 297 // update idle timestamp 298 hci_connection_timestamp(conn); 299 300 // handle different packet types 301 switch (acl_flags & 0x03) { 302 303 case 0x01: // continuation fragment 304 305 // sanity check 306 if (conn->acl_recombination_pos == 0) { 307 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle); 308 return; 309 } 310 311 // append fragment payload (header already stored) 312 memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length ); 313 conn->acl_recombination_pos += acl_length; 314 315 // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length, 316 // conn->acl_recombination_pos, conn->acl_recombination_length); 317 318 // forward complete L2CAP packet if complete. 319 if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header 320 321 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos); 322 // reset recombination buffer 323 conn->acl_recombination_length = 0; 324 conn->acl_recombination_pos = 0; 325 } 326 break; 327 328 case 0x02: { // first fragment 329 330 // sanity check 331 if (conn->acl_recombination_pos) { 332 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle); 333 return; 334 } 335 336 // peek into L2CAP packet! 337 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 338 339 // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length); 340 341 // compare fragment size to L2CAP packet size 342 if (acl_length >= l2cap_length + 4){ 343 344 // forward fragment as L2CAP packet 345 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4); 346 347 } else { 348 // store first fragment and tweak acl length for complete package 349 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4); 350 conn->acl_recombination_pos = acl_length + 4; 351 conn->acl_recombination_length = l2cap_length; 352 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4); 353 } 354 break; 355 356 } 357 default: 358 log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03); 359 return; 360 } 361 362 // execute main loop 363 hci_run(); 364 } 365 366 static void hci_shutdown_connection(hci_connection_t *conn){ 367 log_info("Connection closed: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 368 369 // cancel all l2cap connections 370 hci_emit_disconnection_complete(conn->con_handle, 0x16); // terminated by local host 371 372 run_loop_remove_timer(&conn->timeout); 373 374 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); 375 btstack_memory_hci_connection_free( conn ); 376 377 // now it's gone 378 hci_emit_nr_connections_changed(); 379 } 380 381 static const uint16_t packet_type_sizes[] = { 382 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 383 HCI_ACL_DH1_SIZE, 0, 0, 0, 384 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 385 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 386 }; 387 static const uint8_t packet_type_feature_requirement_bit[] = { 388 0, // 3 slot packets 389 1, // 5 slot packets 390 25, // EDR 2 mpbs 391 26, // EDR 3 mbps 392 39, // 3 slot EDR packts 393 40, // 5 slot EDR packet 394 }; 395 static const uint16_t packet_type_feature_packet_mask[] = { 396 0x0f00, // 3 slot packets 397 0xf000, // 5 slot packets 398 0x1102, // EDR 2 mpbs 399 0x2204, // EDR 3 mbps 400 0x0300, // 3 slot EDR packts 401 0x3000, // 5 slot EDR packet 402 }; 403 404 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){ 405 // enable packet types based on size 406 uint16_t packet_types = 0; 407 int i; 408 for (i=0;i<16;i++){ 409 if (packet_type_sizes[i] == 0) continue; 410 if (packet_type_sizes[i] <= buffer_size){ 411 packet_types |= 1 << i; 412 } 413 } 414 // disable packet types due to missing local supported features 415 for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){ 416 int bit_idx = packet_type_feature_requirement_bit[i]; 417 int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0; 418 if (feature_set) continue; 419 log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]); 420 packet_types &= ~packet_type_feature_packet_mask[i]; 421 } 422 // flip bits for "may not be used" 423 packet_types ^= 0x3306; 424 return packet_types; 425 } 426 427 uint16_t hci_usable_acl_packet_types(void){ 428 return hci_stack.packet_types; 429 } 430 431 uint8_t* hci_get_outgoing_acl_packet_buffer(void){ 432 // hci packet buffer is >= acl data packet length 433 return hci_stack.hci_packet_buffer; 434 } 435 436 uint16_t hci_max_acl_data_packet_length(void){ 437 return hci_stack.acl_data_packet_length; 438 } 439 440 int hci_ssp_supported(void){ 441 // No 51, byte 6, bit 3 442 return (hci_stack.local_supported_features[6] & (1 << 3)) != 0; 443 } 444 445 int hci_classic_supported(void){ 446 // No 37, byte 4, bit 5, = No BR/EDR Support 447 return (hci_stack.local_supported_features[4] & (1 << 5)) == 0; 448 } 449 450 int hci_le_supported(void){ 451 // No 37, byte 4, bit 6 = LE Supported (Controller) 452 #ifdef HAVE_BLE 453 return (hci_stack.local_supported_features[4] & (1 << 6)) != 0; 454 #else 455 return 0; 456 #endif 457 } 458 459 // get addr type and address used in advertisement packets 460 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){ 461 *addr_type = hci_stack.adv_addr_type; 462 if (hci_stack.adv_addr_type){ 463 memcpy(addr, hci_stack.adv_address, 6); 464 } else { 465 memcpy(addr, hci_stack.local_bd_addr, 6); 466 } 467 } 468 469 // avoid huge local variables 470 #ifndef EMBEDDED 471 static device_name_t device_name; 472 #endif 473 static void event_handler(uint8_t *packet, int size){ 474 475 uint16_t event_length = packet[1]; 476 477 // assert packet is complete 478 if (size != event_length + 2){ 479 log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2); 480 return; 481 } 482 483 bd_addr_t addr; 484 uint8_t link_type; 485 hci_con_handle_t handle; 486 hci_connection_t * conn; 487 int i; 488 489 // printf("HCI:EVENT:%02x\n", packet[0]); 490 491 switch (packet[0]) { 492 493 case HCI_EVENT_COMMAND_COMPLETE: 494 // get num cmd packets 495 // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack.num_cmd_packets, packet[2]); 496 hci_stack.num_cmd_packets = packet[2]; 497 498 if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){ 499 // from offset 5 500 // status 501 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 502 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6); 503 // ignore: SCO data packet len (8) 504 hci_stack.total_num_acl_packets = packet[9]; 505 // ignore: total num SCO packets 506 if (hci_stack.state == HCI_STATE_INITIALIZING){ 507 // determine usable ACL payload size 508 if (HCI_ACL_PAYLOAD_SIZE < hci_stack.acl_data_packet_length){ 509 hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 510 } 511 log_info("hci_read_buffer_size: used size %u, count %u\n", 512 hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets); 513 } 514 } 515 #ifdef HAVE_BLE 516 if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){ 517 hci_stack.le_data_packet_length = READ_BT_16(packet, 6); 518 hci_stack.total_num_le_packets = packet[8]; 519 log_info("hci_le_read_buffer_size: size %u, count %u\n", hci_stack.le_data_packet_length, hci_stack.total_num_le_packets); 520 } 521 #endif 522 // Dump local address 523 if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) { 524 bt_flip_addr(hci_stack.local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]); 525 log_info("Local Address, Status: 0x%02x: Addr: %s\n", 526 packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack.local_bd_addr)); 527 } 528 if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 529 hci_emit_discoverable_enabled(hci_stack.discoverable); 530 } 531 // Note: HCI init checks 532 if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){ 533 memcpy(hci_stack.local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8); 534 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x", 535 hci_stack.local_supported_features[0], hci_stack.local_supported_features[1], 536 hci_stack.local_supported_features[2], hci_stack.local_supported_features[3], 537 hci_stack.local_supported_features[4], hci_stack.local_supported_features[5], 538 hci_stack.local_supported_features[6], hci_stack.local_supported_features[7]); 539 540 // determine usable ACL packet types based buffer size and supported features 541 hci_stack.packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(hci_stack.acl_data_packet_length, &hci_stack.local_supported_features[0]); 542 log_info("packet types %04x", hci_stack.packet_types); 543 544 // Classic/LE 545 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported()); 546 } 547 break; 548 549 case HCI_EVENT_COMMAND_STATUS: 550 // get num cmd packets 551 // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack.num_cmd_packets, packet[3]); 552 hci_stack.num_cmd_packets = packet[3]; 553 break; 554 555 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 556 for (i=0; i<packet[2];i++){ 557 handle = READ_BT_16(packet, 3 + 2*i); 558 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i); 559 conn = hci_connection_for_handle(handle); 560 if (!conn){ 561 log_error("hci_number_completed_packet lists unused con handle %u\n", handle); 562 continue; 563 } 564 conn->num_acl_packets_sent -= num_packets; 565 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent); 566 } 567 break; 568 569 case HCI_EVENT_CONNECTION_REQUEST: 570 bt_flip_addr(addr, &packet[2]); 571 // TODO: eval COD 8-10 572 link_type = packet[11]; 573 log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type); 574 if (link_type == 1) { // ACL 575 conn = connection_for_address(addr); 576 if (!conn) { 577 conn = create_connection_for_addr(addr); 578 } 579 if (!conn) { 580 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 581 hci_stack.decline_reason = 0x0d; 582 BD_ADDR_COPY(hci_stack.decline_addr, addr); 583 break; 584 } 585 conn->state = RECEIVED_CONNECTION_REQUEST; 586 hci_run(); 587 } else { 588 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A) 589 hci_stack.decline_reason = 0x0a; 590 BD_ADDR_COPY(hci_stack.decline_addr, addr); 591 } 592 break; 593 594 case HCI_EVENT_CONNECTION_COMPLETE: 595 // Connection management 596 bt_flip_addr(addr, &packet[5]); 597 log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr)); 598 conn = connection_for_address(addr); 599 if (conn) { 600 if (!packet[2]){ 601 conn->state = OPEN; 602 conn->con_handle = READ_BT_16(packet, 3); 603 conn->bonding_flags = BONDING_REQUEST_REMOTE_FEATURES; 604 605 // restart timer 606 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 607 run_loop_add_timer(&conn->timeout); 608 609 log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 610 611 hci_emit_nr_connections_changed(); 612 } else { 613 // connection failed, remove entry 614 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); 615 btstack_memory_hci_connection_free( conn ); 616 617 // if authentication error, also delete link key 618 if (packet[2] == 0x05) { 619 hci_drop_link_key_for_bd_addr(&addr); 620 } 621 } 622 } 623 break; 624 625 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 626 handle = READ_BT_16(packet, 3); 627 conn = hci_connection_for_handle(handle); 628 if (!conn) break; 629 if (!packet[2]){ 630 uint8_t * features = &packet[5]; 631 if (features[6] & (1 << 3)){ 632 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP; 633 } 634 } 635 conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES; 636 break; 637 638 case HCI_EVENT_LINK_KEY_REQUEST: 639 log_info("HCI_EVENT_LINK_KEY_REQUEST\n"); 640 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST); 641 // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST 642 if (hci_stack.bondable && !hci_stack.remote_device_db) break; 643 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST); 644 hci_run(); 645 // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set 646 return; 647 648 case HCI_EVENT_LINK_KEY_NOTIFICATION: 649 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION); 650 if (!hci_stack.remote_device_db) break; 651 bt_flip_addr(addr, &packet[2]); 652 hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]); 653 // still forward event to allow dismiss of pairing dialog 654 break; 655 656 case HCI_EVENT_PIN_CODE_REQUEST: 657 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST); 658 // non-bondable mode: pin code negative reply will be sent 659 if (!hci_stack.bondable){ 660 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_PIN_CODE_REQUEST); 661 hci_run(); 662 return; 663 } 664 // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key 665 if (!hci_stack.remote_device_db) break; 666 bt_flip_addr(addr, &packet[2]); 667 hci_stack.remote_device_db->delete_link_key(&addr); 668 break; 669 670 case HCI_EVENT_IO_CAPABILITY_REQUEST: 671 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST); 672 if (!hci_stack.bondable || hci_stack.ssp_io_capability == SSP_IO_CAPABILITY_UNKNOWN) break; 673 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY); 674 break; 675 676 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 677 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_CONFIRM_REQUEST); 678 if (!hci_stack.ssp_auto_accept) break; 679 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY); 680 break; 681 682 case HCI_EVENT_USER_PASSKEY_REQUEST: 683 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_PASSKEY_REQUEST); 684 if (!hci_stack.ssp_auto_accept) break; 685 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY); 686 break; 687 688 case HCI_EVENT_ENCRYPTION_CHANGE: 689 if (packet[2]) break; // error status 690 handle = READ_BT_16(packet, 3); 691 conn = hci_connection_for_handle(handle); 692 if (!conn) break; 693 if (packet[5]){ 694 conn->authentication_flags |= CONNECTION_ENCRYPTED; 695 // @TODO set authentication depending on pairing process 696 } else { 697 conn->authentication_flags &= ~(CONNECTION_ENCRYPTED | CONNECTION_AUTHENTICATED); 698 } 699 break; 700 701 #ifndef EMBEDDED 702 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 703 if (!hci_stack.remote_device_db) break; 704 if (packet[2]) break; // status not ok 705 bt_flip_addr(addr, &packet[3]); 706 // fix for invalid remote names - terminate on 0xff 707 for (i=0; i<248;i++){ 708 if (packet[9+i] == 0xff){ 709 packet[9+i] = 0; 710 break; 711 } 712 } 713 memset(&device_name, 0, sizeof(device_name_t)); 714 strncpy((char*) device_name, (char*) &packet[9], 248); 715 hci_stack.remote_device_db->put_name(&addr, &device_name); 716 break; 717 718 case HCI_EVENT_INQUIRY_RESULT: 719 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 720 if (!hci_stack.remote_device_db) break; 721 // first send inq result packet 722 hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size); 723 // then send cached remote names 724 for (i=0; i<packet[2];i++){ 725 bt_flip_addr(addr, &packet[3+i*6]); 726 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){ 727 hci_emit_remote_name_cached(&addr, &device_name); 728 } 729 } 730 return; 731 #endif 732 733 case HCI_EVENT_DISCONNECTION_COMPLETE: 734 if (!packet[2]){ 735 handle = READ_BT_16(packet, 3); 736 hci_connection_t * conn = hci_connection_for_handle(handle); 737 if (conn) { 738 hci_shutdown_connection(conn); 739 } 740 } 741 break; 742 743 case HCI_EVENT_HARDWARE_ERROR: 744 if(hci_stack.control && hci_stack.control->hw_error){ 745 (*hci_stack.control->hw_error)(); 746 } 747 break; 748 749 #ifdef HAVE_BLE 750 case HCI_EVENT_LE_META: 751 switch (packet[2]) { 752 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 753 // Connection management 754 bt_flip_addr(addr, &packet[8]); 755 log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr)); 756 // LE connections are auto-accepted, so just create a connection if there isn't one already 757 conn = connection_for_address(addr); 758 if (packet[3]){ 759 if (conn){ 760 // outgoing connection failed, remove entry 761 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); 762 btstack_memory_hci_connection_free( conn ); 763 764 } 765 // if authentication error, also delete link key 766 if (packet[3] == 0x05) { 767 hci_drop_link_key_for_bd_addr(&addr); 768 } 769 break; 770 } 771 if (!conn){ 772 conn = create_connection_for_addr(addr); 773 } 774 if (!conn){ 775 // no memory 776 break; 777 } 778 779 conn->state = OPEN; 780 conn->con_handle = READ_BT_16(packet, 4); 781 782 // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock 783 784 // restart timer 785 // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 786 // run_loop_add_timer(&conn->timeout); 787 788 log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 789 790 hci_emit_nr_connections_changed(); 791 break; 792 793 // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]); 794 795 default: 796 break; 797 } 798 break; 799 #endif 800 801 default: 802 break; 803 } 804 805 // handle BT initialization 806 if (hci_stack.state == HCI_STATE_INITIALIZING){ 807 if (hci_stack.substate % 2){ 808 // odd: waiting for event 809 if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){ 810 // wait for explicit COMMAND COMPLETE on RESET 811 if (hci_stack.substate > 1 || COMMAND_COMPLETE_EVENT(packet, hci_reset)) { 812 hci_stack.substate++; 813 } 814 } 815 } 816 } 817 818 // help with BT sleep 819 if (hci_stack.state == HCI_STATE_FALLING_ASLEEP 820 && hci_stack.substate == 1 821 && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 822 hci_stack.substate++; 823 } 824 825 hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size); 826 827 // execute main loop 828 hci_run(); 829 } 830 831 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 832 switch (packet_type) { 833 case HCI_EVENT_PACKET: 834 event_handler(packet, size); 835 break; 836 case HCI_ACL_DATA_PACKET: 837 acl_handler(packet, size); 838 break; 839 default: 840 break; 841 } 842 } 843 844 /** Register HCI packet handlers */ 845 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 846 hci_stack.packet_handler = handler; 847 } 848 849 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){ 850 851 // reference to use transport layer implementation 852 hci_stack.hci_transport = transport; 853 854 // references to used control implementation 855 hci_stack.control = control; 856 857 // reference to used config 858 hci_stack.config = config; 859 860 // no connections yet 861 hci_stack.connections = NULL; 862 hci_stack.discoverable = 0; 863 hci_stack.connectable = 0; 864 hci_stack.bondable = 1; 865 866 // no pending cmds 867 hci_stack.decline_reason = 0; 868 hci_stack.new_scan_enable_value = 0xff; 869 870 // higher level handler 871 hci_stack.packet_handler = dummy_handler; 872 873 // store and open remote device db 874 hci_stack.remote_device_db = remote_device_db; 875 if (hci_stack.remote_device_db) { 876 hci_stack.remote_device_db->open(); 877 } 878 879 // max acl payload size defined in config.h 880 hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 881 882 // register packet handlers with transport 883 transport->register_packet_handler(&packet_handler); 884 885 hci_stack.state = HCI_STATE_OFF; 886 887 // class of device 888 hci_stack.class_of_device = 0x007a020c; // Smartphone 889 890 // Secure Simple Pairing default: enable, no I/O capabilities, auto accept 891 hci_stack.ssp_enable = 1; 892 hci_stack.ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 893 hci_stack.ssp_authentication_requirement = 0; 894 hci_stack.ssp_auto_accept = 1; 895 896 // LE 897 hci_stack.adv_addr_type = 0; 898 memset(hci_stack.adv_address, 0, 6); 899 } 900 901 void hci_close(){ 902 // close remote device db 903 if (hci_stack.remote_device_db) { 904 hci_stack.remote_device_db->close(); 905 } 906 while (hci_stack.connections) { 907 hci_shutdown_connection((hci_connection_t *) hci_stack.connections); 908 } 909 hci_power_control(HCI_POWER_OFF); 910 } 911 912 // State-Module-Driver overview 913 // state module low-level 914 // HCI_STATE_OFF off close 915 // HCI_STATE_INITIALIZING, on open 916 // HCI_STATE_WORKING, on open 917 // HCI_STATE_HALTING, on open 918 // HCI_STATE_SLEEPING, off/sleep close 919 // HCI_STATE_FALLING_ASLEEP on open 920 921 static int hci_power_control_on(void){ 922 923 // power on 924 int err = 0; 925 if (hci_stack.control && hci_stack.control->on){ 926 err = (*hci_stack.control->on)(hci_stack.config); 927 } 928 if (err){ 929 log_error( "POWER_ON failed\n"); 930 hci_emit_hci_open_failed(); 931 return err; 932 } 933 934 // open low-level device 935 err = hci_stack.hci_transport->open(hci_stack.config); 936 if (err){ 937 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 938 if (hci_stack.control && hci_stack.control->off){ 939 (*hci_stack.control->off)(hci_stack.config); 940 } 941 hci_emit_hci_open_failed(); 942 return err; 943 } 944 return 0; 945 } 946 947 static void hci_power_control_off(void){ 948 949 log_info("hci_power_control_off\n"); 950 951 // close low-level device 952 hci_stack.hci_transport->close(hci_stack.config); 953 954 log_info("hci_power_control_off - hci_transport closed\n"); 955 956 // power off 957 if (hci_stack.control && hci_stack.control->off){ 958 (*hci_stack.control->off)(hci_stack.config); 959 } 960 961 log_info("hci_power_control_off - control closed\n"); 962 963 hci_stack.state = HCI_STATE_OFF; 964 } 965 966 static void hci_power_control_sleep(void){ 967 968 log_info("hci_power_control_sleep\n"); 969 970 #if 0 971 // don't close serial port during sleep 972 973 // close low-level device 974 hci_stack.hci_transport->close(hci_stack.config); 975 #endif 976 977 // sleep mode 978 if (hci_stack.control && hci_stack.control->sleep){ 979 (*hci_stack.control->sleep)(hci_stack.config); 980 } 981 982 hci_stack.state = HCI_STATE_SLEEPING; 983 } 984 985 static int hci_power_control_wake(void){ 986 987 log_info("hci_power_control_wake\n"); 988 989 // wake on 990 if (hci_stack.control && hci_stack.control->wake){ 991 (*hci_stack.control->wake)(hci_stack.config); 992 } 993 994 #if 0 995 // open low-level device 996 int err = hci_stack.hci_transport->open(hci_stack.config); 997 if (err){ 998 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 999 if (hci_stack.control && hci_stack.control->off){ 1000 (*hci_stack.control->off)(hci_stack.config); 1001 } 1002 hci_emit_hci_open_failed(); 1003 return err; 1004 } 1005 #endif 1006 1007 return 0; 1008 } 1009 1010 1011 int hci_power_control(HCI_POWER_MODE power_mode){ 1012 1013 log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state); 1014 1015 int err = 0; 1016 switch (hci_stack.state){ 1017 1018 case HCI_STATE_OFF: 1019 switch (power_mode){ 1020 case HCI_POWER_ON: 1021 err = hci_power_control_on(); 1022 if (err) return err; 1023 // set up state machine 1024 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 1025 hci_stack.state = HCI_STATE_INITIALIZING; 1026 hci_stack.substate = 0; 1027 break; 1028 case HCI_POWER_OFF: 1029 // do nothing 1030 break; 1031 case HCI_POWER_SLEEP: 1032 // do nothing (with SLEEP == OFF) 1033 break; 1034 } 1035 break; 1036 1037 case HCI_STATE_INITIALIZING: 1038 switch (power_mode){ 1039 case HCI_POWER_ON: 1040 // do nothing 1041 break; 1042 case HCI_POWER_OFF: 1043 // no connections yet, just turn it off 1044 hci_power_control_off(); 1045 break; 1046 case HCI_POWER_SLEEP: 1047 // no connections yet, just turn it off 1048 hci_power_control_sleep(); 1049 break; 1050 } 1051 break; 1052 1053 case HCI_STATE_WORKING: 1054 switch (power_mode){ 1055 case HCI_POWER_ON: 1056 // do nothing 1057 break; 1058 case HCI_POWER_OFF: 1059 // see hci_run 1060 hci_stack.state = HCI_STATE_HALTING; 1061 break; 1062 case HCI_POWER_SLEEP: 1063 // see hci_run 1064 hci_stack.state = HCI_STATE_FALLING_ASLEEP; 1065 hci_stack.substate = 0; 1066 break; 1067 } 1068 break; 1069 1070 case HCI_STATE_HALTING: 1071 switch (power_mode){ 1072 case HCI_POWER_ON: 1073 // set up state machine 1074 hci_stack.state = HCI_STATE_INITIALIZING; 1075 hci_stack.substate = 0; 1076 break; 1077 case HCI_POWER_OFF: 1078 // do nothing 1079 break; 1080 case HCI_POWER_SLEEP: 1081 // see hci_run 1082 hci_stack.state = HCI_STATE_FALLING_ASLEEP; 1083 hci_stack.substate = 0; 1084 break; 1085 } 1086 break; 1087 1088 case HCI_STATE_FALLING_ASLEEP: 1089 switch (power_mode){ 1090 case HCI_POWER_ON: 1091 1092 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1093 // nothing to do, if H4 supports power management 1094 if (bt_control_iphone_power_management_enabled()){ 1095 hci_stack.state = HCI_STATE_INITIALIZING; 1096 hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP; 1097 break; 1098 } 1099 #endif 1100 // set up state machine 1101 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 1102 hci_stack.state = HCI_STATE_INITIALIZING; 1103 hci_stack.substate = 0; 1104 break; 1105 case HCI_POWER_OFF: 1106 // see hci_run 1107 hci_stack.state = HCI_STATE_HALTING; 1108 break; 1109 case HCI_POWER_SLEEP: 1110 // do nothing 1111 break; 1112 } 1113 break; 1114 1115 case HCI_STATE_SLEEPING: 1116 switch (power_mode){ 1117 case HCI_POWER_ON: 1118 1119 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1120 // nothing to do, if H4 supports power management 1121 if (bt_control_iphone_power_management_enabled()){ 1122 hci_stack.state = HCI_STATE_INITIALIZING; 1123 hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP; 1124 hci_update_scan_enable(); 1125 break; 1126 } 1127 #endif 1128 err = hci_power_control_wake(); 1129 if (err) return err; 1130 // set up state machine 1131 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 1132 hci_stack.state = HCI_STATE_INITIALIZING; 1133 hci_stack.substate = 0; 1134 break; 1135 case HCI_POWER_OFF: 1136 hci_stack.state = HCI_STATE_HALTING; 1137 break; 1138 case HCI_POWER_SLEEP: 1139 // do nothing 1140 break; 1141 } 1142 break; 1143 } 1144 1145 // create internal event 1146 hci_emit_state(); 1147 1148 // trigger next/first action 1149 hci_run(); 1150 1151 return 0; 1152 } 1153 1154 static void hci_update_scan_enable(void){ 1155 // 2 = page scan, 1 = inq scan 1156 hci_stack.new_scan_enable_value = hci_stack.connectable << 1 | hci_stack.discoverable; 1157 hci_run(); 1158 } 1159 1160 void hci_discoverable_control(uint8_t enable){ 1161 if (enable) enable = 1; // normalize argument 1162 1163 if (hci_stack.discoverable == enable){ 1164 hci_emit_discoverable_enabled(hci_stack.discoverable); 1165 return; 1166 } 1167 1168 hci_stack.discoverable = enable; 1169 hci_update_scan_enable(); 1170 } 1171 1172 void hci_connectable_control(uint8_t enable){ 1173 if (enable) enable = 1; // normalize argument 1174 1175 // don't emit event 1176 if (hci_stack.connectable == enable) return; 1177 1178 hci_stack.connectable = enable; 1179 hci_update_scan_enable(); 1180 } 1181 1182 bd_addr_t * hci_local_bd_addr(void){ 1183 return &hci_stack.local_bd_addr; 1184 } 1185 1186 void hci_run(){ 1187 1188 hci_connection_t * connection; 1189 linked_item_t * it; 1190 1191 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1192 1193 // global/non-connection oriented commands 1194 1195 // decline incoming connections 1196 if (hci_stack.decline_reason){ 1197 uint8_t reason = hci_stack.decline_reason; 1198 hci_stack.decline_reason = 0; 1199 hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason); 1200 return; 1201 } 1202 1203 // send scan enable 1204 if (hci_stack.state == HCI_STATE_WORKING && hci_stack.new_scan_enable_value != 0xff && hci_classic_supported()){ 1205 hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value); 1206 hci_stack.new_scan_enable_value = 0xff; 1207 return; 1208 } 1209 1210 // send pending HCI commands 1211 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 1212 1213 connection = (hci_connection_t *) it; 1214 1215 if (connection->state == RECEIVED_CONNECTION_REQUEST){ 1216 log_info("sending hci_accept_connection_request\n"); 1217 hci_send_cmd(&hci_accept_connection_request, connection->address, 1); 1218 connection->state = ACCEPTED_CONNECTION_REQUEST; 1219 return; 1220 } 1221 1222 if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){ 1223 link_key_t link_key; 1224 log_info("responding to link key request\n"); 1225 if ( hci_stack.bondable && hci_stack.remote_device_db && hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){ 1226 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key); 1227 } else { 1228 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 1229 } 1230 connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST); 1231 return; 1232 } 1233 1234 if (connection->authentication_flags & HANDLE_PIN_CODE_REQUEST){ 1235 log_info("denying to pin request\n"); 1236 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 1237 connectionClearAuthenticationFlags(connection, HANDLE_PIN_CODE_REQUEST); 1238 return; 1239 } 1240 1241 if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){ 1242 if (hci_stack.bondable){ 1243 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack.ssp_io_capability, NULL, hci_stack.ssp_authentication_requirement); 1244 } else { 1245 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 1246 } 1247 connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY); 1248 return; 1249 } 1250 1251 if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){ 1252 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 1253 connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY); 1254 return; 1255 } 1256 1257 if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){ 1258 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 1259 connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY); 1260 return; 1261 } 1262 1263 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){ 1264 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 1265 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES; 1266 } 1267 } 1268 1269 switch (hci_stack.state){ 1270 case HCI_STATE_INITIALIZING: 1271 // log_info("hci_init: substate %u\n", hci_stack.substate); 1272 if (hci_stack.substate % 2) { 1273 // odd: waiting for command completion 1274 return; 1275 } 1276 switch (hci_stack.substate >> 1){ 1277 case 0: // RESET 1278 hci_send_cmd(&hci_reset); 1279 1280 if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){ 1281 // skip baud change 1282 hci_stack.substate = 4; // >> 1 = 2 1283 } 1284 break; 1285 case 1: // SEND BAUD CHANGE 1286 hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer); 1287 hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]); 1288 break; 1289 case 2: // LOCAL BAUD CHANGE 1290 hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main); 1291 hci_stack.substate += 2; 1292 // break missing here for fall through 1293 1294 case 3: 1295 // Custom initialization 1296 if (hci_stack.control && hci_stack.control->next_cmd){ 1297 int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer); 1298 if (valid_cmd){ 1299 int size = 3 + hci_stack.hci_packet_buffer[2]; 1300 hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size); 1301 hci_stack.substate = 4; // more init commands 1302 break; 1303 } 1304 log_info("hci_run: init script done\n\r"); 1305 } 1306 // otherwise continue 1307 hci_send_cmd(&hci_read_bd_addr); 1308 break; 1309 case 4: 1310 hci_send_cmd(&hci_read_buffer_size); 1311 break; 1312 case 5: 1313 hci_send_cmd(&hci_read_local_supported_features); 1314 break; 1315 case 6: 1316 if (hci_le_supported()){ 1317 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF); 1318 } else { 1319 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 1320 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF); 1321 } 1322 1323 // skip Classic init commands for LE only chipsets 1324 if (!hci_classic_supported()){ 1325 if (hci_le_supported()){ 1326 hci_stack.substate = 11 << 1; // skip all classic command 1327 } else { 1328 log_error("Neither BR/EDR nor LE supported"); 1329 hci_stack.substate = 13 << 1; // skip all 1330 } 1331 } 1332 break; 1333 case 7: 1334 if (hci_ssp_supported()){ 1335 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack.ssp_enable); 1336 break; 1337 } 1338 hci_stack.substate += 2; 1339 // break missing here for fall through 1340 1341 case 8: 1342 // ca. 15 sec 1343 hci_send_cmd(&hci_write_page_timeout, 0x6000); 1344 break; 1345 case 9: 1346 hci_send_cmd(&hci_write_class_of_device, hci_stack.class_of_device); 1347 break; 1348 case 10: 1349 if (hci_stack.local_name){ 1350 hci_send_cmd(&hci_write_local_name, hci_stack.local_name); 1351 } else { 1352 char hostname[30]; 1353 #ifdef EMBEDDED 1354 // BTstack-11:22:33:44:55:66 1355 strcpy(hostname, "BTstack "); 1356 strcat(hostname, bd_addr_to_str(hci_stack.local_bd_addr)); 1357 printf("---> Name %s\n", hostname); 1358 #else 1359 // hostname for POSIX systems 1360 gethostname(hostname, 30); 1361 hostname[29] = '\0'; 1362 #endif 1363 hci_send_cmd(&hci_write_local_name, hostname); 1364 } 1365 break; 1366 case 11: 1367 hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan 1368 if (!hci_le_supported()){ 1369 // SKIP LE init for Classic only configuration 1370 hci_stack.substate = 13 << 1; 1371 } 1372 break; 1373 1374 #ifdef HAVE_BLE 1375 // LE INIT 1376 case 12: 1377 hci_send_cmd(&hci_le_read_buffer_size); 1378 break; 1379 case 13: 1380 // LE Supported Host = 1, Simultaneous Host = 0 1381 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 1382 break; 1383 #endif 1384 1385 // DONE 1386 case 14: 1387 // done. 1388 hci_stack.state = HCI_STATE_WORKING; 1389 hci_emit_state(); 1390 break; 1391 default: 1392 break; 1393 } 1394 hci_stack.substate++; 1395 break; 1396 1397 case HCI_STATE_HALTING: 1398 1399 log_info("HCI_STATE_HALTING\n"); 1400 // close all open connections 1401 connection = (hci_connection_t *) hci_stack.connections; 1402 if (connection){ 1403 1404 // send disconnect 1405 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1406 1407 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle); 1408 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1409 1410 // send disconnected event right away - causes higher layer connections to get closed, too. 1411 hci_shutdown_connection(connection); 1412 return; 1413 } 1414 log_info("HCI_STATE_HALTING, calling off\n"); 1415 1416 // switch mode 1417 hci_power_control_off(); 1418 1419 log_info("HCI_STATE_HALTING, emitting state\n"); 1420 hci_emit_state(); 1421 log_info("HCI_STATE_HALTING, done\n"); 1422 break; 1423 1424 case HCI_STATE_FALLING_ASLEEP: 1425 switch(hci_stack.substate) { 1426 case 0: 1427 log_info("HCI_STATE_FALLING_ASLEEP\n"); 1428 // close all open connections 1429 connection = (hci_connection_t *) hci_stack.connections; 1430 1431 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1432 // don't close connections, if H4 supports power management 1433 if (bt_control_iphone_power_management_enabled()){ 1434 connection = NULL; 1435 } 1436 #endif 1437 if (connection){ 1438 1439 // send disconnect 1440 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1441 1442 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle); 1443 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1444 1445 // send disconnected event right away - causes higher layer connections to get closed, too. 1446 hci_shutdown_connection(connection); 1447 return; 1448 } 1449 1450 if (hci_classic_supported()){ 1451 // disable page and inquiry scan 1452 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1453 1454 log_info("HCI_STATE_HALTING, disabling inq scans\n"); 1455 hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan 1456 1457 // continue in next sub state 1458 hci_stack.substate++; 1459 break; 1460 } 1461 // fall through for ble-only chips 1462 1463 case 2: 1464 log_info("HCI_STATE_HALTING, calling sleep\n"); 1465 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1466 // don't actually go to sleep, if H4 supports power management 1467 if (bt_control_iphone_power_management_enabled()){ 1468 // SLEEP MODE reached 1469 hci_stack.state = HCI_STATE_SLEEPING; 1470 hci_emit_state(); 1471 break; 1472 } 1473 #endif 1474 // switch mode 1475 hci_power_control_sleep(); // changes hci_stack.state to SLEEP 1476 hci_emit_state(); 1477 break; 1478 1479 default: 1480 break; 1481 } 1482 break; 1483 1484 default: 1485 break; 1486 } 1487 } 1488 1489 int hci_send_cmd_packet(uint8_t *packet, int size){ 1490 bd_addr_t addr; 1491 hci_connection_t * conn; 1492 // house-keeping 1493 1494 // create_connection? 1495 if (IS_COMMAND(packet, hci_create_connection)){ 1496 bt_flip_addr(addr, &packet[3]); 1497 log_info("Create_connection to %s\n", bd_addr_to_str(addr)); 1498 conn = connection_for_address(addr); 1499 if (conn) { 1500 // if connection exists 1501 if (conn->state == OPEN) { 1502 // and OPEN, emit connection complete command 1503 hci_emit_connection_complete(conn, 0); 1504 } 1505 // otherwise, just ignore as it is already in the open process 1506 return 0; // don't sent packet to controller 1507 1508 } 1509 // create connection struct and register, state = SENT_CREATE_CONNECTION 1510 conn = create_connection_for_addr(addr); 1511 if (!conn){ 1512 // notify client that alloc failed 1513 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 1514 return 0; // don't sent packet to controller 1515 } 1516 conn->state = SENT_CREATE_CONNECTION; 1517 } 1518 1519 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 1520 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 1521 } 1522 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 1523 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 1524 } 1525 // if (IS_COMMAND(packet, hci_pin_code_request_reply)){ 1526 // hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY); 1527 // } 1528 // if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){ 1529 // hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY); 1530 // } 1531 1532 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 1533 if (hci_stack.remote_device_db){ 1534 bt_flip_addr(addr, &packet[3]); 1535 hci_stack.remote_device_db->delete_link_key(&addr); 1536 } 1537 } 1538 1539 #ifdef HAVE_BLE 1540 if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){ 1541 hci_stack.adv_addr_type = packet[8]; 1542 } 1543 if (IS_COMMAND(packet, hci_le_set_random_address)){ 1544 bt_flip_addr(hci_stack.adv_address, &packet[3]); 1545 } 1546 #endif 1547 1548 1549 hci_stack.num_cmd_packets--; 1550 return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 1551 } 1552 1553 // Configure Secure Simple Pairing 1554 1555 // enable will enable SSP during init 1556 void hci_ssp_set_enable(int enable){ 1557 hci_stack.ssp_enable = enable; 1558 } 1559 1560 // if set, BTstack will respond to io capability request using authentication requirement 1561 void hci_ssp_set_io_capability(int io_capability){ 1562 hci_stack.ssp_io_capability = io_capability; 1563 } 1564 void hci_ssp_set_authentication_requirement(int authentication_requirement){ 1565 hci_stack.ssp_authentication_requirement = authentication_requirement; 1566 } 1567 1568 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 1569 void hci_ssp_set_auto_accept(int auto_accept){ 1570 hci_stack.ssp_auto_accept = auto_accept; 1571 } 1572 1573 /** 1574 * pre: numcmds >= 0 - it's allowed to send a command to the controller 1575 */ 1576 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 1577 va_list argptr; 1578 va_start(argptr, cmd); 1579 uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr); 1580 va_end(argptr); 1581 return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size); 1582 } 1583 1584 // Create various non-HCI events. 1585 // TODO: generalize, use table similar to hci_create_command 1586 1587 void hci_emit_state(){ 1588 log_info("BTSTACK_EVENT_STATE %u", hci_stack.state); 1589 uint8_t event[3]; 1590 event[0] = BTSTACK_EVENT_STATE; 1591 event[1] = sizeof(event) - 2; 1592 event[2] = hci_stack.state; 1593 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1594 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1595 } 1596 1597 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){ 1598 uint8_t event[13]; 1599 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 1600 event[1] = sizeof(event) - 2; 1601 event[2] = status; 1602 bt_store_16(event, 3, conn->con_handle); 1603 bt_flip_addr(&event[5], conn->address); 1604 event[11] = 1; // ACL connection 1605 event[12] = 0; // encryption disabled 1606 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1607 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1608 } 1609 1610 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 1611 uint8_t event[6]; 1612 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 1613 event[1] = sizeof(event) - 2; 1614 event[2] = 0; // status = OK 1615 bt_store_16(event, 3, handle); 1616 event[5] = reason; 1617 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1618 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1619 } 1620 1621 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 1622 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 1623 uint8_t event[4]; 1624 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 1625 event[1] = sizeof(event) - 2; 1626 bt_store_16(event, 2, conn->con_handle); 1627 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1628 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1629 } 1630 1631 void hci_emit_nr_connections_changed(){ 1632 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 1633 uint8_t event[3]; 1634 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 1635 event[1] = sizeof(event) - 2; 1636 event[2] = nr_hci_connections(); 1637 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1638 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1639 } 1640 1641 void hci_emit_hci_open_failed(){ 1642 log_info("BTSTACK_EVENT_POWERON_FAILED"); 1643 uint8_t event[2]; 1644 event[0] = BTSTACK_EVENT_POWERON_FAILED; 1645 event[1] = sizeof(event) - 2; 1646 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1647 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1648 } 1649 1650 #ifndef EMBEDDED 1651 void hci_emit_btstack_version() { 1652 log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 1653 uint8_t event[6]; 1654 event[0] = BTSTACK_EVENT_VERSION; 1655 event[1] = sizeof(event) - 2; 1656 event[2] = BTSTACK_MAJOR; 1657 event[3] = BTSTACK_MINOR; 1658 bt_store_16(event, 4, BTSTACK_REVISION); 1659 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1660 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1661 } 1662 #endif 1663 1664 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 1665 log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 1666 uint8_t event[3]; 1667 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 1668 event[1] = sizeof(event) - 2; 1669 event[2] = enabled; 1670 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1671 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1672 } 1673 1674 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){ 1675 uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info 1676 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 1677 event[1] = sizeof(event) - 2 - 1; 1678 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 1679 bt_flip_addr(&event[3], *addr); 1680 memcpy(&event[9], name, 248); 1681 1682 event[9+248] = 0; // assert \0 for log_info 1683 log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]); 1684 1685 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1); 1686 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1); 1687 } 1688 1689 void hci_emit_discoverable_enabled(uint8_t enabled){ 1690 log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled); 1691 uint8_t event[3]; 1692 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 1693 event[1] = sizeof(event) - 2; 1694 event[2] = enabled; 1695 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1696 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1697 } 1698 1699 // GAP API 1700 /** 1701 * @bbrief enable/disable bonding. default is enabled 1702 * @praram enabled 1703 */ 1704 void gap_set_bondable_mode(int enable){ 1705 hci_stack.bondable = enable ? 1 : 0; 1706 } 1707 1708 /** 1709 * @brief get current security level 1710 */ 1711 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 1712 return LEVEL_0; 1713 } 1714 1715 /** 1716 * @brief request connection to device to 1717 * @result GAP_AUTHENTICATION_RESULT 1718 */ 1719 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 1720 } 1721