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 "btstack-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 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection); 74 static void hci_connection_timeout_handler(timer_source_t *timer); 75 static void hci_connection_timestamp(hci_connection_t *connection); 76 static int hci_power_control_on(void); 77 static void hci_power_control_off(void); 78 static void hci_state_reset(); 79 80 // the STACK is here 81 #ifndef HAVE_MALLOC 82 static hci_stack_t hci_stack_static; 83 #endif 84 static hci_stack_t * hci_stack = NULL; 85 86 // test helper 87 static uint8_t disable_l2cap_timeouts = 0; 88 89 /** 90 * create connection for given address 91 * 92 * @return connection OR NULL, if no memory left 93 */ 94 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){ 95 96 log_info("create_connection_for_addr %s", bd_addr_to_str(addr)); 97 hci_connection_t * conn = (hci_connection_t *) btstack_memory_hci_connection_get(); 98 if (!conn) return NULL; 99 BD_ADDR_COPY(conn->address, addr); 100 conn->address_type = addr_type; 101 conn->con_handle = 0xffff; 102 conn->authentication_flags = AUTH_FLAGS_NONE; 103 conn->bonding_flags = 0; 104 conn->requested_security_level = LEVEL_0; 105 linked_item_set_user(&conn->timeout.item, conn); 106 conn->timeout.process = hci_connection_timeout_handler; 107 hci_connection_timestamp(conn); 108 conn->acl_recombination_length = 0; 109 conn->acl_recombination_pos = 0; 110 conn->num_acl_packets_sent = 0; 111 linked_list_add(&hci_stack->connections, (linked_item_t *) conn); 112 return conn; 113 } 114 115 /** 116 * get connection for a given handle 117 * 118 * @return connection OR NULL, if not found 119 */ 120 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){ 121 linked_item_t *it; 122 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 123 if ( ((hci_connection_t *) it)->con_handle == con_handle){ 124 return (hci_connection_t *) it; 125 } 126 } 127 return NULL; 128 } 129 130 /** 131 * get connection for given address 132 * 133 * @return connection OR NULL, if not found 134 */ 135 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){ 136 linked_item_t *it; 137 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 138 hci_connection_t * connection = (hci_connection_t *) it; 139 if (connection->address_type != addr_type) continue; 140 if (memcmp(addr, connection->address, 6) != 0) continue; 141 return connection; 142 } 143 return NULL; 144 } 145 146 static void hci_connection_timeout_handler(timer_source_t *timer){ 147 hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item); 148 #ifdef HAVE_TIME 149 struct timeval tv; 150 gettimeofday(&tv, NULL); 151 if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) { 152 // connections might be timed out 153 hci_emit_l2cap_check_timeout(connection); 154 } 155 #endif 156 #ifdef HAVE_TICK 157 if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 158 // connections might be timed out 159 hci_emit_l2cap_check_timeout(connection); 160 } 161 #endif 162 run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS); 163 run_loop_add_timer(timer); 164 } 165 166 static void hci_connection_timestamp(hci_connection_t *connection){ 167 #ifdef HAVE_TIME 168 gettimeofday(&connection->timestamp, NULL); 169 #endif 170 #ifdef HAVE_TICK 171 connection->timestamp = embedded_get_ticks(); 172 #endif 173 } 174 175 176 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 177 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags); 178 } 179 180 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 181 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags); 182 } 183 184 185 /** 186 * add authentication flags and reset timer 187 * @note: assumes classic connection 188 */ 189 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 190 bd_addr_t addr; 191 bt_flip_addr(addr, *(bd_addr_t *) bd_addr); 192 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 193 if (conn) { 194 connectionSetAuthenticationFlags(conn, flags); 195 hci_connection_timestamp(conn); 196 } 197 } 198 199 int hci_authentication_active_for_handle(hci_con_handle_t handle){ 200 hci_connection_t * conn = hci_connection_for_handle(handle); 201 if (!conn) return 0; 202 if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1; 203 if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1; 204 return 0; 205 } 206 207 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){ 208 if (hci_stack->remote_device_db) { 209 hci_stack->remote_device_db->delete_link_key(addr); 210 } 211 } 212 213 int hci_is_le_connection(hci_connection_t * connection){ 214 return connection->address_type == BD_ADDR_TYPE_LE_PUBLIC || 215 connection->address_type == BD_ADDR_TYPE_LE_RANDOM; 216 } 217 218 219 /** 220 * count connections 221 */ 222 static int nr_hci_connections(void){ 223 int count = 0; 224 linked_item_t *it; 225 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++); 226 return count; 227 } 228 229 /** 230 * Dummy handler called by HCI 231 */ 232 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 233 } 234 235 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){ 236 hci_connection_t * connection = hci_connection_for_handle(handle); 237 if (!connection) { 238 log_error("hci_number_outgoing_packets: connection for handle %u does not exist!\n", handle); 239 return 0; 240 } 241 return connection->num_acl_packets_sent; 242 } 243 244 uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){ 245 246 int num_packets_sent_classic = 0; 247 int num_packets_sent_le = 0; 248 249 bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN; 250 251 linked_item_t *it; 252 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 253 hci_connection_t * connection = (hci_connection_t *) it; 254 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){ 255 num_packets_sent_classic += connection->num_acl_packets_sent; 256 } else { 257 num_packets_sent_le += connection->num_acl_packets_sent; 258 } 259 if (connection->con_handle == con_handle){ 260 address_type = connection->address_type; 261 } 262 } 263 264 int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic; 265 int free_slots_le = 0; 266 267 if (free_slots_classic < 0){ 268 log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)\n", num_packets_sent_classic, hci_stack->acl_packets_total_num); 269 return 0; 270 } 271 272 if (hci_stack->le_acl_packets_total_num){ 273 // if we have LE slots, they are used 274 free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le; 275 if (free_slots_le < 0){ 276 log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)\n", num_packets_sent_le, hci_stack->le_acl_packets_total_num); 277 return 0; 278 } 279 } else { 280 // otherwise, classic slots are used for LE, too 281 free_slots_classic -= num_packets_sent_le; 282 if (free_slots_classic < 0){ 283 log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)\n", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num); 284 return 0; 285 } 286 } 287 288 switch (address_type){ 289 case BD_ADDR_TYPE_UNKNOWN: 290 log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list\n", con_handle); 291 return 0; 292 293 case BD_ADDR_TYPE_CLASSIC: 294 return free_slots_classic; 295 296 default: 297 return free_slots_le; 298 } 299 } 300 301 302 // @deprecated 303 int hci_can_send_packet_now(uint8_t packet_type){ 304 switch (packet_type) { 305 case HCI_ACL_DATA_PACKET: 306 return hci_can_send_prepared_acl_packet_now(0); 307 case HCI_COMMAND_DATA_PACKET: 308 return hci_can_send_command_packet_now(); 309 default: 310 return 0; 311 } 312 } 313 314 // @deprecated 315 // same as hci_can_send_packet_now, but also checks if packet buffer is free for use 316 int hci_can_send_packet_now_using_packet_buffer(uint8_t packet_type){ 317 318 if (hci_stack->hci_packet_buffer_reserved) return 0; 319 320 switch (packet_type) { 321 case HCI_ACL_DATA_PACKET: 322 return hci_can_send_acl_packet_now(0); 323 case HCI_COMMAND_DATA_PACKET: 324 return hci_can_send_command_packet_now(); 325 default: 326 return 0; 327 } 328 } 329 330 331 // new functions replacing hci_can_send_packet_now[_using_packet_buffer] 332 int hci_can_send_command_packet_now(void){ 333 if (hci_stack->hci_packet_buffer_reserved) return 0; 334 335 // check for async hci transport implementations 336 if (hci_stack->hci_transport->can_send_packet_now){ 337 if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){ 338 return 0; 339 } 340 } 341 342 return hci_stack->num_cmd_packets > 0; 343 } 344 345 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) { 346 // check for async hci transport implementations 347 if (hci_stack->hci_transport->can_send_packet_now){ 348 if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){ 349 return 0; 350 } 351 } 352 return hci_number_free_acl_slots_for_handle(con_handle) > 0; 353 } 354 355 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){ 356 if (hci_stack->hci_packet_buffer_reserved) return 0; 357 return hci_can_send_prepared_acl_packet_now(con_handle); 358 } 359 360 // used for internal checks in l2cap[-le].c 361 int hci_is_packet_buffer_reserved(void){ 362 return hci_stack->hci_packet_buffer_reserved; 363 } 364 365 // reserves outgoing packet buffer. @returns 1 if successful 366 int hci_reserve_packet_buffer(void){ 367 if (hci_stack->hci_packet_buffer_reserved) { 368 log_error("hci_reserve_packet_buffer called but buffer already reserved"); 369 return 0; 370 } 371 hci_stack->hci_packet_buffer_reserved = 1; 372 return 1; 373 } 374 375 void hci_release_packet_buffer(void){ 376 hci_stack->hci_packet_buffer_reserved = 0; 377 } 378 379 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call 380 int hci_transport_synchronous(void){ 381 return hci_stack->hci_transport->can_send_packet_now == NULL; 382 } 383 384 // pre: caller has reserved the packet buffer 385 int hci_send_acl_packet_buffer(int size){ 386 387 if (!hci_stack->hci_packet_buffer_reserved) { 388 log_error("hci_send_acl_packet_buffer called without reserving packet buffer"); 389 return 0; 390 } 391 392 uint8_t * packet = hci_stack->hci_packet_buffer; 393 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 394 395 // check for free places on Bluetooth module 396 if (!hci_can_send_prepared_acl_packet_now(con_handle)) { 397 log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller"); 398 hci_release_packet_buffer(); 399 return BTSTACK_ACL_BUFFERS_FULL; 400 } 401 402 hci_connection_t *connection = hci_connection_for_handle( con_handle); 403 if (!connection) { 404 log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle); 405 hci_release_packet_buffer(); 406 return 0; 407 } 408 hci_connection_timestamp(connection); 409 410 // count packet 411 connection->num_acl_packets_sent++; 412 // log_info("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent); 413 414 // send packet 415 int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 416 417 // free packet buffer for synchronous transport implementations 418 if (hci_transport_synchronous()){ 419 hci_release_packet_buffer(); 420 } 421 422 return err; 423 } 424 425 static void acl_handler(uint8_t *packet, int size){ 426 427 // log_info("acl_handler: size %u", size); 428 429 // get info 430 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 431 hci_connection_t *conn = hci_connection_for_handle(con_handle); 432 uint8_t acl_flags = READ_ACL_FLAGS(packet); 433 uint16_t acl_length = READ_ACL_LENGTH(packet); 434 435 // ignore non-registered handle 436 if (!conn){ 437 log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle); 438 return; 439 } 440 441 // assert packet is complete 442 if (acl_length + 4 != size){ 443 log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4); 444 return; 445 } 446 447 // update idle timestamp 448 hci_connection_timestamp(conn); 449 450 // handle different packet types 451 switch (acl_flags & 0x03) { 452 453 case 0x01: // continuation fragment 454 455 // sanity check 456 if (conn->acl_recombination_pos == 0) { 457 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle); 458 return; 459 } 460 461 // append fragment payload (header already stored) 462 memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length ); 463 conn->acl_recombination_pos += acl_length; 464 465 // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length, 466 // conn->acl_recombination_pos, conn->acl_recombination_length); 467 468 // forward complete L2CAP packet if complete. 469 if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header 470 471 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos); 472 // reset recombination buffer 473 conn->acl_recombination_length = 0; 474 conn->acl_recombination_pos = 0; 475 } 476 break; 477 478 case 0x02: { // first fragment 479 480 // sanity check 481 if (conn->acl_recombination_pos) { 482 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle); 483 return; 484 } 485 486 // peek into L2CAP packet! 487 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 488 489 // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length); 490 491 // compare fragment size to L2CAP packet size 492 if (acl_length >= l2cap_length + 4){ 493 494 // forward fragment as L2CAP packet 495 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4); 496 497 } else { 498 // store first fragment and tweak acl length for complete package 499 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4); 500 conn->acl_recombination_pos = acl_length + 4; 501 conn->acl_recombination_length = l2cap_length; 502 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4); 503 } 504 break; 505 506 } 507 default: 508 log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03); 509 return; 510 } 511 512 // execute main loop 513 hci_run(); 514 } 515 516 static void hci_shutdown_connection(hci_connection_t *conn){ 517 log_info("Connection closed: handle 0x%x, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 518 519 run_loop_remove_timer(&conn->timeout); 520 521 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 522 btstack_memory_hci_connection_free( conn ); 523 524 // now it's gone 525 hci_emit_nr_connections_changed(); 526 } 527 528 static const uint16_t packet_type_sizes[] = { 529 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 530 HCI_ACL_DH1_SIZE, 0, 0, 0, 531 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 532 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 533 }; 534 static const uint8_t packet_type_feature_requirement_bit[] = { 535 0, // 3 slot packets 536 1, // 5 slot packets 537 25, // EDR 2 mpbs 538 26, // EDR 3 mbps 539 39, // 3 slot EDR packts 540 40, // 5 slot EDR packet 541 }; 542 static const uint16_t packet_type_feature_packet_mask[] = { 543 0x0f00, // 3 slot packets 544 0xf000, // 5 slot packets 545 0x1102, // EDR 2 mpbs 546 0x2204, // EDR 3 mbps 547 0x0300, // 3 slot EDR packts 548 0x3000, // 5 slot EDR packet 549 }; 550 551 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){ 552 // enable packet types based on size 553 uint16_t packet_types = 0; 554 int i; 555 for (i=0;i<16;i++){ 556 if (packet_type_sizes[i] == 0) continue; 557 if (packet_type_sizes[i] <= buffer_size){ 558 packet_types |= 1 << i; 559 } 560 } 561 // disable packet types due to missing local supported features 562 for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){ 563 int bit_idx = packet_type_feature_requirement_bit[i]; 564 int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0; 565 if (feature_set) continue; 566 log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]); 567 packet_types &= ~packet_type_feature_packet_mask[i]; 568 } 569 // flip bits for "may not be used" 570 packet_types ^= 0x3306; 571 return packet_types; 572 } 573 574 uint16_t hci_usable_acl_packet_types(void){ 575 return hci_stack->packet_types; 576 } 577 578 uint8_t* hci_get_outgoing_packet_buffer(void){ 579 // hci packet buffer is >= acl data packet length 580 return hci_stack->hci_packet_buffer; 581 } 582 583 uint16_t hci_max_acl_data_packet_length(void){ 584 return hci_stack->acl_data_packet_length; 585 } 586 587 int hci_non_flushable_packet_boundary_flag_supported(void){ 588 // No. 54, byte 6, bit 6 589 return (hci_stack->local_supported_features[6] & (1 << 6)) != 0; 590 } 591 592 int hci_ssp_supported(void){ 593 // No. 51, byte 6, bit 3 594 return (hci_stack->local_supported_features[6] & (1 << 3)) != 0; 595 } 596 597 int hci_classic_supported(void){ 598 // No. 37, byte 4, bit 5, = No BR/EDR Support 599 return (hci_stack->local_supported_features[4] & (1 << 5)) == 0; 600 } 601 602 int hci_le_supported(void){ 603 #ifdef HAVE_BLE 604 // No. 37, byte 4, bit 6 = LE Supported (Controller) 605 return (hci_stack->local_supported_features[4] & (1 << 6)) != 0; 606 #else 607 return 0; 608 #endif 609 } 610 611 // get addr type and address used in advertisement packets 612 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){ 613 *addr_type = hci_stack->adv_addr_type; 614 if (hci_stack->adv_addr_type){ 615 memcpy(addr, hci_stack->adv_address, 6); 616 } else { 617 memcpy(addr, hci_stack->local_bd_addr, 6); 618 } 619 } 620 621 #ifdef HAVE_BLE 622 void le_handle_advertisement_report(uint8_t *packet, int size){ 623 int num_reports = packet[3]; 624 int i; 625 int total_data_length = 0; 626 int data_offset = 0; 627 628 for (i=0; i<num_reports;i++){ 629 total_data_length += packet[4+num_reports*8+i]; 630 } 631 632 log_info("num reports: %d, ", num_reports); 633 for (i=0; i<num_reports;i++){ 634 int pos = 0; 635 uint8_t data_length = packet[4+num_reports*8+i]; 636 uint8_t event_size = 10 + data_length; 637 uint8_t event[2 + event_size ]; 638 event[pos++] = GAP_LE_ADVERTISING_REPORT; 639 event[pos++] = event_size; 640 event[pos++] = packet[4+i]; // event_type; 641 event[pos++] = packet[4+num_reports+i]; // address_type; 642 memcpy(&event[pos], &packet[4+num_reports*2+i*6], 6); // bt address 643 pos += 6; 644 event[pos++] = packet[4+num_reports*9+total_data_length + i]; 645 log_info("rssi: %d, ", event[pos-1]); 646 event[pos++] = data_length; 647 memcpy(&event[pos], &packet[4+num_reports*9+data_offset], data_length); 648 data_offset += data_length; 649 pos += data_length; 650 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 651 } 652 } 653 #endif 654 655 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){ 656 uint8_t command_completed = 0; 657 if ((hci_stack->substate % 2) == 0) return; 658 // odd: waiting for event 659 if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){ 660 uint16_t opcode = READ_BT_16(packet,3); 661 if (opcode == hci_stack->last_cmd_opcode){ 662 command_completed = 1; 663 log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate); 664 } else { 665 log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 666 } 667 } 668 if (packet[0] == HCI_EVENT_COMMAND_STATUS){ 669 uint8_t status = packet[2]; 670 uint16_t opcode = READ_BT_16(packet,4); 671 if (opcode == hci_stack->last_cmd_opcode){ 672 if (status){ 673 command_completed = 1; 674 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate); 675 } else { 676 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode); 677 } 678 } else { 679 log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 680 } 681 } 682 683 if (!command_completed) return; 684 685 switch(hci_stack->substate >> 1){ 686 default: 687 hci_stack->substate++; 688 break; 689 } 690 } 691 692 static void hci_initializing_state_machine(){ 693 // log_info("hci_init: substate %u\n", hci_stack->substate); 694 if (hci_stack->substate % 2) { 695 // odd: waiting for command completion 696 return; 697 } 698 switch (hci_stack->substate >> 1){ 699 case 0: // RESET 700 hci_state_reset(); 701 702 hci_send_cmd(&hci_reset); 703 if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){ 704 // skip baud change 705 hci_stack->substate = 4; // >> 1 = 2 706 } 707 break; 708 case 1: // SEND BAUD CHANGE 709 hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer); 710 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0); 711 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]); 712 break; 713 case 2: // LOCAL BAUD CHANGE 714 log_info("Local baud rate change"); 715 hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main); 716 hci_stack->substate += 2; 717 // break missing here for fall through 718 719 case 3: 720 log_info("Custom init"); 721 // Custom initialization 722 if (hci_stack->control && hci_stack->control->next_cmd){ 723 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer); 724 if (valid_cmd){ 725 int size = 3 + hci_stack->hci_packet_buffer[2]; 726 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0); 727 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size); 728 hci_stack->substate = 4; // more init commands 729 break; 730 } 731 log_info("hci_run: init script done\n\r"); 732 } 733 // otherwise continue 734 hci_send_cmd(&hci_read_bd_addr); 735 break; 736 case 4: 737 hci_send_cmd(&hci_read_buffer_size); 738 break; 739 case 5: 740 hci_send_cmd(&hci_read_local_supported_features); 741 break; 742 case 6: 743 if (hci_le_supported()){ 744 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF); 745 } else { 746 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 747 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF); 748 } 749 750 // skip Classic init commands for LE only chipsets 751 if (!hci_classic_supported()){ 752 if (hci_le_supported()){ 753 hci_stack->substate = 11 << 1; // skip all classic command 754 } else { 755 log_error("Neither BR/EDR nor LE supported"); 756 hci_stack->substate = 14 << 1; // skip all 757 } 758 } 759 break; 760 case 7: 761 if (hci_ssp_supported()){ 762 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable); 763 break; 764 } 765 hci_stack->substate += 2; 766 // break missing here for fall through 767 768 case 8: 769 // ca. 15 sec 770 hci_send_cmd(&hci_write_page_timeout, 0x6000); 771 break; 772 case 9: 773 hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device); 774 break; 775 case 10: 776 if (hci_stack->local_name){ 777 hci_send_cmd(&hci_write_local_name, hci_stack->local_name); 778 } else { 779 char hostname[30]; 780 #ifdef EMBEDDED 781 // BTstack-11:22:33:44:55:66 782 strcpy(hostname, "BTstack "); 783 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr)); 784 log_info("---> Name %s", hostname); 785 #else 786 // hostname for POSIX systems 787 gethostname(hostname, 30); 788 hostname[29] = '\0'; 789 #endif 790 hci_send_cmd(&hci_write_local_name, hostname); 791 } 792 break; 793 case 11: 794 hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan 795 if (!hci_le_supported()){ 796 // SKIP LE init for Classic only configuration 797 hci_stack->substate = 14 << 1; 798 } 799 break; 800 801 #ifdef HAVE_BLE 802 // LE INIT 803 case 12: 804 hci_send_cmd(&hci_le_read_buffer_size); 805 break; 806 case 13: 807 // LE Supported Host = 1, Simultaneous Host = 0 808 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 809 break; 810 case 14: 811 // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs 812 hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0); 813 break; 814 #endif 815 816 // DONE 817 case 15: 818 // done. 819 hci_stack->state = HCI_STATE_WORKING; 820 hci_emit_state(); 821 break; 822 default: 823 break; 824 } 825 hci_stack->substate++; 826 } 827 828 // avoid huge local variables 829 #ifndef EMBEDDED 830 static device_name_t device_name; 831 #endif 832 static void event_handler(uint8_t *packet, int size){ 833 834 uint16_t event_length = packet[1]; 835 836 // assert packet is complete 837 if (size != event_length + 2){ 838 log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2); 839 return; 840 } 841 842 bd_addr_t addr; 843 bd_addr_type_t addr_type; 844 uint8_t link_type; 845 hci_con_handle_t handle; 846 hci_connection_t * conn; 847 int i; 848 849 // printf("HCI:EVENT:%02x\n", packet[0]); 850 851 switch (packet[0]) { 852 853 case HCI_EVENT_COMMAND_COMPLETE: 854 // get num cmd packets 855 // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack->num_cmd_packets, packet[2]); 856 hci_stack->num_cmd_packets = packet[2]; 857 858 if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){ 859 // from offset 5 860 // status 861 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 862 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6); 863 // ignore: SCO data packet len (8) 864 hci_stack->acl_packets_total_num = packet[9]; 865 // ignore: total num SCO packets 866 if (hci_stack->state == HCI_STATE_INITIALIZING){ 867 // determine usable ACL payload size 868 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){ 869 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 870 } 871 log_info("hci_read_buffer_size: used size %u, count %u\n", 872 hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num); 873 } 874 } 875 #ifdef HAVE_BLE 876 if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){ 877 hci_stack->le_data_packet_length = READ_BT_16(packet, 6); 878 hci_stack->le_acl_packets_total_num = packet[8]; 879 log_info("hci_le_read_buffer_size: size %u, count %u\n", hci_stack->le_data_packet_length, hci_stack->le_acl_packets_total_num); 880 } 881 #endif 882 // Dump local address 883 if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) { 884 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]); 885 log_info("Local Address, Status: 0x%02x: Addr: %s\n", 886 packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr)); 887 } 888 if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 889 hci_emit_discoverable_enabled(hci_stack->discoverable); 890 } 891 // Note: HCI init checks 892 if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){ 893 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8); 894 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x", 895 hci_stack->local_supported_features[0], hci_stack->local_supported_features[1], 896 hci_stack->local_supported_features[2], hci_stack->local_supported_features[3], 897 hci_stack->local_supported_features[4], hci_stack->local_supported_features[5], 898 hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]); 899 900 // determine usable ACL packet types based buffer size and supported features 901 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]); 902 log_info("packet types %04x", hci_stack->packet_types); 903 904 // Classic/LE 905 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported()); 906 } 907 break; 908 909 case HCI_EVENT_COMMAND_STATUS: 910 // get num cmd packets 911 // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack->num_cmd_packets, packet[3]); 912 hci_stack->num_cmd_packets = packet[3]; 913 break; 914 915 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{ 916 int offset = 3; 917 for (i=0; i<packet[2];i++){ 918 handle = READ_BT_16(packet, offset); 919 offset += 2; 920 uint16_t num_packets = READ_BT_16(packet, offset); 921 offset += 2; 922 923 conn = hci_connection_for_handle(handle); 924 if (!conn){ 925 log_error("hci_number_completed_packet lists unused con handle %u\n", handle); 926 continue; 927 } 928 conn->num_acl_packets_sent -= num_packets; 929 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent); 930 } 931 break; 932 } 933 case HCI_EVENT_CONNECTION_REQUEST: 934 bt_flip_addr(addr, &packet[2]); 935 // TODO: eval COD 8-10 936 link_type = packet[11]; 937 log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type); 938 if (link_type == 1) { // ACL 939 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 940 if (!conn) { 941 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 942 } 943 if (!conn) { 944 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 945 hci_stack->decline_reason = 0x0d; 946 BD_ADDR_COPY(hci_stack->decline_addr, addr); 947 break; 948 } 949 conn->state = RECEIVED_CONNECTION_REQUEST; 950 hci_run(); 951 } else { 952 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A) 953 hci_stack->decline_reason = 0x0a; 954 BD_ADDR_COPY(hci_stack->decline_addr, addr); 955 } 956 break; 957 958 case HCI_EVENT_CONNECTION_COMPLETE: 959 // Connection management 960 bt_flip_addr(addr, &packet[5]); 961 log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr)); 962 addr_type = BD_ADDR_TYPE_CLASSIC; 963 conn = hci_connection_for_bd_addr_and_type(&addr, addr_type); 964 if (conn) { 965 if (!packet[2]){ 966 conn->state = OPEN; 967 conn->con_handle = READ_BT_16(packet, 3); 968 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES; 969 970 // restart timer 971 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 972 run_loop_add_timer(&conn->timeout); 973 974 log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 975 976 hci_emit_nr_connections_changed(); 977 } else { 978 // notify client if dedicated bonding 979 if (conn->bonding_flags & BONDING_DEDICATED){ 980 hci_emit_dedicated_bonding_result(conn, packet[2]); 981 } 982 983 // connection failed, remove entry 984 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 985 btstack_memory_hci_connection_free( conn ); 986 987 // if authentication error, also delete link key 988 if (packet[2] == 0x05) { 989 hci_drop_link_key_for_bd_addr(&addr); 990 } 991 } 992 } 993 break; 994 995 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 996 handle = READ_BT_16(packet, 3); 997 conn = hci_connection_for_handle(handle); 998 if (!conn) break; 999 if (!packet[2]){ 1000 uint8_t * features = &packet[5]; 1001 if (features[6] & (1 << 3)){ 1002 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP; 1003 } 1004 } 1005 conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES; 1006 log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags); 1007 if (conn->bonding_flags & BONDING_DEDICATED){ 1008 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 1009 } 1010 break; 1011 1012 case HCI_EVENT_LINK_KEY_REQUEST: 1013 log_info("HCI_EVENT_LINK_KEY_REQUEST\n"); 1014 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST); 1015 // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST 1016 if (hci_stack->bondable && !hci_stack->remote_device_db) break; 1017 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST); 1018 hci_run(); 1019 // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set 1020 return; 1021 1022 case HCI_EVENT_LINK_KEY_NOTIFICATION: { 1023 bt_flip_addr(addr, &packet[2]); 1024 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1025 if (!conn) break; 1026 conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION; 1027 link_key_type_t link_key_type = (link_key_type_t)packet[24]; 1028 // Change Connection Encryption keeps link key type 1029 if (link_key_type != CHANGED_COMBINATION_KEY){ 1030 conn->link_key_type = link_key_type; 1031 } 1032 if (!hci_stack->remote_device_db) break; 1033 hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type); 1034 // still forward event to allow dismiss of pairing dialog 1035 break; 1036 } 1037 1038 case HCI_EVENT_PIN_CODE_REQUEST: 1039 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE); 1040 // non-bondable mode: pin code negative reply will be sent 1041 if (!hci_stack->bondable){ 1042 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST); 1043 hci_run(); 1044 return; 1045 } 1046 // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key 1047 if (!hci_stack->remote_device_db) break; 1048 bt_flip_addr(addr, &packet[2]); 1049 hci_stack->remote_device_db->delete_link_key(&addr); 1050 break; 1051 1052 case HCI_EVENT_IO_CAPABILITY_REQUEST: 1053 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST); 1054 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY); 1055 break; 1056 1057 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 1058 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 1059 if (!hci_stack->ssp_auto_accept) break; 1060 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY); 1061 break; 1062 1063 case HCI_EVENT_USER_PASSKEY_REQUEST: 1064 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 1065 if (!hci_stack->ssp_auto_accept) break; 1066 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY); 1067 break; 1068 1069 case HCI_EVENT_ENCRYPTION_CHANGE: 1070 handle = READ_BT_16(packet, 3); 1071 conn = hci_connection_for_handle(handle); 1072 if (!conn) break; 1073 if (packet[2] == 0) { 1074 if (packet[5]){ 1075 conn->authentication_flags |= CONNECTION_ENCRYPTED; 1076 } else { 1077 conn->authentication_flags &= ~CONNECTION_ENCRYPTED; 1078 } 1079 } 1080 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 1081 break; 1082 1083 case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT: 1084 handle = READ_BT_16(packet, 3); 1085 conn = hci_connection_for_handle(handle); 1086 if (!conn) break; 1087 1088 // dedicated bonding: send result and disconnect 1089 if (conn->bonding_flags & BONDING_DEDICATED){ 1090 conn->bonding_flags &= ~BONDING_DEDICATED; 1091 hci_emit_dedicated_bonding_result( conn, packet[2]); 1092 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 1093 break; 1094 } 1095 1096 if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){ 1097 // link key sufficient for requested security 1098 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 1099 break; 1100 } 1101 // not enough 1102 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 1103 break; 1104 1105 #ifndef EMBEDDED 1106 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 1107 if (!hci_stack->remote_device_db) break; 1108 if (packet[2]) break; // status not ok 1109 bt_flip_addr(addr, &packet[3]); 1110 // fix for invalid remote names - terminate on 0xff 1111 for (i=0; i<248;i++){ 1112 if (packet[9+i] == 0xff){ 1113 packet[9+i] = 0; 1114 break; 1115 } 1116 } 1117 memset(&device_name, 0, sizeof(device_name_t)); 1118 strncpy((char*) device_name, (char*) &packet[9], 248); 1119 hci_stack->remote_device_db->put_name(&addr, &device_name); 1120 break; 1121 1122 case HCI_EVENT_INQUIRY_RESULT: 1123 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{ 1124 if (!hci_stack->remote_device_db) break; 1125 // first send inq result packet 1126 hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size); 1127 // then send cached remote names 1128 int offset = 3; 1129 for (i=0; i<packet[2];i++){ 1130 bt_flip_addr(addr, &packet[offset]); 1131 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2; 1132 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){ 1133 hci_emit_remote_name_cached(&addr, &device_name); 1134 } 1135 } 1136 return; 1137 } 1138 #endif 1139 1140 case HCI_EVENT_DISCONNECTION_COMPLETE: 1141 if (!packet[2]){ 1142 handle = READ_BT_16(packet, 3); 1143 hci_connection_t * conn = hci_connection_for_handle(handle); 1144 if (conn) { 1145 hci_shutdown_connection(conn); 1146 } 1147 } 1148 break; 1149 1150 case HCI_EVENT_HARDWARE_ERROR: 1151 if(hci_stack->control && hci_stack->control->hw_error){ 1152 (*hci_stack->control->hw_error)(); 1153 } else { 1154 // if no special requests, just reboot stack 1155 hci_power_control_off(); 1156 hci_power_control_on(); 1157 } 1158 break; 1159 1160 case DAEMON_EVENT_HCI_PACKET_SENT: 1161 // free packet buffer for asynchronous transport 1162 if (hci_transport_synchronous()) break; 1163 hci_stack->hci_packet_buffer_reserved = 0; 1164 break; 1165 1166 #ifdef HAVE_BLE 1167 case HCI_EVENT_LE_META: 1168 switch (packet[2]){ 1169 case HCI_SUBEVENT_LE_ADVERTISING_REPORT: 1170 log_info("advertising report received\n"); 1171 if (hci_stack->le_scanning_state != LE_SCANNING) break; 1172 le_handle_advertisement_report(packet, size); 1173 break; 1174 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 1175 // Connection management 1176 bt_flip_addr(addr, &packet[8]); 1177 addr_type = (bd_addr_type_t)packet[7]; 1178 log_info("LE Connection_complete (status=%u) type %u, %s\n", packet[3], addr_type, bd_addr_to_str(addr)); 1179 // LE connections are auto-accepted, so just create a connection if there isn't one already 1180 conn = hci_connection_for_bd_addr_and_type(&addr, addr_type); 1181 if (packet[3]){ 1182 if (conn){ 1183 // outgoing connection failed, remove entry 1184 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 1185 btstack_memory_hci_connection_free( conn ); 1186 } 1187 // if authentication error, also delete link key 1188 if (packet[3] == 0x05) { 1189 hci_drop_link_key_for_bd_addr(&addr); 1190 } 1191 break; 1192 } 1193 if (!conn){ 1194 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 1195 } 1196 if (!conn){ 1197 // no memory 1198 break; 1199 } 1200 1201 conn->state = OPEN; 1202 conn->con_handle = READ_BT_16(packet, 4); 1203 1204 // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock 1205 1206 // restart timer 1207 // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 1208 // run_loop_add_timer(&conn->timeout); 1209 1210 log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 1211 1212 hci_emit_nr_connections_changed(); 1213 break; 1214 1215 // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]); 1216 1217 default: 1218 break; 1219 } 1220 break; 1221 #endif 1222 default: 1223 break; 1224 } 1225 1226 // handle BT initialization 1227 if (hci_stack->state == HCI_STATE_INITIALIZING){ 1228 hci_initializing_event_handler(packet, size); 1229 } 1230 1231 // help with BT sleep 1232 if (hci_stack->state == HCI_STATE_FALLING_ASLEEP 1233 && hci_stack->substate == 1 1234 && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 1235 hci_stack->substate++; 1236 } 1237 1238 hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size); 1239 1240 // execute main loop 1241 hci_run(); 1242 } 1243 1244 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 1245 switch (packet_type) { 1246 case HCI_EVENT_PACKET: 1247 event_handler(packet, size); 1248 break; 1249 case HCI_ACL_DATA_PACKET: 1250 acl_handler(packet, size); 1251 break; 1252 default: 1253 break; 1254 } 1255 } 1256 1257 /** Register HCI packet handlers */ 1258 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 1259 hci_stack->packet_handler = handler; 1260 } 1261 1262 static void hci_state_reset(){ 1263 // no connections yet 1264 hci_stack->connections = NULL; 1265 1266 // keep discoverable/connectable as this has been requested by the client(s) 1267 // hci_stack->discoverable = 0; 1268 // hci_stack->connectable = 0; 1269 // hci_stack->bondable = 1; 1270 1271 // buffer is free 1272 hci_stack->hci_packet_buffer_reserved = 0; 1273 1274 // no pending cmds 1275 hci_stack->decline_reason = 0; 1276 hci_stack->new_scan_enable_value = 0xff; 1277 1278 // LE 1279 hci_stack->adv_addr_type = 0; 1280 memset(hci_stack->adv_address, 0, 6); 1281 hci_stack->le_scanning_state = LE_SCAN_IDLE; 1282 hci_stack->le_scan_type = 0xff; 1283 } 1284 1285 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){ 1286 1287 #ifdef HAVE_MALLOC 1288 if (!hci_stack) { 1289 hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t)); 1290 } 1291 #else 1292 hci_stack = &hci_stack_static; 1293 #endif 1294 memset(hci_stack, 0, sizeof(hci_stack_t)); 1295 1296 // reference to use transport layer implementation 1297 hci_stack->hci_transport = transport; 1298 1299 // references to used control implementation 1300 hci_stack->control = control; 1301 1302 // reference to used config 1303 hci_stack->config = config; 1304 1305 // higher level handler 1306 hci_stack->packet_handler = dummy_handler; 1307 1308 // store and open remote device db 1309 hci_stack->remote_device_db = remote_device_db; 1310 if (hci_stack->remote_device_db) { 1311 hci_stack->remote_device_db->open(); 1312 } 1313 1314 // max acl payload size defined in config.h 1315 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 1316 1317 // register packet handlers with transport 1318 transport->register_packet_handler(&packet_handler); 1319 1320 hci_stack->state = HCI_STATE_OFF; 1321 1322 // class of device 1323 hci_stack->class_of_device = 0x007a020c; // Smartphone 1324 1325 // bondable by default 1326 hci_stack->bondable = 1; 1327 1328 // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept 1329 hci_stack->ssp_enable = 1; 1330 hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 1331 hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 1332 hci_stack->ssp_auto_accept = 1; 1333 1334 hci_state_reset(); 1335 } 1336 1337 void hci_close(){ 1338 // close remote device db 1339 if (hci_stack->remote_device_db) { 1340 hci_stack->remote_device_db->close(); 1341 } 1342 while (hci_stack->connections) { 1343 // cancel all l2cap connections 1344 hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host 1345 hci_shutdown_connection((hci_connection_t *) hci_stack->connections); 1346 } 1347 hci_power_control(HCI_POWER_OFF); 1348 1349 #ifdef HAVE_MALLOC 1350 free(hci_stack); 1351 #endif 1352 hci_stack = NULL; 1353 } 1354 1355 void hci_set_class_of_device(uint32_t class_of_device){ 1356 hci_stack->class_of_device = class_of_device; 1357 } 1358 1359 void hci_disable_l2cap_timeout_check(){ 1360 disable_l2cap_timeouts = 1; 1361 } 1362 // State-Module-Driver overview 1363 // state module low-level 1364 // HCI_STATE_OFF off close 1365 // HCI_STATE_INITIALIZING, on open 1366 // HCI_STATE_WORKING, on open 1367 // HCI_STATE_HALTING, on open 1368 // HCI_STATE_SLEEPING, off/sleep close 1369 // HCI_STATE_FALLING_ASLEEP on open 1370 1371 static int hci_power_control_on(void){ 1372 1373 // power on 1374 int err = 0; 1375 if (hci_stack->control && hci_stack->control->on){ 1376 err = (*hci_stack->control->on)(hci_stack->config); 1377 } 1378 if (err){ 1379 log_error( "POWER_ON failed\n"); 1380 hci_emit_hci_open_failed(); 1381 return err; 1382 } 1383 1384 // open low-level device 1385 err = hci_stack->hci_transport->open(hci_stack->config); 1386 if (err){ 1387 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 1388 if (hci_stack->control && hci_stack->control->off){ 1389 (*hci_stack->control->off)(hci_stack->config); 1390 } 1391 hci_emit_hci_open_failed(); 1392 return err; 1393 } 1394 return 0; 1395 } 1396 1397 static void hci_power_control_off(void){ 1398 1399 log_info("hci_power_control_off\n"); 1400 1401 // close low-level device 1402 hci_stack->hci_transport->close(hci_stack->config); 1403 1404 log_info("hci_power_control_off - hci_transport closed\n"); 1405 1406 // power off 1407 if (hci_stack->control && hci_stack->control->off){ 1408 (*hci_stack->control->off)(hci_stack->config); 1409 } 1410 1411 log_info("hci_power_control_off - control closed\n"); 1412 1413 hci_stack->state = HCI_STATE_OFF; 1414 } 1415 1416 static void hci_power_control_sleep(void){ 1417 1418 log_info("hci_power_control_sleep\n"); 1419 1420 #if 0 1421 // don't close serial port during sleep 1422 1423 // close low-level device 1424 hci_stack->hci_transport->close(hci_stack->config); 1425 #endif 1426 1427 // sleep mode 1428 if (hci_stack->control && hci_stack->control->sleep){ 1429 (*hci_stack->control->sleep)(hci_stack->config); 1430 } 1431 1432 hci_stack->state = HCI_STATE_SLEEPING; 1433 } 1434 1435 static int hci_power_control_wake(void){ 1436 1437 log_info("hci_power_control_wake\n"); 1438 1439 // wake on 1440 if (hci_stack->control && hci_stack->control->wake){ 1441 (*hci_stack->control->wake)(hci_stack->config); 1442 } 1443 1444 #if 0 1445 // open low-level device 1446 int err = hci_stack->hci_transport->open(hci_stack->config); 1447 if (err){ 1448 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 1449 if (hci_stack->control && hci_stack->control->off){ 1450 (*hci_stack->control->off)(hci_stack->config); 1451 } 1452 hci_emit_hci_open_failed(); 1453 return err; 1454 } 1455 #endif 1456 1457 return 0; 1458 } 1459 1460 static void hci_power_transition_to_initializing(void){ 1461 // set up state machine 1462 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 1463 hci_stack->hci_packet_buffer_reserved = 0; 1464 hci_stack->state = HCI_STATE_INITIALIZING; 1465 hci_stack->substate = 0; 1466 } 1467 1468 int hci_power_control(HCI_POWER_MODE power_mode){ 1469 1470 log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack->state); 1471 1472 int err = 0; 1473 switch (hci_stack->state){ 1474 1475 case HCI_STATE_OFF: 1476 switch (power_mode){ 1477 case HCI_POWER_ON: 1478 err = hci_power_control_on(); 1479 if (err) { 1480 log_error("hci_power_control_on() error %u", err); 1481 return err; 1482 } 1483 hci_power_transition_to_initializing(); 1484 break; 1485 case HCI_POWER_OFF: 1486 // do nothing 1487 break; 1488 case HCI_POWER_SLEEP: 1489 // do nothing (with SLEEP == OFF) 1490 break; 1491 } 1492 break; 1493 1494 case HCI_STATE_INITIALIZING: 1495 switch (power_mode){ 1496 case HCI_POWER_ON: 1497 // do nothing 1498 break; 1499 case HCI_POWER_OFF: 1500 // no connections yet, just turn it off 1501 hci_power_control_off(); 1502 break; 1503 case HCI_POWER_SLEEP: 1504 // no connections yet, just turn it off 1505 hci_power_control_sleep(); 1506 break; 1507 } 1508 break; 1509 1510 case HCI_STATE_WORKING: 1511 switch (power_mode){ 1512 case HCI_POWER_ON: 1513 // do nothing 1514 break; 1515 case HCI_POWER_OFF: 1516 // see hci_run 1517 hci_stack->state = HCI_STATE_HALTING; 1518 break; 1519 case HCI_POWER_SLEEP: 1520 // see hci_run 1521 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 1522 hci_stack->substate = 0; 1523 break; 1524 } 1525 break; 1526 1527 case HCI_STATE_HALTING: 1528 switch (power_mode){ 1529 case HCI_POWER_ON: 1530 hci_power_transition_to_initializing(); 1531 break; 1532 case HCI_POWER_OFF: 1533 // do nothing 1534 break; 1535 case HCI_POWER_SLEEP: 1536 // see hci_run 1537 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 1538 hci_stack->substate = 0; 1539 break; 1540 } 1541 break; 1542 1543 case HCI_STATE_FALLING_ASLEEP: 1544 switch (power_mode){ 1545 case HCI_POWER_ON: 1546 1547 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1548 // nothing to do, if H4 supports power management 1549 if (bt_control_iphone_power_management_enabled()){ 1550 hci_stack->state = HCI_STATE_INITIALIZING; 1551 hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP; 1552 break; 1553 } 1554 #endif 1555 hci_power_transition_to_initializing(); 1556 break; 1557 case HCI_POWER_OFF: 1558 // see hci_run 1559 hci_stack->state = HCI_STATE_HALTING; 1560 break; 1561 case HCI_POWER_SLEEP: 1562 // do nothing 1563 break; 1564 } 1565 break; 1566 1567 case HCI_STATE_SLEEPING: 1568 switch (power_mode){ 1569 case HCI_POWER_ON: 1570 1571 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1572 // nothing to do, if H4 supports power management 1573 if (bt_control_iphone_power_management_enabled()){ 1574 hci_stack->state = HCI_STATE_INITIALIZING; 1575 hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP; 1576 hci_update_scan_enable(); 1577 break; 1578 } 1579 #endif 1580 err = hci_power_control_wake(); 1581 if (err) return err; 1582 hci_power_transition_to_initializing(); 1583 break; 1584 case HCI_POWER_OFF: 1585 hci_stack->state = HCI_STATE_HALTING; 1586 break; 1587 case HCI_POWER_SLEEP: 1588 // do nothing 1589 break; 1590 } 1591 break; 1592 } 1593 1594 // create internal event 1595 hci_emit_state(); 1596 1597 // trigger next/first action 1598 hci_run(); 1599 1600 return 0; 1601 } 1602 1603 static void hci_update_scan_enable(void){ 1604 // 2 = page scan, 1 = inq scan 1605 hci_stack->new_scan_enable_value = hci_stack->connectable << 1 | hci_stack->discoverable; 1606 hci_run(); 1607 } 1608 1609 void hci_discoverable_control(uint8_t enable){ 1610 if (enable) enable = 1; // normalize argument 1611 1612 if (hci_stack->discoverable == enable){ 1613 hci_emit_discoverable_enabled(hci_stack->discoverable); 1614 return; 1615 } 1616 1617 hci_stack->discoverable = enable; 1618 hci_update_scan_enable(); 1619 } 1620 1621 void hci_connectable_control(uint8_t enable){ 1622 if (enable) enable = 1; // normalize argument 1623 1624 // don't emit event 1625 if (hci_stack->connectable == enable) return; 1626 1627 hci_stack->connectable = enable; 1628 hci_update_scan_enable(); 1629 } 1630 1631 bd_addr_t * hci_local_bd_addr(void){ 1632 return &hci_stack->local_bd_addr; 1633 } 1634 1635 void hci_run(){ 1636 1637 hci_connection_t * connection; 1638 linked_item_t * it; 1639 1640 if (!hci_can_send_command_packet_now()) return; 1641 1642 // global/non-connection oriented commands 1643 1644 // decline incoming connections 1645 if (hci_stack->decline_reason){ 1646 uint8_t reason = hci_stack->decline_reason; 1647 hci_stack->decline_reason = 0; 1648 hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason); 1649 return; 1650 } 1651 1652 // send scan enable 1653 if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){ 1654 hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value); 1655 hci_stack->new_scan_enable_value = 0xff; 1656 return; 1657 } 1658 1659 #ifdef HAVE_BLE 1660 // handle le scan 1661 if (hci_stack->state == HCI_STATE_WORKING){ 1662 switch(hci_stack->le_scanning_state){ 1663 case LE_START_SCAN: 1664 hci_stack->le_scanning_state = LE_SCANNING; 1665 hci_send_cmd(&hci_le_set_scan_enable, 1, 0); 1666 return; 1667 1668 case LE_STOP_SCAN: 1669 hci_stack->le_scanning_state = LE_SCAN_IDLE; 1670 hci_send_cmd(&hci_le_set_scan_enable, 0, 0); 1671 return; 1672 default: 1673 break; 1674 } 1675 if (hci_stack->le_scan_type != 0xff){ 1676 // defaults: active scanning, accept all advertisement packets 1677 int scan_type = hci_stack->le_scan_type; 1678 hci_stack->le_scan_type = 0xff; 1679 hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0); 1680 return; 1681 } 1682 } 1683 #endif 1684 1685 // send pending HCI commands 1686 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 1687 connection = (hci_connection_t *) it; 1688 1689 switch(connection->state){ 1690 case SEND_CREATE_CONNECTION: 1691 switch(connection->address_type){ 1692 case BD_ADDR_TYPE_CLASSIC: 1693 log_info("sending hci_create_connection\n"); 1694 hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1); 1695 break; 1696 default: 1697 #ifdef HAVE_BLE 1698 log_info("sending hci_le_create_connection\n"); 1699 hci_send_cmd(&hci_le_create_connection, 1700 0x0060, // scan interval: 60 ms 1701 0x0030, // scan interval: 30 ms 1702 0, // don't use whitelist 1703 connection->address_type, // peer address type 1704 connection->address, // peer bd addr 1705 hci_stack->adv_addr_type, // our addr type: 1706 0x0008, // conn interval min 1707 0x0018, // conn interval max 1708 0, // conn latency 1709 0x0048, // supervision timeout 1710 0x0001, // min ce length 1711 0x0001 // max ce length 1712 ); 1713 1714 connection->state = SENT_CREATE_CONNECTION; 1715 #endif 1716 break; 1717 } 1718 return; 1719 1720 case RECEIVED_CONNECTION_REQUEST: 1721 log_info("sending hci_accept_connection_request\n"); 1722 connection->state = ACCEPTED_CONNECTION_REQUEST; 1723 hci_send_cmd(&hci_accept_connection_request, connection->address, 1); 1724 return; 1725 1726 #ifdef HAVE_BLE 1727 case SEND_CANCEL_CONNECTION: 1728 connection->state = SENT_CANCEL_CONNECTION; 1729 hci_send_cmd(&hci_le_create_connection_cancel); 1730 return; 1731 #endif 1732 case SEND_DISCONNECT: 1733 connection->state = SENT_DISCONNECT; 1734 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1735 return; 1736 1737 default: 1738 break; 1739 } 1740 1741 if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){ 1742 log_info("responding to link key request\n"); 1743 connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST); 1744 link_key_t link_key; 1745 link_key_type_t link_key_type; 1746 if ( hci_stack->remote_device_db 1747 && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type) 1748 && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){ 1749 connection->link_key_type = link_key_type; 1750 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key); 1751 } else { 1752 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 1753 } 1754 return; 1755 } 1756 1757 if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){ 1758 log_info("denying to pin request\n"); 1759 connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST); 1760 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 1761 return; 1762 } 1763 1764 if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){ 1765 connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY); 1766 log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability); 1767 if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){ 1768 // tweak authentication requirements 1769 uint8_t authreq = hci_stack->ssp_authentication_requirement; 1770 if (connection->bonding_flags & BONDING_DEDICATED){ 1771 authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 1772 } 1773 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){ 1774 authreq |= 1; 1775 } 1776 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq); 1777 } else { 1778 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 1779 } 1780 return; 1781 } 1782 1783 if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){ 1784 connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY); 1785 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 1786 return; 1787 } 1788 1789 if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){ 1790 connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY); 1791 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 1792 return; 1793 } 1794 1795 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){ 1796 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES; 1797 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 1798 return; 1799 } 1800 1801 if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){ 1802 connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK; 1803 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005); // authentication failure 1804 return; 1805 } 1806 if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){ 1807 connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE; 1808 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // authentication done 1809 return; 1810 } 1811 if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){ 1812 connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST; 1813 hci_send_cmd(&hci_authentication_requested, connection->con_handle); 1814 return; 1815 } 1816 if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){ 1817 connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST; 1818 hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1); 1819 return; 1820 } 1821 } 1822 1823 switch (hci_stack->state){ 1824 case HCI_STATE_INITIALIZING: 1825 hci_initializing_state_machine(); 1826 break; 1827 1828 case HCI_STATE_HALTING: 1829 1830 log_info("HCI_STATE_HALTING\n"); 1831 // close all open connections 1832 connection = (hci_connection_t *) hci_stack->connections; 1833 if (connection){ 1834 1835 // send disconnect 1836 if (!hci_can_send_command_packet_now()) return; 1837 1838 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle); 1839 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1840 1841 // send disconnected event right away - causes higher layer connections to get closed, too. 1842 hci_shutdown_connection(connection); 1843 return; 1844 } 1845 log_info("HCI_STATE_HALTING, calling off\n"); 1846 1847 // switch mode 1848 hci_power_control_off(); 1849 1850 log_info("HCI_STATE_HALTING, emitting state\n"); 1851 hci_emit_state(); 1852 log_info("HCI_STATE_HALTING, done\n"); 1853 break; 1854 1855 case HCI_STATE_FALLING_ASLEEP: 1856 switch(hci_stack->substate) { 1857 case 0: 1858 log_info("HCI_STATE_FALLING_ASLEEP\n"); 1859 // close all open connections 1860 connection = (hci_connection_t *) hci_stack->connections; 1861 1862 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1863 // don't close connections, if H4 supports power management 1864 if (bt_control_iphone_power_management_enabled()){ 1865 connection = NULL; 1866 } 1867 #endif 1868 if (connection){ 1869 1870 // send disconnect 1871 if (!hci_can_send_command_packet_now()) return; 1872 1873 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle); 1874 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1875 1876 // send disconnected event right away - causes higher layer connections to get closed, too. 1877 hci_shutdown_connection(connection); 1878 return; 1879 } 1880 1881 if (hci_classic_supported()){ 1882 // disable page and inquiry scan 1883 if (!hci_can_send_command_packet_now()) return; 1884 1885 log_info("HCI_STATE_HALTING, disabling inq scans\n"); 1886 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 1887 1888 // continue in next sub state 1889 hci_stack->substate++; 1890 break; 1891 } 1892 // fall through for ble-only chips 1893 1894 case 2: 1895 log_info("HCI_STATE_HALTING, calling sleep\n"); 1896 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1897 // don't actually go to sleep, if H4 supports power management 1898 if (bt_control_iphone_power_management_enabled()){ 1899 // SLEEP MODE reached 1900 hci_stack->state = HCI_STATE_SLEEPING; 1901 hci_emit_state(); 1902 break; 1903 } 1904 #endif 1905 // switch mode 1906 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 1907 hci_emit_state(); 1908 break; 1909 1910 default: 1911 break; 1912 } 1913 break; 1914 1915 default: 1916 break; 1917 } 1918 } 1919 1920 int hci_send_cmd_packet(uint8_t *packet, int size){ 1921 bd_addr_t addr; 1922 hci_connection_t * conn; 1923 // house-keeping 1924 1925 // create_connection? 1926 if (IS_COMMAND(packet, hci_create_connection)){ 1927 bt_flip_addr(addr, &packet[3]); 1928 log_info("Create_connection to %s\n", bd_addr_to_str(addr)); 1929 1930 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1931 if (!conn){ 1932 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 1933 if (!conn){ 1934 // notify client that alloc failed 1935 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 1936 return 0; // don't sent packet to controller 1937 } 1938 conn->state = SEND_CREATE_CONNECTION; 1939 } 1940 log_info("conn state %u", conn->state); 1941 switch (conn->state){ 1942 // if connection active exists 1943 case OPEN: 1944 // and OPEN, emit connection complete command, don't send to controller 1945 hci_emit_connection_complete(conn, 0); 1946 return 0; 1947 case SEND_CREATE_CONNECTION: 1948 // connection created by hci, e.g. dedicated bonding 1949 break; 1950 default: 1951 // otherwise, just ignore as it is already in the open process 1952 return 0; 1953 } 1954 conn->state = SENT_CREATE_CONNECTION; 1955 } 1956 1957 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 1958 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 1959 } 1960 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 1961 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 1962 } 1963 1964 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 1965 if (hci_stack->remote_device_db){ 1966 bt_flip_addr(addr, &packet[3]); 1967 hci_stack->remote_device_db->delete_link_key(&addr); 1968 } 1969 } 1970 1971 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply) 1972 || IS_COMMAND(packet, hci_pin_code_request_reply)){ 1973 bt_flip_addr(addr, &packet[3]); 1974 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1975 if (conn){ 1976 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE); 1977 } 1978 } 1979 1980 if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply) 1981 || IS_COMMAND(packet, hci_user_confirmation_request_reply) 1982 || IS_COMMAND(packet, hci_user_passkey_request_negative_reply) 1983 || IS_COMMAND(packet, hci_user_passkey_request_reply)) { 1984 bt_flip_addr(addr, &packet[3]); 1985 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1986 if (conn){ 1987 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE); 1988 } 1989 } 1990 1991 #ifdef HAVE_BLE 1992 if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){ 1993 hci_stack->adv_addr_type = packet[8]; 1994 } 1995 if (IS_COMMAND(packet, hci_le_set_random_address)){ 1996 bt_flip_addr(hci_stack->adv_address, &packet[3]); 1997 } 1998 #endif 1999 2000 hci_stack->num_cmd_packets--; 2001 int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 2002 2003 // free packet buffer for synchronous transport implementations 2004 if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){ 2005 hci_stack->hci_packet_buffer_reserved = 0; 2006 } 2007 2008 return err; 2009 } 2010 2011 // disconnect because of security block 2012 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 2013 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2014 if (!connection) return; 2015 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 2016 } 2017 2018 2019 // Configure Secure Simple Pairing 2020 2021 // enable will enable SSP during init 2022 void hci_ssp_set_enable(int enable){ 2023 hci_stack->ssp_enable = enable; 2024 } 2025 2026 int hci_local_ssp_activated(){ 2027 return hci_ssp_supported() && hci_stack->ssp_enable; 2028 } 2029 2030 // if set, BTstack will respond to io capability request using authentication requirement 2031 void hci_ssp_set_io_capability(int io_capability){ 2032 hci_stack->ssp_io_capability = io_capability; 2033 } 2034 void hci_ssp_set_authentication_requirement(int authentication_requirement){ 2035 hci_stack->ssp_authentication_requirement = authentication_requirement; 2036 } 2037 2038 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 2039 void hci_ssp_set_auto_accept(int auto_accept){ 2040 hci_stack->ssp_auto_accept = auto_accept; 2041 } 2042 2043 /** 2044 * pre: numcmds >= 0 - it's allowed to send a command to the controller 2045 */ 2046 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 2047 2048 if (!hci_can_send_command_packet_now()){ 2049 log_error("hci_send_cmd called but cannot send packet now"); 2050 return 0; 2051 } 2052 2053 // for HCI INITIALIZATION 2054 // printf("hci_send_cmd: opcode %04x\n", cmd->opcode); 2055 hci_stack->last_cmd_opcode = cmd->opcode; 2056 2057 hci_reserve_packet_buffer(); 2058 uint8_t * packet = hci_stack->hci_packet_buffer; 2059 2060 va_list argptr; 2061 va_start(argptr, cmd); 2062 uint16_t size = hci_create_cmd_internal(packet, cmd, argptr); 2063 va_end(argptr); 2064 2065 return hci_send_cmd_packet(packet, size); 2066 } 2067 2068 // Create various non-HCI events. 2069 // TODO: generalize, use table similar to hci_create_command 2070 2071 void hci_emit_state(){ 2072 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 2073 uint8_t event[3]; 2074 event[0] = BTSTACK_EVENT_STATE; 2075 event[1] = sizeof(event) - 2; 2076 event[2] = hci_stack->state; 2077 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2078 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2079 } 2080 2081 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){ 2082 uint8_t event[13]; 2083 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 2084 event[1] = sizeof(event) - 2; 2085 event[2] = status; 2086 bt_store_16(event, 3, conn->con_handle); 2087 bt_flip_addr(&event[5], conn->address); 2088 event[11] = 1; // ACL connection 2089 event[12] = 0; // encryption disabled 2090 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2091 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2092 } 2093 2094 void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){ 2095 uint8_t event[21]; 2096 event[0] = HCI_EVENT_LE_META; 2097 event[1] = sizeof(event) - 2; 2098 event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE; 2099 event[3] = status; 2100 bt_store_16(event, 4, conn->con_handle); 2101 event[6] = 0; // TODO: role 2102 event[7] = conn->address_type; 2103 bt_flip_addr(&event[8], conn->address); 2104 bt_store_16(event, 14, 0); // interval 2105 bt_store_16(event, 16, 0); // latency 2106 bt_store_16(event, 18, 0); // supervision timeout 2107 event[20] = 0; // master clock accuracy 2108 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2109 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2110 } 2111 2112 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 2113 uint8_t event[6]; 2114 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 2115 event[1] = sizeof(event) - 2; 2116 event[2] = 0; // status = OK 2117 bt_store_16(event, 3, handle); 2118 event[5] = reason; 2119 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2120 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2121 } 2122 2123 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 2124 if (disable_l2cap_timeouts) return; 2125 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 2126 uint8_t event[4]; 2127 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 2128 event[1] = sizeof(event) - 2; 2129 bt_store_16(event, 2, conn->con_handle); 2130 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2131 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2132 } 2133 2134 void hci_emit_nr_connections_changed(){ 2135 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 2136 uint8_t event[3]; 2137 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 2138 event[1] = sizeof(event) - 2; 2139 event[2] = nr_hci_connections(); 2140 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2141 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2142 } 2143 2144 void hci_emit_hci_open_failed(){ 2145 log_info("BTSTACK_EVENT_POWERON_FAILED"); 2146 uint8_t event[2]; 2147 event[0] = BTSTACK_EVENT_POWERON_FAILED; 2148 event[1] = sizeof(event) - 2; 2149 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2150 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2151 } 2152 2153 #ifndef EMBEDDED 2154 void hci_emit_btstack_version() { 2155 log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 2156 uint8_t event[6]; 2157 event[0] = BTSTACK_EVENT_VERSION; 2158 event[1] = sizeof(event) - 2; 2159 event[2] = BTSTACK_MAJOR; 2160 event[3] = BTSTACK_MINOR; 2161 bt_store_16(event, 4, BTSTACK_REVISION); 2162 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2163 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2164 } 2165 #endif 2166 2167 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 2168 log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 2169 uint8_t event[3]; 2170 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 2171 event[1] = sizeof(event) - 2; 2172 event[2] = enabled; 2173 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2174 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2175 } 2176 2177 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){ 2178 uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info 2179 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 2180 event[1] = sizeof(event) - 2 - 1; 2181 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 2182 bt_flip_addr(&event[3], *addr); 2183 memcpy(&event[9], name, 248); 2184 2185 event[9+248] = 0; // assert \0 for log_info 2186 log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]); 2187 2188 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1); 2189 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1); 2190 } 2191 2192 void hci_emit_discoverable_enabled(uint8_t enabled){ 2193 log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled); 2194 uint8_t event[3]; 2195 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 2196 event[1] = sizeof(event) - 2; 2197 event[2] = enabled; 2198 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2199 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2200 } 2201 2202 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 2203 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 2204 uint8_t event[5]; 2205 int pos = 0; 2206 event[pos++] = GAP_SECURITY_LEVEL; 2207 event[pos++] = sizeof(event) - 2; 2208 bt_store_16(event, 2, con_handle); 2209 pos += 2; 2210 event[pos++] = level; 2211 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2212 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2213 } 2214 2215 void hci_emit_dedicated_bonding_result(hci_connection_t * connection, uint8_t status){ 2216 log_info("hci_emit_dedicated_bonding_result %u ", status); 2217 uint8_t event[9]; 2218 int pos = 0; 2219 event[pos++] = GAP_DEDICATED_BONDING_COMPLETED; 2220 event[pos++] = sizeof(event) - 2; 2221 event[pos++] = status; 2222 bt_flip_addr( * (bd_addr_t *) &event[pos], connection->address); 2223 pos += 6; 2224 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2225 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2226 } 2227 2228 // query if remote side supports SSP 2229 int hci_remote_ssp_supported(hci_con_handle_t con_handle){ 2230 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2231 if (!connection) return 0; 2232 return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0; 2233 } 2234 2235 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){ 2236 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 2237 } 2238 2239 // GAP API 2240 /** 2241 * @bbrief enable/disable bonding. default is enabled 2242 * @praram enabled 2243 */ 2244 void gap_set_bondable_mode(int enable){ 2245 hci_stack->bondable = enable ? 1 : 0; 2246 } 2247 2248 /** 2249 * @brief map link keys to security levels 2250 */ 2251 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 2252 switch (link_key_type){ 2253 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 2254 return LEVEL_4; 2255 case COMBINATION_KEY: 2256 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 2257 return LEVEL_3; 2258 default: 2259 return LEVEL_2; 2260 } 2261 } 2262 2263 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 2264 if (!connection) return LEVEL_0; 2265 if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 2266 return gap_security_level_for_link_key_type(connection->link_key_type); 2267 } 2268 2269 2270 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 2271 log_info("gap_mitm_protection_required_for_security_level %u", level); 2272 return level > LEVEL_2; 2273 } 2274 2275 /** 2276 * @brief get current security level 2277 */ 2278 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 2279 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2280 if (!connection) return LEVEL_0; 2281 return gap_security_level_for_connection(connection); 2282 } 2283 2284 /** 2285 * @brief request connection to device to 2286 * @result GAP_AUTHENTICATION_RESULT 2287 */ 2288 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 2289 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2290 if (!connection){ 2291 hci_emit_security_level(con_handle, LEVEL_0); 2292 return; 2293 } 2294 gap_security_level_t current_level = gap_security_level(con_handle); 2295 log_info("gap_request_security_level %u, current level %u", requested_level, current_level); 2296 if (current_level >= requested_level){ 2297 hci_emit_security_level(con_handle, current_level); 2298 return; 2299 } 2300 2301 connection->requested_security_level = requested_level; 2302 2303 // would enabling ecnryption suffice (>= LEVEL_2)? 2304 if (hci_stack->remote_device_db){ 2305 link_key_type_t link_key_type; 2306 link_key_t link_key; 2307 if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){ 2308 if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){ 2309 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 2310 return; 2311 } 2312 } 2313 } 2314 2315 // try to authenticate connection 2316 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2317 hci_run(); 2318 } 2319 2320 /** 2321 * @brief start dedicated bonding with device. disconnect after bonding 2322 * @param device 2323 * @param request MITM protection 2324 * @result GAP_DEDICATED_BONDING_COMPLETE 2325 */ 2326 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 2327 2328 // create connection state machine 2329 hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC); 2330 2331 if (!connection){ 2332 return BTSTACK_MEMORY_ALLOC_FAILED; 2333 } 2334 2335 // delete linkn key 2336 hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device); 2337 2338 // configure LEVEL_2/3, dedicated bonding 2339 connection->state = SEND_CREATE_CONNECTION; 2340 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 2341 log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level); 2342 connection->bonding_flags = BONDING_DEDICATED; 2343 2344 // wait for GAP Security Result and send GAP Dedicated Bonding complete 2345 2346 // handle: connnection failure (connection complete != ok) 2347 // handle: authentication failure 2348 // handle: disconnect on done 2349 2350 hci_run(); 2351 2352 return 0; 2353 } 2354 2355 void gap_set_local_name(const char * local_name){ 2356 hci_stack->local_name = local_name; 2357 } 2358 2359 le_command_status_t le_central_start_scan(){ 2360 if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK; 2361 hci_stack->le_scanning_state = LE_START_SCAN; 2362 hci_run(); 2363 return BLE_PERIPHERAL_OK; 2364 } 2365 2366 le_command_status_t le_central_stop_scan(){ 2367 if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK; 2368 hci_stack->le_scanning_state = LE_STOP_SCAN; 2369 hci_run(); 2370 return BLE_PERIPHERAL_OK; 2371 } 2372 2373 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){ 2374 hci_stack->le_scan_type = scan_type; 2375 hci_stack->le_scan_interval = scan_interval; 2376 hci_stack->le_scan_window = scan_window; 2377 hci_run(); 2378 } 2379 2380 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){ 2381 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 2382 if (!conn){ 2383 log_info("le_central_connect: no connection exists yet, creating context"); 2384 conn = create_connection_for_bd_addr_and_type(*addr, addr_type); 2385 if (!conn){ 2386 // notify client that alloc failed 2387 hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 2388 log_info("le_central_connect: failed to alloc context"); 2389 return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller 2390 } 2391 conn->state = SEND_CREATE_CONNECTION; 2392 log_info("le_central_connect: send create connection next"); 2393 hci_run(); 2394 return BLE_PERIPHERAL_OK; 2395 } 2396 2397 if (!hci_is_le_connection(conn) || 2398 conn->state == SEND_CREATE_CONNECTION || 2399 conn->state == SENT_CREATE_CONNECTION) { 2400 hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED); 2401 log_error("le_central_connect: classic connection or connect is already being created"); 2402 return BLE_PERIPHERAL_IN_WRONG_STATE; 2403 } 2404 2405 log_info("le_central_connect: context exists with state %u", conn->state); 2406 hci_emit_le_connection_complete(conn, 0); 2407 hci_run(); 2408 return BLE_PERIPHERAL_OK; 2409 } 2410 2411 // @assumption: only a single outgoing LE Connection exists 2412 static hci_connection_t * le_central_get_outgoing_connection(){ 2413 linked_item_t *it; 2414 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 2415 hci_connection_t * conn = (hci_connection_t *) it; 2416 if (!hci_is_le_connection(conn)) continue; 2417 switch (conn->state){ 2418 case SEND_CREATE_CONNECTION: 2419 case SENT_CREATE_CONNECTION: 2420 return conn; 2421 default: 2422 break; 2423 }; 2424 } 2425 return NULL; 2426 } 2427 2428 le_command_status_t le_central_connect_cancel(){ 2429 hci_connection_t * conn = le_central_get_outgoing_connection(); 2430 switch (conn->state){ 2431 case SEND_CREATE_CONNECTION: 2432 // skip sending create connection and emit event instead 2433 hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER); 2434 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 2435 btstack_memory_hci_connection_free( conn ); 2436 break; 2437 case SENT_CREATE_CONNECTION: 2438 // request to send cancel connection 2439 conn->state = SEND_CANCEL_CONNECTION; 2440 hci_run(); 2441 break; 2442 default: 2443 break; 2444 } 2445 return BLE_PERIPHERAL_OK; 2446 } 2447 2448 le_command_status_t gap_disconnect(hci_con_handle_t handle){ 2449 hci_connection_t * conn = hci_connection_for_handle(handle); 2450 if (!conn){ 2451 hci_emit_disconnection_complete(handle, 0); 2452 return BLE_PERIPHERAL_OK; 2453 } 2454 conn->state = SEND_DISCONNECT; 2455 hci_run(); 2456 return BLE_PERIPHERAL_OK; 2457 } 2458 2459 void hci_disconnect_all(){ 2460 linked_list_iterator_t it; 2461 linked_list_iterator_init(&it, &hci_stack->connections); 2462 while (linked_list_iterator_has_next(&it)){ 2463 hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it); 2464 if (con->state == SENT_DISCONNECT) continue; 2465 con->state = SEND_DISCONNECT; 2466 } 2467 hci_run(); 2468 } 2469