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