1 /* 2 * Copyright (C) 2014 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 24 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 /* 39 * hci.c 40 * 41 * Created by Matthias Ringwald on 4/29/09. 42 * 43 */ 44 45 #include "btstack-config.h" 46 47 #include "hci.h" 48 #include "gap.h" 49 50 #ifdef HAVE_BLE 51 #include "gap_le.h" 52 #endif 53 54 #include <stdarg.h> 55 #include <string.h> 56 #include <stdio.h> 57 #include <inttypes.h> 58 59 #ifndef EMBEDDED 60 #ifdef _WIN32 61 #include "Winsock2.h" 62 #else 63 #include <unistd.h> // gethostbyname 64 #endif 65 #include <btstack/version.h> 66 #endif 67 68 #include "btstack_memory.h" 69 #include "debug.h" 70 #include "hci_dump.h" 71 72 #include <btstack/linked_list.h> 73 #include <btstack/hci_cmds.h> 74 75 #define HCI_CONNECTION_TIMEOUT_MS 10000 76 77 #ifdef USE_BLUETOOL 78 #include "../platforms/ios/src/bt_control_iphone.h" 79 #endif 80 81 static void hci_update_scan_enable(void); 82 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection); 83 static void hci_connection_timeout_handler(timer_source_t *timer); 84 static void hci_connection_timestamp(hci_connection_t *connection); 85 static int hci_power_control_on(void); 86 static void hci_power_control_off(void); 87 static void hci_state_reset(void); 88 89 #ifdef HAVE_BLE 90 // called from test/ble_client/advertising_data_parser.c 91 void le_handle_advertisement_report(uint8_t *packet, int size); 92 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address); 93 #endif 94 95 // the STACK is here 96 #ifndef HAVE_MALLOC 97 static hci_stack_t hci_stack_static; 98 #endif 99 static hci_stack_t * hci_stack = NULL; 100 101 // test helper 102 static uint8_t disable_l2cap_timeouts = 0; 103 104 /** 105 * create connection for given address 106 * 107 * @return connection OR NULL, if no memory left 108 */ 109 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){ 110 log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type); 111 hci_connection_t * conn = btstack_memory_hci_connection_get(); 112 if (!conn) return NULL; 113 memset(conn, 0, sizeof(hci_connection_t)); 114 BD_ADDR_COPY(conn->address, addr); 115 conn->address_type = addr_type; 116 conn->con_handle = 0xffff; 117 conn->authentication_flags = AUTH_FLAGS_NONE; 118 conn->bonding_flags = 0; 119 conn->requested_security_level = LEVEL_0; 120 linked_item_set_user(&conn->timeout.item, conn); 121 conn->timeout.process = hci_connection_timeout_handler; 122 hci_connection_timestamp(conn); 123 conn->acl_recombination_length = 0; 124 conn->acl_recombination_pos = 0; 125 conn->num_acl_packets_sent = 0; 126 conn->num_sco_packets_sent = 0; 127 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 128 linked_list_add(&hci_stack->connections, (linked_item_t *) conn); 129 return conn; 130 } 131 132 133 /** 134 * get le connection parameter range 135 * 136 * @return le connection parameter range struct 137 */ 138 void gap_le_get_connection_parameter_range(le_connection_parameter_range_t range){ 139 range = hci_stack->le_connection_parameter_range; 140 } 141 142 /** 143 * set le connection parameter range 144 * 145 */ 146 147 void gap_le_set_connection_parameter_range(le_connection_parameter_range_t range){ 148 hci_stack->le_connection_parameter_range = range; 149 } 150 151 /** 152 * get hci connections iterator 153 * 154 * @return hci connections iterator 155 */ 156 157 void hci_connections_get_iterator(linked_list_iterator_t *it){ 158 linked_list_iterator_init(it, &hci_stack->connections); 159 } 160 161 /** 162 * get connection for a given handle 163 * 164 * @return connection OR NULL, if not found 165 */ 166 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){ 167 linked_list_iterator_t it; 168 linked_list_iterator_init(&it, &hci_stack->connections); 169 while (linked_list_iterator_has_next(&it)){ 170 hci_connection_t * item = (hci_connection_t *) linked_list_iterator_next(&it); 171 if ( item->con_handle == con_handle ) { 172 return item; 173 } 174 } 175 return NULL; 176 } 177 178 /** 179 * get connection for given address 180 * 181 * @return connection OR NULL, if not found 182 */ 183 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){ 184 linked_list_iterator_t it; 185 linked_list_iterator_init(&it, &hci_stack->connections); 186 while (linked_list_iterator_has_next(&it)){ 187 hci_connection_t * connection = (hci_connection_t *) linked_list_iterator_next(&it); 188 if (connection->address_type != addr_type) continue; 189 if (memcmp(addr, connection->address, 6) != 0) continue; 190 return connection; 191 } 192 return NULL; 193 } 194 195 static void hci_connection_timeout_handler(timer_source_t *timer){ 196 hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item); 197 #ifdef HAVE_TIME 198 struct timeval tv; 199 gettimeofday(&tv, NULL); 200 if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) { 201 // connections might be timed out 202 hci_emit_l2cap_check_timeout(connection); 203 } 204 #endif 205 #ifdef HAVE_TICK 206 if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 207 // connections might be timed out 208 hci_emit_l2cap_check_timeout(connection); 209 } 210 #endif 211 run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS); 212 run_loop_add_timer(timer); 213 } 214 215 static void hci_connection_timestamp(hci_connection_t *connection){ 216 #ifdef HAVE_TIME 217 gettimeofday(&connection->timestamp, NULL); 218 #endif 219 #ifdef HAVE_TICK 220 connection->timestamp = embedded_get_ticks(); 221 #endif 222 } 223 224 225 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 226 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags); 227 } 228 229 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 230 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags); 231 } 232 233 234 /** 235 * add authentication flags and reset timer 236 * @note: assumes classic connection 237 * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets 238 */ 239 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 240 bd_addr_t addr; 241 bt_flip_addr(addr, bd_addr); 242 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 243 if (conn) { 244 connectionSetAuthenticationFlags(conn, flags); 245 hci_connection_timestamp(conn); 246 } 247 } 248 249 int hci_authentication_active_for_handle(hci_con_handle_t handle){ 250 hci_connection_t * conn = hci_connection_for_handle(handle); 251 if (!conn) return 0; 252 if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1; 253 if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1; 254 return 0; 255 } 256 257 void hci_drop_link_key_for_bd_addr(bd_addr_t addr){ 258 if (hci_stack->remote_device_db) { 259 hci_stack->remote_device_db->delete_link_key(addr); 260 } 261 } 262 263 int hci_is_le_connection(hci_connection_t * connection){ 264 return connection->address_type == BD_ADDR_TYPE_LE_PUBLIC || 265 connection->address_type == BD_ADDR_TYPE_LE_RANDOM; 266 } 267 268 269 /** 270 * count connections 271 */ 272 static int nr_hci_connections(void){ 273 int count = 0; 274 linked_item_t *it; 275 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++); 276 return count; 277 } 278 279 /** 280 * Dummy handler called by HCI 281 */ 282 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 283 } 284 285 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){ 286 hci_connection_t * connection = hci_connection_for_handle(handle); 287 if (!connection) { 288 log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle); 289 return 0; 290 } 291 return connection->num_acl_packets_sent; 292 } 293 294 uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){ 295 296 int num_packets_sent_classic = 0; 297 int num_packets_sent_le = 0; 298 299 bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN; 300 301 linked_item_t *it; 302 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 303 hci_connection_t * connection = (hci_connection_t *) it; 304 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){ 305 num_packets_sent_classic += connection->num_acl_packets_sent; 306 } else { 307 num_packets_sent_le += connection->num_acl_packets_sent; 308 } 309 // ignore connections that are not open, e.g., in state RECEIVED_DISCONNECTION_COMPLETE 310 if (connection->con_handle == con_handle && connection->state == OPEN){ 311 address_type = connection->address_type; 312 } 313 } 314 315 int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic; 316 int free_slots_le = 0; 317 318 if (free_slots_classic < 0){ 319 log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num); 320 return 0; 321 } 322 323 if (hci_stack->le_acl_packets_total_num){ 324 // if we have LE slots, they are used 325 free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le; 326 if (free_slots_le < 0){ 327 log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num); 328 return 0; 329 } 330 } else { 331 // otherwise, classic slots are used for LE, too 332 free_slots_classic -= num_packets_sent_le; 333 if (free_slots_classic < 0){ 334 log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num); 335 return 0; 336 } 337 } 338 339 switch (address_type){ 340 case BD_ADDR_TYPE_UNKNOWN: 341 log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle); 342 return 0; 343 344 case BD_ADDR_TYPE_CLASSIC: 345 return free_slots_classic; 346 347 default: 348 if (hci_stack->le_acl_packets_total_num){ 349 return free_slots_le; 350 } 351 return free_slots_classic; 352 } 353 } 354 355 static int hci_number_free_sco_slots_for_handle(hci_con_handle_t handle){ 356 int num_sco_packets_sent = 0; 357 linked_item_t *it; 358 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 359 hci_connection_t * connection = (hci_connection_t *) it; 360 num_sco_packets_sent += connection->num_sco_packets_sent; 361 } 362 if (num_sco_packets_sent > hci_stack->sco_packets_total_num){ 363 log_info("hci_number_free_sco_slots_for_handle: outgoing packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num); 364 return 0; 365 } 366 return hci_stack->sco_packets_total_num - num_sco_packets_sent; 367 } 368 369 // new functions replacing hci_can_send_packet_now[_using_packet_buffer] 370 int hci_can_send_command_packet_now(void){ 371 if (hci_stack->hci_packet_buffer_reserved) return 0; 372 373 // check for async hci transport implementations 374 if (hci_stack->hci_transport->can_send_packet_now){ 375 if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){ 376 return 0; 377 } 378 } 379 380 return hci_stack->num_cmd_packets > 0; 381 } 382 383 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) { 384 // check for async hci transport implementations 385 if (hci_stack->hci_transport->can_send_packet_now){ 386 if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){ 387 return 0; 388 } 389 } 390 return hci_number_free_acl_slots_for_handle(con_handle) > 0; 391 } 392 393 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){ 394 if (hci_stack->hci_packet_buffer_reserved) return 0; 395 return hci_can_send_prepared_acl_packet_now(con_handle); 396 } 397 398 int hci_can_send_prepared_sco_packet_now(hci_con_handle_t con_handle){ 399 if (hci_stack->hci_transport->can_send_packet_now){ 400 if (!hci_stack->hci_transport->can_send_packet_now(HCI_SCO_DATA_PACKET)){ 401 return 0; 402 } 403 } 404 return hci_number_free_sco_slots_for_handle(con_handle) > 0; 405 } 406 407 int hci_can_send_sco_packet_now(hci_con_handle_t con_handle){ 408 if (hci_stack->hci_packet_buffer_reserved) return 0; 409 return hci_can_send_prepared_sco_packet_now(con_handle); 410 } 411 412 // used for internal checks in l2cap[-le].c 413 int hci_is_packet_buffer_reserved(void){ 414 return hci_stack->hci_packet_buffer_reserved; 415 } 416 417 // reserves outgoing packet buffer. @returns 1 if successful 418 int hci_reserve_packet_buffer(void){ 419 if (hci_stack->hci_packet_buffer_reserved) { 420 log_error("hci_reserve_packet_buffer called but buffer already reserved"); 421 return 0; 422 } 423 hci_stack->hci_packet_buffer_reserved = 1; 424 return 1; 425 } 426 427 void hci_release_packet_buffer(void){ 428 hci_stack->hci_packet_buffer_reserved = 0; 429 } 430 431 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call 432 static int hci_transport_synchronous(void){ 433 return hci_stack->hci_transport->can_send_packet_now == NULL; 434 } 435 436 uint16_t hci_max_acl_le_data_packet_length(void){ 437 return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length; 438 } 439 440 static int hci_send_acl_packet_fragments(hci_connection_t *connection){ 441 442 // log_info("hci_send_acl_packet_fragments %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle); 443 444 // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers 445 uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length; 446 if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){ 447 max_acl_data_packet_length = hci_stack->le_data_packets_length; 448 } 449 450 // testing: reduce buffer to minimum 451 // max_acl_data_packet_length = 52; 452 453 int err; 454 // multiple packets could be send on a synchronous HCI transport 455 while (1){ 456 457 // get current data 458 const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4; 459 int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos; 460 int more_fragments = 0; 461 462 // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length 463 if (current_acl_data_packet_length > max_acl_data_packet_length){ 464 more_fragments = 1; 465 current_acl_data_packet_length = max_acl_data_packet_length; 466 } 467 468 // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent) 469 if (acl_header_pos > 0){ 470 uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0); 471 handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12); 472 bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags); 473 } 474 475 // update header len 476 bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length); 477 478 // count packet 479 connection->num_acl_packets_sent++; 480 481 // send packet 482 uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos]; 483 const int size = current_acl_data_packet_length + 4; 484 hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size); 485 err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 486 487 // done yet? 488 if (!more_fragments) break; 489 490 // update start of next fragment to send 491 hci_stack->acl_fragmentation_pos += current_acl_data_packet_length; 492 493 // can send more? 494 if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err; 495 } 496 497 // done 498 hci_stack->acl_fragmentation_pos = 0; 499 hci_stack->acl_fragmentation_total_size = 0; 500 501 // release buffer now for synchronous transport 502 if (hci_transport_synchronous()){ 503 hci_release_packet_buffer(); 504 // notify upper stack that iit might be possible to send again 505 uint8_t event[] = { DAEMON_EVENT_HCI_PACKET_SENT, 0}; 506 hci_stack->packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event)); 507 } 508 509 return err; 510 } 511 512 // pre: caller has reserved the packet buffer 513 int hci_send_acl_packet_buffer(int size){ 514 515 // log_info("hci_send_acl_packet_buffer size %u", size); 516 517 if (!hci_stack->hci_packet_buffer_reserved) { 518 log_error("hci_send_acl_packet_buffer called without reserving packet buffer"); 519 return 0; 520 } 521 522 uint8_t * packet = hci_stack->hci_packet_buffer; 523 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 524 525 // check for free places on Bluetooth module 526 if (!hci_can_send_prepared_acl_packet_now(con_handle)) { 527 log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller"); 528 hci_release_packet_buffer(); 529 return BTSTACK_ACL_BUFFERS_FULL; 530 } 531 532 hci_connection_t *connection = hci_connection_for_handle( con_handle); 533 if (!connection) { 534 log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle); 535 hci_release_packet_buffer(); 536 return 0; 537 } 538 hci_connection_timestamp(connection); 539 540 // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size); 541 542 // setup data 543 hci_stack->acl_fragmentation_total_size = size; 544 hci_stack->acl_fragmentation_pos = 4; // start of L2CAP packet 545 546 return hci_send_acl_packet_fragments(connection); 547 } 548 549 // pre: caller has reserved the packet buffer 550 int hci_send_sco_packet_buffer(int size){ 551 552 // log_info("hci_send_acl_packet_buffer size %u", size); 553 554 if (!hci_stack->hci_packet_buffer_reserved) { 555 log_error("hci_send_acl_packet_buffer called without reserving packet buffer"); 556 return 0; 557 } 558 559 uint8_t * packet = hci_stack->hci_packet_buffer; 560 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); // same for ACL and SCO 561 562 // check for free places on Bluetooth module 563 if (!hci_can_send_prepared_sco_packet_now(con_handle)) { 564 log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller"); 565 hci_release_packet_buffer(); 566 return BTSTACK_ACL_BUFFERS_FULL; 567 } 568 569 // track send packet in connection struct 570 hci_connection_t *connection = hci_connection_for_handle( con_handle); 571 if (!connection) { 572 log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle); 573 hci_release_packet_buffer(); 574 return 0; 575 } 576 connection->num_sco_packets_sent++; 577 578 hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size); 579 return hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size); 580 } 581 582 static void acl_handler(uint8_t *packet, int size){ 583 584 // log_info("acl_handler: size %u", size); 585 586 // get info 587 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 588 hci_connection_t *conn = hci_connection_for_handle(con_handle); 589 uint8_t acl_flags = READ_ACL_FLAGS(packet); 590 uint16_t acl_length = READ_ACL_LENGTH(packet); 591 592 // ignore non-registered handle 593 if (!conn){ 594 log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle); 595 return; 596 } 597 598 // assert packet is complete 599 if (acl_length + 4 != size){ 600 log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4); 601 return; 602 } 603 604 // update idle timestamp 605 hci_connection_timestamp(conn); 606 607 // handle different packet types 608 switch (acl_flags & 0x03) { 609 610 case 0x01: // continuation fragment 611 612 // sanity checks 613 if (conn->acl_recombination_pos == 0) { 614 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle); 615 return; 616 } 617 if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){ 618 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x", 619 conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle); 620 conn->acl_recombination_pos = 0; 621 return; 622 } 623 624 // append fragment payload (header already stored) 625 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length ); 626 conn->acl_recombination_pos += acl_length; 627 628 // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length, 629 // conn->acl_recombination_pos, conn->acl_recombination_length); 630 631 // forward complete L2CAP packet if complete. 632 if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header 633 634 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, &conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos); 635 // reset recombination buffer 636 conn->acl_recombination_length = 0; 637 conn->acl_recombination_pos = 0; 638 } 639 break; 640 641 case 0x02: { // first fragment 642 643 // sanity check 644 if (conn->acl_recombination_pos) { 645 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle); 646 conn->acl_recombination_pos = 0; 647 } 648 649 // peek into L2CAP packet! 650 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 651 652 // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length); 653 654 // compare fragment size to L2CAP packet size 655 if (acl_length >= l2cap_length + 4){ 656 657 // forward fragment as L2CAP packet 658 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4); 659 660 } else { 661 662 if (acl_length > HCI_ACL_BUFFER_SIZE){ 663 log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x", 664 4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle); 665 return; 666 } 667 668 // store first fragment and tweak acl length for complete package 669 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4); 670 conn->acl_recombination_pos = acl_length + 4; 671 conn->acl_recombination_length = l2cap_length; 672 bt_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4); 673 } 674 break; 675 676 } 677 default: 678 log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03); 679 return; 680 } 681 682 // execute main loop 683 hci_run(); 684 } 685 686 static void hci_shutdown_connection(hci_connection_t *conn){ 687 log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address)); 688 689 run_loop_remove_timer(&conn->timeout); 690 691 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 692 btstack_memory_hci_connection_free( conn ); 693 694 // now it's gone 695 hci_emit_nr_connections_changed(); 696 } 697 698 static const uint16_t packet_type_sizes[] = { 699 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 700 HCI_ACL_DH1_SIZE, 0, 0, 0, 701 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 702 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 703 }; 704 static const uint8_t packet_type_feature_requirement_bit[] = { 705 0, // 3 slot packets 706 1, // 5 slot packets 707 25, // EDR 2 mpbs 708 26, // EDR 3 mbps 709 39, // 3 slot EDR packts 710 40, // 5 slot EDR packet 711 }; 712 static const uint16_t packet_type_feature_packet_mask[] = { 713 0x0f00, // 3 slot packets 714 0xf000, // 5 slot packets 715 0x1102, // EDR 2 mpbs 716 0x2204, // EDR 3 mbps 717 0x0300, // 3 slot EDR packts 718 0x3000, // 5 slot EDR packet 719 }; 720 721 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){ 722 // enable packet types based on size 723 uint16_t packet_types = 0; 724 unsigned int i; 725 for (i=0;i<16;i++){ 726 if (packet_type_sizes[i] == 0) continue; 727 if (packet_type_sizes[i] <= buffer_size){ 728 packet_types |= 1 << i; 729 } 730 } 731 // disable packet types due to missing local supported features 732 for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){ 733 int bit_idx = packet_type_feature_requirement_bit[i]; 734 int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0; 735 if (feature_set) continue; 736 log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]); 737 packet_types &= ~packet_type_feature_packet_mask[i]; 738 } 739 // flip bits for "may not be used" 740 packet_types ^= 0x3306; 741 return packet_types; 742 } 743 744 uint16_t hci_usable_acl_packet_types(void){ 745 return hci_stack->packet_types; 746 } 747 748 uint8_t* hci_get_outgoing_packet_buffer(void){ 749 // hci packet buffer is >= acl data packet length 750 return hci_stack->hci_packet_buffer; 751 } 752 753 uint16_t hci_max_acl_data_packet_length(void){ 754 return hci_stack->acl_data_packet_length; 755 } 756 757 int hci_non_flushable_packet_boundary_flag_supported(void){ 758 // No. 54, byte 6, bit 6 759 return (hci_stack->local_supported_features[6] & (1 << 6)) != 0; 760 } 761 762 static int hci_ssp_supported(void){ 763 // No. 51, byte 6, bit 3 764 return (hci_stack->local_supported_features[6] & (1 << 3)) != 0; 765 } 766 767 static int hci_classic_supported(void){ 768 // No. 37, byte 4, bit 5, = No BR/EDR Support 769 return (hci_stack->local_supported_features[4] & (1 << 5)) == 0; 770 } 771 772 static int hci_le_supported(void){ 773 #ifdef HAVE_BLE 774 // No. 37, byte 4, bit 6 = LE Supported (Controller) 775 return (hci_stack->local_supported_features[4] & (1 << 6)) != 0; 776 #else 777 return 0; 778 #endif 779 } 780 781 // get addr type and address used in advertisement packets 782 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t addr){ 783 *addr_type = hci_stack->adv_addr_type; 784 if (hci_stack->adv_addr_type){ 785 memcpy(addr, hci_stack->adv_address, 6); 786 } else { 787 memcpy(addr, hci_stack->local_bd_addr, 6); 788 } 789 } 790 791 #ifdef HAVE_BLE 792 void le_handle_advertisement_report(uint8_t *packet, int size){ 793 int offset = 3; 794 int num_reports = packet[offset]; 795 offset += 1; 796 797 int i; 798 log_info("HCI: handle adv report with num reports: %d", num_reports); 799 uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var 800 for (i=0; i<num_reports;i++){ 801 uint8_t data_length = packet[offset + 8]; 802 uint8_t event_size = 10 + data_length; 803 int pos = 0; 804 event[pos++] = GAP_LE_ADVERTISING_REPORT; 805 event[pos++] = event_size; 806 memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address 807 offset += 8; 808 pos += 8; 809 event[pos++] = packet[offset + 1 + data_length]; // rssi 810 event[pos++] = packet[offset++]; //data_length; 811 memcpy(&event[pos], &packet[offset], data_length); 812 pos += data_length; 813 offset += data_length + 1; // rssi 814 hci_dump_packet( HCI_EVENT_PACKET, 0, event, pos); 815 hci_stack->packet_handler(HCI_EVENT_PACKET, event, pos); 816 } 817 } 818 #endif 819 820 static void hci_initialization_timeout_handler(timer_source_t * ds){ 821 switch (hci_stack->substate){ 822 case HCI_INIT_W4_SEND_RESET: 823 log_info("Resend HCI Reset"); 824 hci_stack->substate = HCI_INIT_SEND_RESET; 825 hci_stack->num_cmd_packets = 1; 826 hci_run(); 827 break; 828 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT: 829 log_info("Resend HCI Reset - CSR Warm Boot"); 830 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT; 831 hci_stack->num_cmd_packets = 1; 832 hci_run(); 833 case HCI_INIT_W4_SEND_BAUD_CHANGE: 834 log_info("Local baud rate change to %"PRIu32, ((hci_uart_config_t *)hci_stack->config)->baudrate_main); 835 hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main); 836 break; 837 default: 838 break; 839 } 840 } 841 842 static void hci_initializing_next_state(void){ 843 hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1); 844 } 845 846 // assumption: hci_can_send_command_packet_now() == true 847 static void hci_initializing_run(void){ 848 log_info("hci_initializing_run: substate %u", hci_stack->substate); 849 switch (hci_stack->substate){ 850 case HCI_INIT_SEND_RESET: 851 hci_state_reset(); 852 853 #ifndef USE_BLUETOOL 854 // prepare reset if command complete not received in 100ms 855 run_loop_set_timer(&hci_stack->timeout, 100); 856 run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 857 run_loop_add_timer(&hci_stack->timeout); 858 #endif 859 // send command 860 hci_stack->substate = HCI_INIT_W4_SEND_RESET; 861 hci_send_cmd(&hci_reset); 862 break; 863 case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION: 864 hci_send_cmd(&hci_read_local_version_information); 865 hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION; 866 break; 867 case HCI_INIT_SEND_RESET_CSR_WARM_BOOT: 868 hci_state_reset(); 869 // prepare reset if command complete not received in 100ms 870 run_loop_set_timer(&hci_stack->timeout, 100); 871 run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 872 run_loop_add_timer(&hci_stack->timeout); 873 // send command 874 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT; 875 hci_send_cmd(&hci_reset); 876 break; 877 case HCI_INIT_SEND_RESET_ST_WARM_BOOT: 878 hci_state_reset(); 879 hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT; 880 hci_send_cmd(&hci_reset); 881 break; 882 case HCI_INIT_SET_BD_ADDR: 883 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr)); 884 hci_stack->control->set_bd_addr_cmd(hci_stack->config, hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer); 885 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0); 886 hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR; 887 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]); 888 break; 889 case HCI_INIT_SEND_BAUD_CHANGE: 890 hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer); 891 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0); 892 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE; 893 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]); 894 // STLC25000D: baudrate change happens within 0.5 s after command was send, 895 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial) 896 if (hci_stack->manufacturer == 0x0030){ 897 run_loop_set_timer(&hci_stack->timeout, 100); 898 run_loop_add_timer(&hci_stack->timeout); 899 } 900 break; 901 case HCI_INIT_CUSTOM_INIT: 902 log_info("Custom init"); 903 // Custom initialization 904 if (hci_stack->control && hci_stack->control->next_cmd){ 905 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer); 906 if (valid_cmd){ 907 int size = 3 + hci_stack->hci_packet_buffer[2]; 908 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0); 909 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size); 910 switch (valid_cmd) { 911 case 1: 912 default: 913 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT; 914 break; 915 case 2: // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete 916 log_info("CSR Warm Boot"); 917 run_loop_set_timer(&hci_stack->timeout, 100); 918 run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 919 run_loop_add_timer(&hci_stack->timeout); 920 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT; 921 break; 922 } 923 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size); 924 break; 925 } 926 log_info("hci_run: init script done"); 927 } 928 // otherwise continue 929 hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR; 930 hci_send_cmd(&hci_read_bd_addr); 931 break; 932 case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS: 933 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS; 934 hci_send_cmd(&hci_read_local_supported_commands); 935 break; 936 case HCI_INIT_READ_BUFFER_SIZE: 937 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE; 938 hci_send_cmd(&hci_read_buffer_size); 939 break; 940 case HCI_INIT_READ_LOCAL_SUPPORTED_FEATUES: 941 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATUES; 942 hci_send_cmd(&hci_read_local_supported_features); 943 break; 944 case HCI_INIT_SET_EVENT_MASK: 945 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK; 946 if (hci_le_supported()){ 947 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF); 948 } else { 949 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 950 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF); 951 } 952 break; 953 case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE: 954 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE; 955 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable); 956 break; 957 case HCI_INIT_WRITE_PAGE_TIMEOUT: 958 hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT; 959 hci_send_cmd(&hci_write_page_timeout, 0x6000); // ca. 15 sec 960 break; 961 case HCI_INIT_WRITE_CLASS_OF_DEVICE: 962 hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE; 963 hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device); 964 break; 965 case HCI_INIT_WRITE_LOCAL_NAME: 966 hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME; 967 if (hci_stack->local_name){ 968 hci_send_cmd(&hci_write_local_name, hci_stack->local_name); 969 } else { 970 char hostname[30]; 971 #ifdef EMBEDDED 972 // BTstack-11:22:33:44:55:66 973 strcpy(hostname, "BTstack "); 974 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr)); 975 log_info("---> Name %s", hostname); 976 #else 977 // hostname for POSIX systems 978 gethostname(hostname, 30); 979 hostname[29] = '\0'; 980 #endif 981 hci_send_cmd(&hci_write_local_name, hostname); 982 } 983 break; 984 case HCI_INIT_WRITE_SCAN_ENABLE: 985 hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan 986 hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE; 987 break; 988 #ifdef HAVE_BLE 989 // LE INIT 990 case HCI_INIT_LE_READ_BUFFER_SIZE: 991 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE; 992 hci_send_cmd(&hci_le_read_buffer_size); 993 break; 994 case HCI_INIT_WRITE_LE_HOST_SUPPORTED: 995 // LE Supported Host = 1, Simultaneous Host = 0 996 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED; 997 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 998 break; 999 case HCI_INIT_READ_WHITE_LIST_SIZE: 1000 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE; 1001 hci_send_cmd(&hci_le_read_white_list_size); 1002 break; 1003 case HCI_INIT_LE_SET_SCAN_PARAMETERS: 1004 // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs 1005 hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS; 1006 hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0); 1007 break; 1008 #endif 1009 // DONE 1010 case HCI_INIT_DONE: 1011 // done. 1012 hci_stack->state = HCI_STATE_WORKING; 1013 hci_emit_state(); 1014 return; 1015 default: 1016 return; 1017 } 1018 } 1019 1020 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){ 1021 uint8_t command_completed = 0; 1022 1023 if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){ 1024 uint16_t opcode = READ_BT_16(packet,3); 1025 if (opcode == hci_stack->last_cmd_opcode){ 1026 command_completed = 1; 1027 log_info("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate); 1028 } else { 1029 log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 1030 } 1031 } 1032 if (packet[0] == HCI_EVENT_COMMAND_STATUS){ 1033 uint8_t status = packet[2]; 1034 uint16_t opcode = READ_BT_16(packet,4); 1035 if (opcode == hci_stack->last_cmd_opcode){ 1036 if (status){ 1037 command_completed = 1; 1038 log_error("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate); 1039 } else { 1040 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode); 1041 } 1042 } else { 1043 log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 1044 } 1045 } 1046 // Vendor == CSR 1047 if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && packet[0] == HCI_EVENT_VENDOR_SPECIFIC){ 1048 // TODO: track actual command 1049 command_completed = 1; 1050 } 1051 1052 if (!command_completed) return; 1053 1054 int need_baud_change = hci_stack->config 1055 && hci_stack->control 1056 && hci_stack->control->baudrate_cmd 1057 && hci_stack->hci_transport->set_baudrate 1058 && ((hci_uart_config_t *)hci_stack->config)->baudrate_main; 1059 1060 int need_addr_change = hci_stack->custom_bd_addr_set 1061 && hci_stack->control 1062 && hci_stack->control->set_bd_addr_cmd; 1063 1064 switch(hci_stack->substate){ 1065 case HCI_INIT_W4_SEND_RESET: 1066 run_loop_remove_timer(&hci_stack->timeout); 1067 break; 1068 case HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION: 1069 if (need_addr_change){ 1070 hci_stack->substate = HCI_INIT_SET_BD_ADDR; 1071 return; 1072 } 1073 // skipping addr change 1074 if (need_baud_change){ 1075 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE; 1076 return; 1077 } 1078 // also skip baud change 1079 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1080 return; 1081 case HCI_INIT_W4_SET_BD_ADDR: 1082 // for STLC2500D, bd addr change only gets active after sending reset command 1083 if (hci_stack->manufacturer == 0x0030){ 1084 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT; 1085 return; 1086 } 1087 // skipping warm boot on STLC2500D 1088 if (need_baud_change){ 1089 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE; 1090 return; 1091 } 1092 // skipping baud change 1093 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1094 return; 1095 case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT: 1096 if (need_baud_change){ 1097 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE; 1098 return; 1099 } 1100 // skipping baud change 1101 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1102 return; 1103 case HCI_INIT_W4_SEND_BAUD_CHANGE: 1104 // for STLC2500D, baud rate change already happened. 1105 // for CC256x, baud rate gets changed now 1106 if (hci_stack->manufacturer != 0x0030){ 1107 uint32_t new_baud = ((hci_uart_config_t *)hci_stack->config)->baudrate_main; 1108 log_info("Local baud rate change to %"PRIu32, new_baud); 1109 hci_stack->hci_transport->set_baudrate(new_baud); 1110 } 1111 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1112 return; 1113 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT: 1114 run_loop_remove_timer(&hci_stack->timeout); 1115 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1116 return; 1117 case HCI_INIT_W4_CUSTOM_INIT: 1118 // repeat custom init 1119 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1120 return; 1121 case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS: 1122 // skip read buffer size if not supported 1123 if (hci_stack->local_supported_commands[0] & 0x01) break; 1124 hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATUES; 1125 return; 1126 case HCI_INIT_W4_SET_EVENT_MASK: 1127 // skip Classic init commands for LE only chipsets 1128 if (!hci_classic_supported()){ 1129 if (hci_le_supported()){ 1130 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command 1131 return; 1132 } else { 1133 log_error("Neither BR/EDR nor LE supported"); 1134 hci_stack->substate = HCI_INIT_DONE; // skip all 1135 return; 1136 } 1137 } 1138 if (!hci_ssp_supported()){ 1139 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT; 1140 return; 1141 } 1142 break; 1143 case HCI_INIT_W4_LE_READ_BUFFER_SIZE: 1144 // skip write le host if not supported (e.g. on LE only EM9301) 1145 if (hci_stack->local_supported_commands[0] & 0x02) break; 1146 hci_stack->substate = HCI_INIT_LE_SET_SCAN_PARAMETERS; 1147 return; 1148 case HCI_INIT_W4_WRITE_SCAN_ENABLE: 1149 if (!hci_le_supported()){ 1150 // SKIP LE init for Classic only configuration 1151 hci_stack->substate = HCI_INIT_DONE; 1152 return; 1153 } 1154 default: 1155 break; 1156 } 1157 hci_initializing_next_state(); 1158 } 1159 1160 1161 // avoid huge local variables 1162 #ifndef EMBEDDED 1163 static device_name_t device_name; 1164 #endif 1165 static void event_handler(uint8_t *packet, int size){ 1166 1167 uint16_t event_length = packet[1]; 1168 1169 // assert packet is complete 1170 if (size != event_length + 2){ 1171 log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2); 1172 return; 1173 } 1174 1175 bd_addr_t addr; 1176 bd_addr_type_t addr_type; 1177 uint8_t link_type; 1178 hci_con_handle_t handle; 1179 hci_connection_t * conn; 1180 int i; 1181 1182 // log_info("HCI:EVENT:%02x", packet[0]); 1183 1184 switch (packet[0]) { 1185 1186 case HCI_EVENT_COMMAND_COMPLETE: 1187 // get num cmd packets 1188 // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]); 1189 hci_stack->num_cmd_packets = packet[2]; 1190 1191 if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){ 1192 // from offset 5 1193 // status 1194 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 1195 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6); 1196 hci_stack->sco_data_packet_length = packet[8]; 1197 hci_stack->acl_packets_total_num = READ_BT_16(packet, 9); 1198 hci_stack->sco_packets_total_num = READ_BT_16(packet, 11); 1199 1200 if (hci_stack->state == HCI_STATE_INITIALIZING){ 1201 // determine usable ACL payload size 1202 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){ 1203 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 1204 } 1205 log_info("hci_read_buffer_size: acl used size %u, count %u / sco size %u, count %u", 1206 hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num, 1207 hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num); 1208 } 1209 } 1210 #ifdef HAVE_BLE 1211 if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){ 1212 hci_stack->le_data_packets_length = READ_BT_16(packet, 6); 1213 hci_stack->le_acl_packets_total_num = packet[8]; 1214 // determine usable ACL payload size 1215 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){ 1216 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE; 1217 } 1218 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num); 1219 } 1220 if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_white_list_size)){ 1221 hci_stack->le_whitelist_capacity = READ_BT_16(packet, 6); 1222 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity); 1223 } 1224 #endif 1225 // Dump local address 1226 if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) { 1227 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]); 1228 log_info("Local Address, Status: 0x%02x: Addr: %s", 1229 packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr)); 1230 } 1231 if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 1232 hci_emit_discoverable_enabled(hci_stack->discoverable); 1233 } 1234 // Note: HCI init checks 1235 if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){ 1236 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8); 1237 1238 // determine usable ACL packet types based on host buffer size and supported features 1239 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]); 1240 log_info("packet types %04x", hci_stack->packet_types); 1241 1242 // Classic/LE 1243 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported()); 1244 } 1245 if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_version_information)){ 1246 // hci_stack->hci_version = READ_BT_16(packet, 4); 1247 // hci_stack->hci_revision = READ_BT_16(packet, 6); 1248 // hci_stack->lmp_version = READ_BT_16(packet, 8); 1249 hci_stack->manufacturer = READ_BT_16(packet, 10); 1250 // hci_stack->lmp_subversion = READ_BT_16(packet, 12); 1251 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer); 1252 } 1253 if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_commands)){ 1254 hci_stack->local_supported_commands[0] = 1255 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0X80) >> 7 | // Octet 14, bit 7 1256 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5; // Octet 24, bit 6 1257 } 1258 break; 1259 1260 case HCI_EVENT_COMMAND_STATUS: 1261 // get num cmd packets 1262 // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]); 1263 hci_stack->num_cmd_packets = packet[3]; 1264 break; 1265 1266 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{ 1267 int offset = 3; 1268 for (i=0; i<packet[2];i++){ 1269 handle = READ_BT_16(packet, offset); 1270 offset += 2; 1271 uint16_t num_packets = READ_BT_16(packet, offset); 1272 offset += 2; 1273 1274 conn = hci_connection_for_handle(handle); 1275 if (!conn){ 1276 log_error("hci_number_completed_packet lists unused con handle %u", handle); 1277 continue; 1278 } 1279 1280 if (conn->address_type == BD_ADDR_TYPE_SCO){ 1281 if (conn->num_sco_packets_sent >= num_packets){ 1282 conn->num_sco_packets_sent -= num_packets; 1283 } else { 1284 log_error("hci_number_completed_packets, more sco slots freed then sent."); 1285 conn->num_sco_packets_sent = 0; 1286 } 1287 1288 } else { 1289 if (conn->num_acl_packets_sent >= num_packets){ 1290 conn->num_acl_packets_sent -= num_packets; 1291 } else { 1292 log_error("hci_number_completed_packets, more acl slots freed then sent."); 1293 conn->num_acl_packets_sent = 0; 1294 } 1295 } 1296 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent); 1297 } 1298 break; 1299 } 1300 case HCI_EVENT_CONNECTION_REQUEST: 1301 bt_flip_addr(addr, &packet[2]); 1302 // TODO: eval COD 8-10 1303 link_type = packet[11]; 1304 log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type); 1305 addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO; 1306 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 1307 if (!conn) { 1308 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 1309 } 1310 if (!conn) { 1311 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 1312 hci_stack->decline_reason = 0x0d; 1313 BD_ADDR_COPY(hci_stack->decline_addr, addr); 1314 break; 1315 } 1316 conn->role = HCI_ROLE_SLAVE; 1317 conn->state = RECEIVED_CONNECTION_REQUEST; 1318 hci_run(); 1319 break; 1320 1321 case HCI_EVENT_CONNECTION_COMPLETE: 1322 // Connection management 1323 bt_flip_addr(addr, &packet[5]); 1324 log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr)); 1325 addr_type = BD_ADDR_TYPE_CLASSIC; 1326 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 1327 if (conn) { 1328 if (!packet[2]){ 1329 conn->state = OPEN; 1330 conn->con_handle = READ_BT_16(packet, 3); 1331 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES; 1332 1333 // restart timer 1334 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 1335 run_loop_add_timer(&conn->timeout); 1336 1337 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 1338 1339 hci_emit_nr_connections_changed(); 1340 } else { 1341 int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED; 1342 uint8_t status = packet[2]; 1343 bd_addr_t bd_address; 1344 memcpy(&bd_address, conn->address, 6); 1345 1346 // connection failed, remove entry 1347 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 1348 btstack_memory_hci_connection_free( conn ); 1349 1350 // notify client if dedicated bonding 1351 if (notify_dedicated_bonding_failed){ 1352 log_info("hci notify_dedicated_bonding_failed"); 1353 hci_emit_dedicated_bonding_result(bd_address, status); 1354 } 1355 1356 // if authentication error, also delete link key 1357 if (packet[2] == 0x05) { 1358 hci_drop_link_key_for_bd_addr(addr); 1359 } 1360 } 1361 } 1362 break; 1363 1364 case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE: 1365 bt_flip_addr(addr, &packet[5]); 1366 log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr)); 1367 if (packet[2]){ 1368 // connection failed 1369 break; 1370 } 1371 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 1372 if (!conn) { 1373 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 1374 } 1375 if (!conn) { 1376 break; 1377 } 1378 conn->state = OPEN; 1379 conn->con_handle = READ_BT_16(packet, 3); 1380 break; 1381 1382 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 1383 handle = READ_BT_16(packet, 3); 1384 conn = hci_connection_for_handle(handle); 1385 if (!conn) break; 1386 if (!packet[2]){ 1387 uint8_t * features = &packet[5]; 1388 if (features[6] & (1 << 3)){ 1389 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP; 1390 } 1391 } 1392 conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES; 1393 log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags); 1394 if (conn->bonding_flags & BONDING_DEDICATED){ 1395 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 1396 } 1397 break; 1398 1399 case HCI_EVENT_LINK_KEY_REQUEST: 1400 log_info("HCI_EVENT_LINK_KEY_REQUEST"); 1401 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST); 1402 // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST 1403 if (hci_stack->bondable && !hci_stack->remote_device_db) break; 1404 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST); 1405 hci_run(); 1406 // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set 1407 return; 1408 1409 case HCI_EVENT_LINK_KEY_NOTIFICATION: { 1410 bt_flip_addr(addr, &packet[2]); 1411 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 1412 if (!conn) break; 1413 conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION; 1414 link_key_type_t link_key_type = (link_key_type_t)packet[24]; 1415 // Change Connection Encryption keeps link key type 1416 if (link_key_type != CHANGED_COMBINATION_KEY){ 1417 conn->link_key_type = link_key_type; 1418 } 1419 if (!hci_stack->remote_device_db) break; 1420 hci_stack->remote_device_db->put_link_key(addr, &packet[8], conn->link_key_type); 1421 // still forward event to allow dismiss of pairing dialog 1422 break; 1423 } 1424 1425 case HCI_EVENT_PIN_CODE_REQUEST: 1426 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE); 1427 // non-bondable mode: pin code negative reply will be sent 1428 if (!hci_stack->bondable){ 1429 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST); 1430 hci_run(); 1431 return; 1432 } 1433 // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key 1434 if (!hci_stack->remote_device_db) break; 1435 bt_flip_addr(addr, &packet[2]); 1436 hci_stack->remote_device_db->delete_link_key(addr); 1437 break; 1438 1439 case HCI_EVENT_IO_CAPABILITY_REQUEST: 1440 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST); 1441 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY); 1442 break; 1443 1444 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 1445 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 1446 if (!hci_stack->ssp_auto_accept) break; 1447 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY); 1448 break; 1449 1450 case HCI_EVENT_USER_PASSKEY_REQUEST: 1451 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 1452 if (!hci_stack->ssp_auto_accept) break; 1453 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY); 1454 break; 1455 1456 case HCI_EVENT_ENCRYPTION_CHANGE: 1457 handle = READ_BT_16(packet, 3); 1458 conn = hci_connection_for_handle(handle); 1459 if (!conn) break; 1460 if (packet[2] == 0) { 1461 if (packet[5]){ 1462 conn->authentication_flags |= CONNECTION_ENCRYPTED; 1463 } else { 1464 conn->authentication_flags &= ~CONNECTION_ENCRYPTED; 1465 } 1466 } 1467 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 1468 break; 1469 1470 case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT: 1471 handle = READ_BT_16(packet, 3); 1472 conn = hci_connection_for_handle(handle); 1473 if (!conn) break; 1474 1475 // dedicated bonding: send result and disconnect 1476 if (conn->bonding_flags & BONDING_DEDICATED){ 1477 conn->bonding_flags &= ~BONDING_DEDICATED; 1478 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 1479 conn->bonding_status = packet[2]; 1480 break; 1481 } 1482 1483 if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){ 1484 // link key sufficient for requested security 1485 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 1486 break; 1487 } 1488 // not enough 1489 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 1490 break; 1491 1492 #ifndef EMBEDDED 1493 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 1494 if (!hci_stack->remote_device_db) break; 1495 if (packet[2]) break; // status not ok 1496 bt_flip_addr(addr, &packet[3]); 1497 // fix for invalid remote names - terminate on 0xff 1498 for (i=0; i<248;i++){ 1499 if (packet[9+i] == 0xff){ 1500 packet[9+i] = 0; 1501 break; 1502 } 1503 } 1504 memset(&device_name, 0, sizeof(device_name_t)); 1505 strncpy((char*) device_name, (char*) &packet[9], 248); 1506 hci_stack->remote_device_db->put_name(addr, &device_name); 1507 break; 1508 1509 case HCI_EVENT_INQUIRY_RESULT: 1510 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{ 1511 if (!hci_stack->remote_device_db) break; 1512 // first send inq result packet 1513 hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size); 1514 // then send cached remote names 1515 int offset = 3; 1516 for (i=0; i<packet[2];i++){ 1517 bt_flip_addr(addr, &packet[offset]); 1518 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2; 1519 if (hci_stack->remote_device_db->get_name(addr, &device_name)){ 1520 hci_emit_remote_name_cached(addr, &device_name); 1521 } 1522 } 1523 return; 1524 } 1525 #endif 1526 1527 // HCI_EVENT_DISCONNECTION_COMPLETE 1528 // has been split, to first notify stack before shutting connection down 1529 // see end of function, too. 1530 case HCI_EVENT_DISCONNECTION_COMPLETE: 1531 if (packet[2]) break; // status != 0 1532 handle = READ_BT_16(packet, 3); 1533 conn = hci_connection_for_handle(handle); 1534 if (!conn) break; // no conn struct anymore 1535 // re-enable advertisements for le connections if active 1536 if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){ 1537 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE; 1538 } 1539 conn->state = RECEIVED_DISCONNECTION_COMPLETE; 1540 break; 1541 1542 case HCI_EVENT_HARDWARE_ERROR: 1543 if (hci_stack->hardware_error_callback){ 1544 (*hci_stack->hardware_error_callback)(); 1545 } else if(hci_stack->control && hci_stack->control->hw_error){ 1546 (*hci_stack->control->hw_error)(); 1547 } else { 1548 // if no special requests, just reboot stack 1549 hci_power_control_off(); 1550 hci_power_control_on(); 1551 } 1552 break; 1553 1554 case HCI_EVENT_ROLE_CHANGE: 1555 if (packet[2]) break; // status != 0 1556 handle = READ_BT_16(packet, 3); 1557 conn = hci_connection_for_handle(handle); 1558 if (!conn) break; // no conn 1559 conn->role = packet[9]; 1560 break; 1561 1562 case DAEMON_EVENT_HCI_PACKET_SENT: 1563 // release packet buffer only for asynchronous transport and if there are not further fragements 1564 if (hci_transport_synchronous()) { 1565 log_error("Synchronous HCI Transport shouldn't send DAEMON_EVENT_HCI_PACKET_SENT"); 1566 return; // instead of break: to avoid re-entering hci_run() 1567 } 1568 if (hci_stack->acl_fragmentation_total_size) break; 1569 hci_release_packet_buffer(); 1570 break; 1571 1572 #ifdef HAVE_BLE 1573 case HCI_EVENT_LE_META: 1574 switch (packet[2]){ 1575 case HCI_SUBEVENT_LE_ADVERTISING_REPORT: 1576 log_info("advertising report received"); 1577 if (hci_stack->le_scanning_state != LE_SCANNING) break; 1578 le_handle_advertisement_report(packet, size); 1579 break; 1580 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 1581 // Connection management 1582 bt_flip_addr(addr, &packet[8]); 1583 addr_type = (bd_addr_type_t)packet[7]; 1584 log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr)); 1585 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 1586 // if auto-connect, remove from whitelist in both roles 1587 if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){ 1588 hci_remove_from_whitelist(addr_type, addr); 1589 } 1590 // handle error: error is reported only to the initiator -> outgoing connection 1591 if (packet[3]){ 1592 // outgoing connection establishment is done 1593 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 1594 // remove entry 1595 if (conn){ 1596 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 1597 btstack_memory_hci_connection_free( conn ); 1598 } 1599 break; 1600 } 1601 // on success, both hosts receive connection complete event 1602 if (packet[6] == HCI_ROLE_MASTER){ 1603 // if we're master, it was an outgoing connection and we're done with it 1604 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 1605 } else { 1606 // if we're slave, it was an incoming connection, advertisements have stopped 1607 hci_stack->le_advertisements_active = 0; 1608 } 1609 // LE connections are auto-accepted, so just create a connection if there isn't one already 1610 if (!conn){ 1611 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 1612 } 1613 // no memory, sorry. 1614 if (!conn){ 1615 break; 1616 } 1617 1618 conn->state = OPEN; 1619 conn->role = packet[6]; 1620 conn->con_handle = READ_BT_16(packet, 4); 1621 1622 // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock 1623 1624 // restart timer 1625 // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 1626 // run_loop_add_timer(&conn->timeout); 1627 1628 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 1629 1630 hci_emit_nr_connections_changed(); 1631 break; 1632 1633 // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]); 1634 1635 default: 1636 break; 1637 } 1638 break; 1639 #endif 1640 default: 1641 break; 1642 } 1643 1644 // handle BT initialization 1645 if (hci_stack->state == HCI_STATE_INITIALIZING){ 1646 hci_initializing_event_handler(packet, size); 1647 } 1648 1649 // help with BT sleep 1650 if (hci_stack->state == HCI_STATE_FALLING_ASLEEP 1651 && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE 1652 && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 1653 hci_initializing_next_state(); 1654 } 1655 1656 // notify upper stack 1657 hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size); 1658 1659 // moved here to give upper stack a chance to close down everything with hci_connection_t intact 1660 if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){ 1661 if (!packet[2]){ 1662 handle = READ_BT_16(packet, 3); 1663 hci_connection_t * aConn = hci_connection_for_handle(handle); 1664 if (aConn) { 1665 uint8_t status = aConn->bonding_status; 1666 uint16_t flags = aConn->bonding_flags; 1667 bd_addr_t bd_address; 1668 memcpy(&bd_address, aConn->address, 6); 1669 hci_shutdown_connection(aConn); 1670 // connection struct is gone, don't access anymore 1671 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){ 1672 hci_emit_dedicated_bonding_result(bd_address, status); 1673 } 1674 } 1675 } 1676 } 1677 1678 // execute main loop 1679 hci_run(); 1680 } 1681 1682 static void sco_handler(uint8_t * packet, uint16_t size){ 1683 if (!hci_stack->sco_packet_handler) return; 1684 hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, packet, size); 1685 } 1686 1687 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 1688 hci_dump_packet(packet_type, 1, packet, size); 1689 switch (packet_type) { 1690 case HCI_EVENT_PACKET: 1691 event_handler(packet, size); 1692 break; 1693 case HCI_ACL_DATA_PACKET: 1694 acl_handler(packet, size); 1695 break; 1696 case HCI_SCO_DATA_PACKET: 1697 sco_handler(packet, size); 1698 default: 1699 break; 1700 } 1701 } 1702 1703 /** Register HCI packet handlers */ 1704 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 1705 hci_stack->packet_handler = handler; 1706 } 1707 1708 /** 1709 * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles. 1710 */ 1711 void hci_register_sco_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 1712 hci_stack->sco_packet_handler = handler; 1713 } 1714 1715 static void hci_state_reset(void){ 1716 // no connections yet 1717 hci_stack->connections = NULL; 1718 1719 // keep discoverable/connectable as this has been requested by the client(s) 1720 // hci_stack->discoverable = 0; 1721 // hci_stack->connectable = 0; 1722 // hci_stack->bondable = 1; 1723 1724 // buffer is free 1725 hci_stack->hci_packet_buffer_reserved = 0; 1726 1727 // no pending cmds 1728 hci_stack->decline_reason = 0; 1729 hci_stack->new_scan_enable_value = 0xff; 1730 1731 // LE 1732 hci_stack->adv_addr_type = 0; 1733 memset(hci_stack->adv_address, 0, 6); 1734 hci_stack->le_scanning_state = LE_SCAN_IDLE; 1735 hci_stack->le_scan_type = 0xff; 1736 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 1737 hci_stack->le_whitelist = 0; 1738 hci_stack->le_whitelist_capacity = 0; 1739 hci_stack->le_connection_parameter_range.le_conn_interval_min = 6; 1740 hci_stack->le_connection_parameter_range.le_conn_interval_max = 3200; 1741 hci_stack->le_connection_parameter_range.le_conn_latency_min = 0; 1742 hci_stack->le_connection_parameter_range.le_conn_latency_max = 500; 1743 hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 10; 1744 hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200; 1745 } 1746 1747 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){ 1748 1749 #ifdef HAVE_MALLOC 1750 if (!hci_stack) { 1751 hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t)); 1752 } 1753 #else 1754 hci_stack = &hci_stack_static; 1755 #endif 1756 memset(hci_stack, 0, sizeof(hci_stack_t)); 1757 1758 // reference to use transport layer implementation 1759 hci_stack->hci_transport = transport; 1760 1761 // references to used control implementation 1762 hci_stack->control = control; 1763 1764 // reference to used config 1765 hci_stack->config = config; 1766 1767 // higher level handler 1768 hci_stack->packet_handler = dummy_handler; 1769 1770 // store and open remote device db 1771 hci_stack->remote_device_db = remote_device_db; 1772 if (hci_stack->remote_device_db) { 1773 hci_stack->remote_device_db->open(); 1774 } 1775 1776 // max acl payload size defined in config.h 1777 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 1778 1779 // register packet handlers with transport 1780 transport->register_packet_handler(&packet_handler); 1781 1782 hci_stack->state = HCI_STATE_OFF; 1783 1784 // class of device 1785 hci_stack->class_of_device = 0x007a020c; // Smartphone 1786 1787 // bondable by default 1788 hci_stack->bondable = 1; 1789 1790 // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept 1791 hci_stack->ssp_enable = 1; 1792 hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 1793 hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 1794 hci_stack->ssp_auto_accept = 1; 1795 1796 // voice setting - signed 8 bit pcm data with CVSD over the air 1797 hci_stack->sco_voice_setting = 0x40; 1798 1799 hci_state_reset(); 1800 } 1801 1802 void hci_close(void){ 1803 // close remote device db 1804 if (hci_stack->remote_device_db) { 1805 hci_stack->remote_device_db->close(); 1806 } 1807 while (hci_stack->connections) { 1808 // cancel all l2cap connections 1809 hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host 1810 hci_shutdown_connection((hci_connection_t *) hci_stack->connections); 1811 } 1812 hci_power_control(HCI_POWER_OFF); 1813 1814 #ifdef HAVE_MALLOC 1815 free(hci_stack); 1816 #endif 1817 hci_stack = NULL; 1818 } 1819 1820 void hci_set_class_of_device(uint32_t class_of_device){ 1821 hci_stack->class_of_device = class_of_device; 1822 } 1823 1824 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h 1825 void hci_set_bd_addr(bd_addr_t addr){ 1826 memcpy(hci_stack->custom_bd_addr, addr, 6); 1827 hci_stack->custom_bd_addr_set = 1; 1828 } 1829 1830 void hci_disable_l2cap_timeout_check(void){ 1831 disable_l2cap_timeouts = 1; 1832 } 1833 // State-Module-Driver overview 1834 // state module low-level 1835 // HCI_STATE_OFF off close 1836 // HCI_STATE_INITIALIZING, on open 1837 // HCI_STATE_WORKING, on open 1838 // HCI_STATE_HALTING, on open 1839 // HCI_STATE_SLEEPING, off/sleep close 1840 // HCI_STATE_FALLING_ASLEEP on open 1841 1842 static int hci_power_control_on(void){ 1843 1844 // power on 1845 int err = 0; 1846 if (hci_stack->control && hci_stack->control->on){ 1847 err = (*hci_stack->control->on)(hci_stack->config); 1848 } 1849 if (err){ 1850 log_error( "POWER_ON failed"); 1851 hci_emit_hci_open_failed(); 1852 return err; 1853 } 1854 1855 // open low-level device 1856 err = hci_stack->hci_transport->open(hci_stack->config); 1857 if (err){ 1858 log_error( "HCI_INIT failed, turning Bluetooth off again"); 1859 if (hci_stack->control && hci_stack->control->off){ 1860 (*hci_stack->control->off)(hci_stack->config); 1861 } 1862 hci_emit_hci_open_failed(); 1863 return err; 1864 } 1865 return 0; 1866 } 1867 1868 static void hci_power_control_off(void){ 1869 1870 log_info("hci_power_control_off"); 1871 1872 // close low-level device 1873 hci_stack->hci_transport->close(hci_stack->config); 1874 1875 log_info("hci_power_control_off - hci_transport closed"); 1876 1877 // power off 1878 if (hci_stack->control && hci_stack->control->off){ 1879 (*hci_stack->control->off)(hci_stack->config); 1880 } 1881 1882 log_info("hci_power_control_off - control closed"); 1883 1884 hci_stack->state = HCI_STATE_OFF; 1885 } 1886 1887 static void hci_power_control_sleep(void){ 1888 1889 log_info("hci_power_control_sleep"); 1890 1891 #if 0 1892 // don't close serial port during sleep 1893 1894 // close low-level device 1895 hci_stack->hci_transport->close(hci_stack->config); 1896 #endif 1897 1898 // sleep mode 1899 if (hci_stack->control && hci_stack->control->sleep){ 1900 (*hci_stack->control->sleep)(hci_stack->config); 1901 } 1902 1903 hci_stack->state = HCI_STATE_SLEEPING; 1904 } 1905 1906 static int hci_power_control_wake(void){ 1907 1908 log_info("hci_power_control_wake"); 1909 1910 // wake on 1911 if (hci_stack->control && hci_stack->control->wake){ 1912 (*hci_stack->control->wake)(hci_stack->config); 1913 } 1914 1915 #if 0 1916 // open low-level device 1917 int err = hci_stack->hci_transport->open(hci_stack->config); 1918 if (err){ 1919 log_error( "HCI_INIT failed, turning Bluetooth off again"); 1920 if (hci_stack->control && hci_stack->control->off){ 1921 (*hci_stack->control->off)(hci_stack->config); 1922 } 1923 hci_emit_hci_open_failed(); 1924 return err; 1925 } 1926 #endif 1927 1928 return 0; 1929 } 1930 1931 static void hci_power_transition_to_initializing(void){ 1932 // set up state machine 1933 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 1934 hci_stack->hci_packet_buffer_reserved = 0; 1935 hci_stack->state = HCI_STATE_INITIALIZING; 1936 hci_stack->substate = HCI_INIT_SEND_RESET; 1937 } 1938 1939 int hci_power_control(HCI_POWER_MODE power_mode){ 1940 1941 log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state); 1942 1943 int err = 0; 1944 switch (hci_stack->state){ 1945 1946 case HCI_STATE_OFF: 1947 switch (power_mode){ 1948 case HCI_POWER_ON: 1949 err = hci_power_control_on(); 1950 if (err) { 1951 log_error("hci_power_control_on() error %u", err); 1952 return err; 1953 } 1954 hci_power_transition_to_initializing(); 1955 break; 1956 case HCI_POWER_OFF: 1957 // do nothing 1958 break; 1959 case HCI_POWER_SLEEP: 1960 // do nothing (with SLEEP == OFF) 1961 break; 1962 } 1963 break; 1964 1965 case HCI_STATE_INITIALIZING: 1966 switch (power_mode){ 1967 case HCI_POWER_ON: 1968 // do nothing 1969 break; 1970 case HCI_POWER_OFF: 1971 // no connections yet, just turn it off 1972 hci_power_control_off(); 1973 break; 1974 case HCI_POWER_SLEEP: 1975 // no connections yet, just turn it off 1976 hci_power_control_sleep(); 1977 break; 1978 } 1979 break; 1980 1981 case HCI_STATE_WORKING: 1982 switch (power_mode){ 1983 case HCI_POWER_ON: 1984 // do nothing 1985 break; 1986 case HCI_POWER_OFF: 1987 // see hci_run 1988 hci_stack->state = HCI_STATE_HALTING; 1989 break; 1990 case HCI_POWER_SLEEP: 1991 // see hci_run 1992 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 1993 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 1994 break; 1995 } 1996 break; 1997 1998 case HCI_STATE_HALTING: 1999 switch (power_mode){ 2000 case HCI_POWER_ON: 2001 hci_power_transition_to_initializing(); 2002 break; 2003 case HCI_POWER_OFF: 2004 // do nothing 2005 break; 2006 case HCI_POWER_SLEEP: 2007 // see hci_run 2008 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 2009 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 2010 break; 2011 } 2012 break; 2013 2014 case HCI_STATE_FALLING_ASLEEP: 2015 switch (power_mode){ 2016 case HCI_POWER_ON: 2017 2018 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 2019 // nothing to do, if H4 supports power management 2020 if (bt_control_iphone_power_management_enabled()){ 2021 hci_stack->state = HCI_STATE_INITIALIZING; 2022 hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE; // init after sleep 2023 break; 2024 } 2025 #endif 2026 hci_power_transition_to_initializing(); 2027 break; 2028 case HCI_POWER_OFF: 2029 // see hci_run 2030 hci_stack->state = HCI_STATE_HALTING; 2031 break; 2032 case HCI_POWER_SLEEP: 2033 // do nothing 2034 break; 2035 } 2036 break; 2037 2038 case HCI_STATE_SLEEPING: 2039 switch (power_mode){ 2040 case HCI_POWER_ON: 2041 2042 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 2043 // nothing to do, if H4 supports power management 2044 if (bt_control_iphone_power_management_enabled()){ 2045 hci_stack->state = HCI_STATE_INITIALIZING; 2046 hci_stack->substate = HCI_INIT_AFTER_SLEEP; 2047 hci_update_scan_enable(); 2048 break; 2049 } 2050 #endif 2051 err = hci_power_control_wake(); 2052 if (err) return err; 2053 hci_power_transition_to_initializing(); 2054 break; 2055 case HCI_POWER_OFF: 2056 hci_stack->state = HCI_STATE_HALTING; 2057 break; 2058 case HCI_POWER_SLEEP: 2059 // do nothing 2060 break; 2061 } 2062 break; 2063 } 2064 2065 // create internal event 2066 hci_emit_state(); 2067 2068 // trigger next/first action 2069 hci_run(); 2070 2071 return 0; 2072 } 2073 2074 static void hci_update_scan_enable(void){ 2075 // 2 = page scan, 1 = inq scan 2076 hci_stack->new_scan_enable_value = hci_stack->connectable << 1 | hci_stack->discoverable; 2077 hci_run(); 2078 } 2079 2080 void hci_discoverable_control(uint8_t enable){ 2081 if (enable) enable = 1; // normalize argument 2082 2083 if (hci_stack->discoverable == enable){ 2084 hci_emit_discoverable_enabled(hci_stack->discoverable); 2085 return; 2086 } 2087 2088 hci_stack->discoverable = enable; 2089 hci_update_scan_enable(); 2090 } 2091 2092 void hci_connectable_control(uint8_t enable){ 2093 if (enable) enable = 1; // normalize argument 2094 2095 // don't emit event 2096 if (hci_stack->connectable == enable) return; 2097 2098 hci_stack->connectable = enable; 2099 hci_update_scan_enable(); 2100 } 2101 2102 void hci_local_bd_addr(bd_addr_t address_buffer){ 2103 memcpy(address_buffer, hci_stack->local_bd_addr, 6); 2104 } 2105 2106 void hci_run(void){ 2107 2108 // log_info("hci_run: entered"); 2109 linked_item_t * it; 2110 2111 // send continuation fragments first, as they block the prepared packet buffer 2112 if (hci_stack->acl_fragmentation_total_size > 0) { 2113 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer); 2114 if (hci_can_send_prepared_acl_packet_now(con_handle)){ 2115 hci_connection_t *connection = hci_connection_for_handle(con_handle); 2116 if (connection) { 2117 hci_send_acl_packet_fragments(connection); 2118 return; 2119 } 2120 // connection gone -> discard further fragments 2121 hci_stack->acl_fragmentation_total_size = 0; 2122 hci_stack->acl_fragmentation_pos = 0; 2123 } 2124 } 2125 2126 if (!hci_can_send_command_packet_now()) return; 2127 2128 // global/non-connection oriented commands 2129 2130 // decline incoming connections 2131 if (hci_stack->decline_reason){ 2132 uint8_t reason = hci_stack->decline_reason; 2133 hci_stack->decline_reason = 0; 2134 hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason); 2135 return; 2136 } 2137 2138 // send scan enable 2139 if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){ 2140 hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value); 2141 hci_stack->new_scan_enable_value = 0xff; 2142 return; 2143 } 2144 2145 #ifdef HAVE_BLE 2146 if (hci_stack->state == HCI_STATE_WORKING){ 2147 // handle le scan 2148 switch(hci_stack->le_scanning_state){ 2149 case LE_START_SCAN: 2150 hci_stack->le_scanning_state = LE_SCANNING; 2151 hci_send_cmd(&hci_le_set_scan_enable, 1, 0); 2152 return; 2153 2154 case LE_STOP_SCAN: 2155 hci_stack->le_scanning_state = LE_SCAN_IDLE; 2156 hci_send_cmd(&hci_le_set_scan_enable, 0, 0); 2157 return; 2158 default: 2159 break; 2160 } 2161 if (hci_stack->le_scan_type != 0xff){ 2162 // defaults: active scanning, accept all advertisement packets 2163 int scan_type = hci_stack->le_scan_type; 2164 hci_stack->le_scan_type = 0xff; 2165 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); 2166 return; 2167 } 2168 // le advertisement control 2169 if (hci_stack->le_advertisements_todo){ 2170 log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo ); 2171 } 2172 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){ 2173 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE; 2174 hci_send_cmd(&hci_le_set_advertise_enable, 0); 2175 return; 2176 } 2177 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){ 2178 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS; 2179 hci_send_cmd(&hci_le_set_advertising_parameters, 2180 hci_stack->le_advertisements_interval_min, 2181 hci_stack->le_advertisements_interval_max, 2182 hci_stack->le_advertisements_type, 2183 hci_stack->le_advertisements_own_address_type, 2184 hci_stack->le_advertisements_direct_address_type, 2185 hci_stack->le_advertisements_direct_address, 2186 hci_stack->le_advertisements_channel_map, 2187 hci_stack->le_advertisements_filter_policy); 2188 return; 2189 } 2190 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_DATA){ 2191 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_DATA; 2192 hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, 2193 hci_stack->le_advertisements_data); 2194 return; 2195 } 2196 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){ 2197 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE; 2198 hci_send_cmd(&hci_le_set_advertise_enable, 1); 2199 return; 2200 } 2201 2202 // 2203 // LE Whitelist Management 2204 // 2205 2206 // check if whitelist needs modification 2207 linked_list_iterator_t lit; 2208 int modification_pending = 0; 2209 linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 2210 while (linked_list_iterator_has_next(&lit)){ 2211 whitelist_entry_t * entry = (whitelist_entry_t*) linked_list_iterator_next(&lit); 2212 if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){ 2213 modification_pending = 1; 2214 break; 2215 } 2216 } 2217 2218 if (modification_pending){ 2219 // stop connnecting if modification pending 2220 if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){ 2221 hci_send_cmd(&hci_le_create_connection_cancel); 2222 return; 2223 } 2224 2225 // add/remove entries 2226 linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 2227 while (linked_list_iterator_has_next(&lit)){ 2228 whitelist_entry_t * entry = (whitelist_entry_t*) linked_list_iterator_next(&lit); 2229 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){ 2230 entry->state = LE_WHITELIST_ON_CONTROLLER; 2231 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address); 2232 return; 2233 2234 } 2235 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){ 2236 bd_addr_t address; 2237 bd_addr_type_t address_type = entry->address_type; 2238 memcpy(address, entry->address, 6); 2239 linked_list_remove(&hci_stack->le_whitelist, (linked_item_t *) entry); 2240 btstack_memory_whitelist_entry_free(entry); 2241 hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address); 2242 return; 2243 } 2244 } 2245 } 2246 2247 // start connecting 2248 if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE && 2249 !linked_list_empty(&hci_stack->le_whitelist)){ 2250 bd_addr_t null_addr; 2251 memset(null_addr, 0, 6); 2252 hci_send_cmd(&hci_le_create_connection, 2253 0x0060, // scan interval: 60 ms 2254 0x0030, // scan interval: 30 ms 2255 1, // use whitelist 2256 0, // peer address type 2257 null_addr, // peer bd addr 2258 hci_stack->adv_addr_type, // our addr type: 2259 0x0008, // conn interval min 2260 0x0018, // conn interval max 2261 0, // conn latency 2262 0x0048, // supervision timeout 2263 0x0001, // min ce length 2264 0x0001 // max ce length 2265 ); 2266 return; 2267 } 2268 } 2269 #endif 2270 2271 // send pending HCI commands 2272 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 2273 hci_connection_t * connection = (hci_connection_t *) it; 2274 2275 switch(connection->state){ 2276 case SEND_CREATE_CONNECTION: 2277 switch(connection->address_type){ 2278 case BD_ADDR_TYPE_CLASSIC: 2279 log_info("sending hci_create_connection"); 2280 hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1); 2281 break; 2282 default: 2283 #ifdef HAVE_BLE 2284 log_info("sending hci_le_create_connection"); 2285 hci_send_cmd(&hci_le_create_connection, 2286 0x0060, // scan interval: 60 ms 2287 0x0030, // scan interval: 30 ms 2288 0, // don't use whitelist 2289 connection->address_type, // peer address type 2290 connection->address, // peer bd addr 2291 hci_stack->adv_addr_type, // our addr type: 2292 0x0008, // conn interval min 2293 0x0018, // conn interval max 2294 0, // conn latency 2295 0x0048, // supervision timeout 2296 0x0001, // min ce length 2297 0x0001 // max ce length 2298 ); 2299 2300 connection->state = SENT_CREATE_CONNECTION; 2301 #endif 2302 break; 2303 } 2304 return; 2305 2306 case RECEIVED_CONNECTION_REQUEST: 2307 log_info("sending hci_accept_connection_request"); 2308 connection->state = ACCEPTED_CONNECTION_REQUEST; 2309 connection->role = HCI_ROLE_SLAVE; 2310 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){ 2311 hci_send_cmd(&hci_accept_connection_request, connection->address, 1); 2312 } else { 2313 hci_send_cmd(&hci_accept_synchronous_connection, connection->address, 8000, 8000, 0xFFFF, hci_stack->sco_voice_setting, 0xFF, 0x003F); 2314 } 2315 return; 2316 2317 #ifdef HAVE_BLE 2318 case SEND_CANCEL_CONNECTION: 2319 connection->state = SENT_CANCEL_CONNECTION; 2320 hci_send_cmd(&hci_le_create_connection_cancel); 2321 return; 2322 #endif 2323 case SEND_DISCONNECT: 2324 connection->state = SENT_DISCONNECT; 2325 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 2326 return; 2327 2328 default: 2329 break; 2330 } 2331 2332 if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){ 2333 log_info("responding to link key request"); 2334 connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST); 2335 link_key_t link_key; 2336 link_key_type_t link_key_type; 2337 if ( hci_stack->remote_device_db 2338 && hci_stack->remote_device_db->get_link_key(connection->address, link_key, &link_key_type) 2339 && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){ 2340 connection->link_key_type = link_key_type; 2341 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key); 2342 } else { 2343 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 2344 } 2345 return; 2346 } 2347 2348 if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){ 2349 log_info("denying to pin request"); 2350 connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST); 2351 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 2352 return; 2353 } 2354 2355 if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){ 2356 connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY); 2357 log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability); 2358 if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){ 2359 // tweak authentication requirements 2360 uint8_t authreq = hci_stack->ssp_authentication_requirement; 2361 if (connection->bonding_flags & BONDING_DEDICATED){ 2362 authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 2363 } 2364 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){ 2365 authreq |= 1; 2366 } 2367 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq); 2368 } else { 2369 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 2370 } 2371 return; 2372 } 2373 2374 if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){ 2375 connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY); 2376 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 2377 return; 2378 } 2379 2380 if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){ 2381 connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY); 2382 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 2383 return; 2384 } 2385 2386 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){ 2387 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES; 2388 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 2389 return; 2390 } 2391 2392 if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){ 2393 connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK; 2394 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005); // authentication failure 2395 return; 2396 } 2397 if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){ 2398 connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE; 2399 connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT; 2400 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // authentication done 2401 return; 2402 } 2403 if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){ 2404 connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST; 2405 hci_send_cmd(&hci_authentication_requested, connection->con_handle); 2406 return; 2407 } 2408 if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){ 2409 connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST; 2410 hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1); 2411 return; 2412 } 2413 2414 #ifdef HAVE_BLE 2415 if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){ 2416 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 2417 2418 uint16_t connection_interval_min = connection->le_conn_interval_min; 2419 connection->le_conn_interval_min = 0; 2420 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min, 2421 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 2422 0x0000, 0xffff); 2423 } 2424 #endif 2425 } 2426 2427 hci_connection_t * connection; 2428 switch (hci_stack->state){ 2429 case HCI_STATE_INITIALIZING: 2430 hci_initializing_run(); 2431 break; 2432 2433 case HCI_STATE_HALTING: 2434 2435 log_info("HCI_STATE_HALTING"); 2436 2437 // free whitelist entries 2438 #ifdef HAVE_BLE 2439 { 2440 linked_list_iterator_t lit; 2441 linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 2442 while (linked_list_iterator_has_next(&lit)){ 2443 whitelist_entry_t * entry = (whitelist_entry_t*) linked_list_iterator_next(&lit); 2444 linked_list_remove(&hci_stack->le_whitelist, (linked_item_t *) entry); 2445 btstack_memory_whitelist_entry_free(entry); 2446 } 2447 } 2448 #endif 2449 // close all open connections 2450 connection = (hci_connection_t *) hci_stack->connections; 2451 if (connection){ 2452 uint16_t con_handle = (uint16_t) connection->con_handle; 2453 if (!hci_can_send_command_packet_now()) return; 2454 2455 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle); 2456 2457 // cancel all l2cap connections right away instead of waiting for disconnection complete event ... 2458 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host 2459 2460 // ... which would be ignored anyway as we shutdown (free) the connection now 2461 hci_shutdown_connection(connection); 2462 2463 // finally, send the disconnect command 2464 hci_send_cmd(&hci_disconnect, con_handle, 0x13); // remote closed connection 2465 return; 2466 } 2467 log_info("HCI_STATE_HALTING, calling off"); 2468 2469 // switch mode 2470 hci_power_control_off(); 2471 2472 log_info("HCI_STATE_HALTING, emitting state"); 2473 hci_emit_state(); 2474 log_info("HCI_STATE_HALTING, done"); 2475 break; 2476 2477 case HCI_STATE_FALLING_ASLEEP: 2478 switch(hci_stack->substate) { 2479 case HCI_FALLING_ASLEEP_DISCONNECT: 2480 log_info("HCI_STATE_FALLING_ASLEEP"); 2481 // close all open connections 2482 connection = (hci_connection_t *) hci_stack->connections; 2483 2484 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 2485 // don't close connections, if H4 supports power management 2486 if (bt_control_iphone_power_management_enabled()){ 2487 connection = NULL; 2488 } 2489 #endif 2490 if (connection){ 2491 2492 // send disconnect 2493 if (!hci_can_send_command_packet_now()) return; 2494 2495 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle); 2496 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 2497 2498 // send disconnected event right away - causes higher layer connections to get closed, too. 2499 hci_shutdown_connection(connection); 2500 return; 2501 } 2502 2503 if (hci_classic_supported()){ 2504 // disable page and inquiry scan 2505 if (!hci_can_send_command_packet_now()) return; 2506 2507 log_info("HCI_STATE_HALTING, disabling inq scans"); 2508 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 2509 2510 // continue in next sub state 2511 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE; 2512 break; 2513 } 2514 // fall through for ble-only chips 2515 2516 case HCI_FALLING_ASLEEP_COMPLETE: 2517 log_info("HCI_STATE_HALTING, calling sleep"); 2518 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 2519 // don't actually go to sleep, if H4 supports power management 2520 if (bt_control_iphone_power_management_enabled()){ 2521 // SLEEP MODE reached 2522 hci_stack->state = HCI_STATE_SLEEPING; 2523 hci_emit_state(); 2524 break; 2525 } 2526 #endif 2527 // switch mode 2528 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 2529 hci_emit_state(); 2530 break; 2531 2532 default: 2533 break; 2534 } 2535 break; 2536 2537 default: 2538 break; 2539 } 2540 } 2541 2542 int hci_send_cmd_packet(uint8_t *packet, int size){ 2543 bd_addr_t addr; 2544 hci_connection_t * conn; 2545 // house-keeping 2546 2547 // create_connection? 2548 if (IS_COMMAND(packet, hci_create_connection)){ 2549 bt_flip_addr(addr, &packet[3]); 2550 log_info("Create_connection to %s", bd_addr_to_str(addr)); 2551 2552 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 2553 if (!conn){ 2554 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 2555 if (!conn){ 2556 // notify client that alloc failed 2557 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 2558 return 0; // don't sent packet to controller 2559 } 2560 conn->state = SEND_CREATE_CONNECTION; 2561 } 2562 log_info("conn state %u", conn->state); 2563 switch (conn->state){ 2564 // if connection active exists 2565 case OPEN: 2566 // and OPEN, emit connection complete command, don't send to controller 2567 hci_emit_connection_complete(conn, 0); 2568 return 0; 2569 case SEND_CREATE_CONNECTION: 2570 // connection created by hci, e.g. dedicated bonding 2571 break; 2572 default: 2573 // otherwise, just ignore as it is already in the open process 2574 return 0; 2575 } 2576 conn->state = SENT_CREATE_CONNECTION; 2577 } 2578 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 2579 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 2580 } 2581 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 2582 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 2583 } 2584 2585 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 2586 if (hci_stack->remote_device_db){ 2587 bt_flip_addr(addr, &packet[3]); 2588 hci_stack->remote_device_db->delete_link_key(addr); 2589 } 2590 } 2591 2592 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply) 2593 || IS_COMMAND(packet, hci_pin_code_request_reply)){ 2594 bt_flip_addr(addr, &packet[3]); 2595 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 2596 if (conn){ 2597 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE); 2598 } 2599 } 2600 2601 if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply) 2602 || IS_COMMAND(packet, hci_user_confirmation_request_reply) 2603 || IS_COMMAND(packet, hci_user_passkey_request_negative_reply) 2604 || IS_COMMAND(packet, hci_user_passkey_request_reply)) { 2605 bt_flip_addr(addr, &packet[3]); 2606 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 2607 if (conn){ 2608 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE); 2609 } 2610 } 2611 2612 #ifdef HAVE_BLE 2613 if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){ 2614 hci_stack->adv_addr_type = packet[8]; 2615 } 2616 if (IS_COMMAND(packet, hci_le_set_random_address)){ 2617 bt_flip_addr(hci_stack->adv_address, &packet[3]); 2618 } 2619 if (IS_COMMAND(packet, hci_le_set_advertise_enable)){ 2620 hci_stack->le_advertisements_active = packet[3]; 2621 } 2622 if (IS_COMMAND(packet, hci_le_create_connection)){ 2623 // white list used? 2624 uint8_t initiator_filter_policy = packet[7]; 2625 switch (initiator_filter_policy){ 2626 case 0: 2627 // whitelist not used 2628 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT; 2629 break; 2630 case 1: 2631 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST; 2632 break; 2633 default: 2634 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy); 2635 break; 2636 } 2637 } 2638 if (IS_COMMAND(packet, hci_le_create_connection_cancel)){ 2639 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 2640 } 2641 #endif 2642 2643 hci_stack->num_cmd_packets--; 2644 2645 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 2646 int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 2647 2648 // release packet buffer for synchronous transport implementations 2649 if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){ 2650 hci_stack->hci_packet_buffer_reserved = 0; 2651 } 2652 2653 return err; 2654 } 2655 2656 // disconnect because of security block 2657 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 2658 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2659 if (!connection) return; 2660 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 2661 } 2662 2663 2664 // Configure Secure Simple Pairing 2665 2666 // enable will enable SSP during init 2667 void hci_ssp_set_enable(int enable){ 2668 hci_stack->ssp_enable = enable; 2669 } 2670 2671 int hci_local_ssp_activated(void){ 2672 return hci_ssp_supported() && hci_stack->ssp_enable; 2673 } 2674 2675 // if set, BTstack will respond to io capability request using authentication requirement 2676 void hci_ssp_set_io_capability(int io_capability){ 2677 hci_stack->ssp_io_capability = io_capability; 2678 } 2679 void hci_ssp_set_authentication_requirement(int authentication_requirement){ 2680 hci_stack->ssp_authentication_requirement = authentication_requirement; 2681 } 2682 2683 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 2684 void hci_ssp_set_auto_accept(int auto_accept){ 2685 hci_stack->ssp_auto_accept = auto_accept; 2686 } 2687 2688 /** 2689 * pre: numcmds >= 0 - it's allowed to send a command to the controller 2690 */ 2691 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 2692 2693 if (!hci_can_send_command_packet_now()){ 2694 log_error("hci_send_cmd called but cannot send packet now"); 2695 return 0; 2696 } 2697 2698 // for HCI INITIALIZATION 2699 // log_info("hci_send_cmd: opcode %04x", cmd->opcode); 2700 hci_stack->last_cmd_opcode = cmd->opcode; 2701 2702 hci_reserve_packet_buffer(); 2703 uint8_t * packet = hci_stack->hci_packet_buffer; 2704 2705 va_list argptr; 2706 va_start(argptr, cmd); 2707 uint16_t size = hci_create_cmd_internal(packet, cmd, argptr); 2708 va_end(argptr); 2709 2710 return hci_send_cmd_packet(packet, size); 2711 } 2712 2713 // Create various non-HCI events. 2714 // TODO: generalize, use table similar to hci_create_command 2715 2716 void hci_emit_state(void){ 2717 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 2718 uint8_t event[3]; 2719 event[0] = BTSTACK_EVENT_STATE; 2720 event[1] = sizeof(event) - 2; 2721 event[2] = hci_stack->state; 2722 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2723 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2724 } 2725 2726 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){ 2727 uint8_t event[13]; 2728 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 2729 event[1] = sizeof(event) - 2; 2730 event[2] = status; 2731 bt_store_16(event, 3, conn->con_handle); 2732 bt_flip_addr(&event[5], conn->address); 2733 event[11] = 1; // ACL connection 2734 event[12] = 0; // encryption disabled 2735 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2736 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2737 } 2738 2739 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, uint16_t conn_handle, uint8_t status){ 2740 uint8_t event[21]; 2741 event[0] = HCI_EVENT_LE_META; 2742 event[1] = sizeof(event) - 2; 2743 event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE; 2744 event[3] = status; 2745 bt_store_16(event, 4, conn_handle); 2746 event[6] = 0; // TODO: role 2747 event[7] = address_type; 2748 bt_flip_addr(&event[8], address); 2749 bt_store_16(event, 14, 0); // interval 2750 bt_store_16(event, 16, 0); // latency 2751 bt_store_16(event, 18, 0); // supervision timeout 2752 event[20] = 0; // master clock accuracy 2753 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2754 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2755 } 2756 2757 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 2758 uint8_t event[6]; 2759 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 2760 event[1] = sizeof(event) - 2; 2761 event[2] = 0; // status = OK 2762 bt_store_16(event, 3, handle); 2763 event[5] = reason; 2764 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2765 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2766 } 2767 2768 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 2769 if (disable_l2cap_timeouts) return; 2770 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 2771 uint8_t event[4]; 2772 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 2773 event[1] = sizeof(event) - 2; 2774 bt_store_16(event, 2, conn->con_handle); 2775 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2776 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2777 } 2778 2779 void hci_emit_nr_connections_changed(void){ 2780 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 2781 uint8_t event[3]; 2782 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 2783 event[1] = sizeof(event) - 2; 2784 event[2] = nr_hci_connections(); 2785 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2786 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2787 } 2788 2789 void hci_emit_hci_open_failed(void){ 2790 log_info("BTSTACK_EVENT_POWERON_FAILED"); 2791 uint8_t event[2]; 2792 event[0] = BTSTACK_EVENT_POWERON_FAILED; 2793 event[1] = sizeof(event) - 2; 2794 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2795 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2796 } 2797 2798 #ifndef EMBEDDED 2799 void hci_emit_btstack_version(void){ 2800 log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 2801 uint8_t event[6]; 2802 event[0] = BTSTACK_EVENT_VERSION; 2803 event[1] = sizeof(event) - 2; 2804 event[2] = BTSTACK_MAJOR; 2805 event[3] = BTSTACK_MINOR; 2806 bt_store_16(event, 4, 3257); // last SVN commit on Google Code + 1 2807 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2808 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2809 } 2810 #endif 2811 2812 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 2813 log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 2814 uint8_t event[3]; 2815 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 2816 event[1] = sizeof(event) - 2; 2817 event[2] = enabled; 2818 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2819 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2820 } 2821 2822 void hci_emit_remote_name_cached(bd_addr_t addr, device_name_t *name){ 2823 uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info 2824 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 2825 event[1] = sizeof(event) - 2 - 1; 2826 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 2827 bt_flip_addr(&event[3], addr); 2828 memcpy(&event[9], name, 248); 2829 2830 event[9+248] = 0; // assert \0 for log_info 2831 log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(addr), &event[9]); 2832 2833 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1); 2834 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1); 2835 } 2836 2837 void hci_emit_discoverable_enabled(uint8_t enabled){ 2838 log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled); 2839 uint8_t event[3]; 2840 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 2841 event[1] = sizeof(event) - 2; 2842 event[2] = enabled; 2843 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2844 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2845 } 2846 2847 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 2848 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 2849 uint8_t event[5]; 2850 int pos = 0; 2851 event[pos++] = GAP_SECURITY_LEVEL; 2852 event[pos++] = sizeof(event) - 2; 2853 bt_store_16(event, 2, con_handle); 2854 pos += 2; 2855 event[pos++] = level; 2856 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2857 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2858 } 2859 2860 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){ 2861 log_info("hci_emit_dedicated_bonding_result %u ", status); 2862 uint8_t event[9]; 2863 int pos = 0; 2864 event[pos++] = GAP_DEDICATED_BONDING_COMPLETED; 2865 event[pos++] = sizeof(event) - 2; 2866 event[pos++] = status; 2867 bt_flip_addr( &event[pos], address); 2868 pos += 6; 2869 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2870 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2871 } 2872 2873 // query if remote side supports SSP 2874 int hci_remote_ssp_supported(hci_con_handle_t con_handle){ 2875 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2876 if (!connection) return 0; 2877 return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0; 2878 } 2879 2880 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){ 2881 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 2882 } 2883 2884 // GAP API 2885 /** 2886 * @bbrief enable/disable bonding. default is enabled 2887 * @praram enabled 2888 */ 2889 void gap_set_bondable_mode(int enable){ 2890 hci_stack->bondable = enable ? 1 : 0; 2891 } 2892 /** 2893 * @brief Get bondable mode. 2894 * @return 1 if bondable 2895 */ 2896 int gap_get_bondable_mode(void){ 2897 return hci_stack->bondable; 2898 } 2899 2900 /** 2901 * @brief map link keys to security levels 2902 */ 2903 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 2904 switch (link_key_type){ 2905 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 2906 return LEVEL_4; 2907 case COMBINATION_KEY: 2908 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 2909 return LEVEL_3; 2910 default: 2911 return LEVEL_2; 2912 } 2913 } 2914 2915 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 2916 if (!connection) return LEVEL_0; 2917 if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 2918 return gap_security_level_for_link_key_type(connection->link_key_type); 2919 } 2920 2921 2922 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 2923 log_info("gap_mitm_protection_required_for_security_level %u", level); 2924 return level > LEVEL_2; 2925 } 2926 2927 /** 2928 * @brief get current security level 2929 */ 2930 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 2931 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2932 if (!connection) return LEVEL_0; 2933 return gap_security_level_for_connection(connection); 2934 } 2935 2936 /** 2937 * @brief request connection to device to 2938 * @result GAP_AUTHENTICATION_RESULT 2939 */ 2940 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 2941 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2942 if (!connection){ 2943 hci_emit_security_level(con_handle, LEVEL_0); 2944 return; 2945 } 2946 gap_security_level_t current_level = gap_security_level(con_handle); 2947 log_info("gap_request_security_level %u, current level %u", requested_level, current_level); 2948 if (current_level >= requested_level){ 2949 hci_emit_security_level(con_handle, current_level); 2950 return; 2951 } 2952 2953 connection->requested_security_level = requested_level; 2954 2955 #if 0 2956 // sending encryption request without a link key results in an error. 2957 // TODO: figure out how to use it properly 2958 2959 // would enabling ecnryption suffice (>= LEVEL_2)? 2960 if (hci_stack->remote_device_db){ 2961 link_key_type_t link_key_type; 2962 link_key_t link_key; 2963 if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){ 2964 if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){ 2965 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 2966 return; 2967 } 2968 } 2969 } 2970 #endif 2971 2972 // try to authenticate connection 2973 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2974 hci_run(); 2975 } 2976 2977 /** 2978 * @brief start dedicated bonding with device. disconnect after bonding 2979 * @param device 2980 * @param request MITM protection 2981 * @result GAP_DEDICATED_BONDING_COMPLETE 2982 */ 2983 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 2984 2985 // create connection state machine 2986 hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC); 2987 2988 if (!connection){ 2989 return BTSTACK_MEMORY_ALLOC_FAILED; 2990 } 2991 2992 // delete linkn key 2993 hci_drop_link_key_for_bd_addr(device); 2994 2995 // configure LEVEL_2/3, dedicated bonding 2996 connection->state = SEND_CREATE_CONNECTION; 2997 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 2998 log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level); 2999 connection->bonding_flags = BONDING_DEDICATED; 3000 3001 // wait for GAP Security Result and send GAP Dedicated Bonding complete 3002 3003 // handle: connnection failure (connection complete != ok) 3004 // handle: authentication failure 3005 // handle: disconnect on done 3006 3007 hci_run(); 3008 3009 return 0; 3010 } 3011 3012 void gap_set_local_name(const char * local_name){ 3013 hci_stack->local_name = local_name; 3014 } 3015 3016 le_command_status_t le_central_start_scan(void){ 3017 if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK; 3018 hci_stack->le_scanning_state = LE_START_SCAN; 3019 hci_run(); 3020 return BLE_PERIPHERAL_OK; 3021 } 3022 3023 le_command_status_t le_central_stop_scan(void){ 3024 if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK; 3025 hci_stack->le_scanning_state = LE_STOP_SCAN; 3026 hci_run(); 3027 return BLE_PERIPHERAL_OK; 3028 } 3029 3030 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){ 3031 hci_stack->le_scan_type = scan_type; 3032 hci_stack->le_scan_interval = scan_interval; 3033 hci_stack->le_scan_window = scan_window; 3034 hci_run(); 3035 } 3036 3037 le_command_status_t le_central_connect(bd_addr_t addr, bd_addr_type_t addr_type){ 3038 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 3039 if (!conn){ 3040 log_info("le_central_connect: no connection exists yet, creating context"); 3041 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 3042 if (!conn){ 3043 // notify client that alloc failed 3044 hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 3045 log_info("le_central_connect: failed to alloc hci_connection_t"); 3046 return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller 3047 } 3048 conn->state = SEND_CREATE_CONNECTION; 3049 log_info("le_central_connect: send create connection next"); 3050 hci_run(); 3051 return BLE_PERIPHERAL_OK; 3052 } 3053 3054 if (!hci_is_le_connection(conn) || 3055 conn->state == SEND_CREATE_CONNECTION || 3056 conn->state == SENT_CREATE_CONNECTION) { 3057 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED); 3058 log_error("le_central_connect: classic connection or connect is already being created"); 3059 return BLE_PERIPHERAL_IN_WRONG_STATE; 3060 } 3061 3062 log_info("le_central_connect: context exists with state %u", conn->state); 3063 hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0); 3064 hci_run(); 3065 return BLE_PERIPHERAL_OK; 3066 } 3067 3068 // @assumption: only a single outgoing LE Connection exists 3069 static hci_connection_t * le_central_get_outgoing_connection(void){ 3070 linked_item_t *it; 3071 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 3072 hci_connection_t * conn = (hci_connection_t *) it; 3073 if (!hci_is_le_connection(conn)) continue; 3074 switch (conn->state){ 3075 case SEND_CREATE_CONNECTION: 3076 case SENT_CREATE_CONNECTION: 3077 return conn; 3078 default: 3079 break; 3080 }; 3081 } 3082 return NULL; 3083 } 3084 3085 le_command_status_t le_central_connect_cancel(void){ 3086 hci_connection_t * conn = le_central_get_outgoing_connection(); 3087 if (!conn) return BLE_PERIPHERAL_OK; 3088 switch (conn->state){ 3089 case SEND_CREATE_CONNECTION: 3090 // skip sending create connection and emit event instead 3091 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER); 3092 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 3093 btstack_memory_hci_connection_free( conn ); 3094 break; 3095 case SENT_CREATE_CONNECTION: 3096 // request to send cancel connection 3097 conn->state = SEND_CANCEL_CONNECTION; 3098 hci_run(); 3099 break; 3100 default: 3101 break; 3102 } 3103 return BLE_PERIPHERAL_OK; 3104 } 3105 3106 /** 3107 * @brief Updates the connection parameters for a given LE connection 3108 * @param handle 3109 * @param conn_interval_min (unit: 1.25ms) 3110 * @param conn_interval_max (unit: 1.25ms) 3111 * @param conn_latency 3112 * @param supervision_timeout (unit: 10ms) 3113 * @returns 0 if ok 3114 */ 3115 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min, 3116 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 3117 hci_connection_t * connection = hci_connection_for_handle(con_handle); 3118 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 3119 connection->le_conn_interval_min = conn_interval_min; 3120 connection->le_conn_interval_max = conn_interval_max; 3121 connection->le_conn_latency = conn_latency; 3122 connection->le_supervision_timeout = supervision_timeout; 3123 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS; 3124 hci_run(); 3125 return 0; 3126 } 3127 3128 /** 3129 * @brief Request an update of the connection parameter for a given LE connection 3130 * @param handle 3131 * @param conn_interval_min (unit: 1.25ms) 3132 * @param conn_interval_max (unit: 1.25ms) 3133 * @param conn_latency 3134 * @param supervision_timeout (unit: 10ms) 3135 * @returns 0 if ok 3136 */ 3137 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min, 3138 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 3139 hci_connection_t * connection = hci_connection_for_handle(con_handle); 3140 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 3141 connection->le_conn_interval_min = conn_interval_min; 3142 connection->le_conn_interval_max = conn_interval_max; 3143 connection->le_conn_latency = conn_latency; 3144 connection->le_supervision_timeout = supervision_timeout; 3145 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST; 3146 hci_run(); 3147 return 0; 3148 } 3149 3150 /** 3151 * @brief Set Advertisement Data 3152 * @param advertising_data_length 3153 * @param advertising_data (max 31 octets) 3154 * @note data is not copied, pointer has to stay valid 3155 */ 3156 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){ 3157 hci_stack->le_advertisements_data_len = advertising_data_length; 3158 hci_stack->le_advertisements_data = advertising_data; 3159 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_DATA; 3160 // disable advertisements before setting data 3161 if (hci_stack->le_advertisements_active){ 3162 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE; 3163 } 3164 hci_run(); 3165 } 3166 3167 /** 3168 * @brief Set Advertisement Parameters 3169 * @param adv_int_min 3170 * @param adv_int_max 3171 * @param adv_type 3172 * @param own_address_type 3173 * @param direct_address_type 3174 * @param direct_address 3175 * @param channel_map 3176 * @param filter_policy 3177 * 3178 * @note internal use. use gap_advertisements_set_params from gap_le.h instead. 3179 */ 3180 void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, 3181 uint8_t own_address_type, uint8_t direct_address_typ, bd_addr_t direct_address, 3182 uint8_t channel_map, uint8_t filter_policy) { 3183 3184 hci_stack->le_advertisements_interval_min = adv_int_min; 3185 hci_stack->le_advertisements_interval_max = adv_int_max; 3186 hci_stack->le_advertisements_type = adv_type; 3187 hci_stack->le_advertisements_own_address_type = own_address_type; 3188 hci_stack->le_advertisements_direct_address_type = direct_address_typ; 3189 hci_stack->le_advertisements_channel_map = channel_map; 3190 hci_stack->le_advertisements_filter_policy = filter_policy; 3191 memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6); 3192 3193 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 3194 // disable advertisements before changing params 3195 if (hci_stack->le_advertisements_active){ 3196 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE; 3197 } 3198 hci_run(); 3199 } 3200 3201 /** 3202 * @brief Enable/Disable Advertisements 3203 * @param enabled 3204 */ 3205 void gap_advertisements_enable(int enabled){ 3206 hci_stack->le_advertisements_enabled = enabled; 3207 if (enabled && !hci_stack->le_advertisements_active){ 3208 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE; 3209 } 3210 if (!enabled && hci_stack->le_advertisements_active){ 3211 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE; 3212 } 3213 hci_run(); 3214 } 3215 3216 3217 le_command_status_t gap_disconnect(hci_con_handle_t handle){ 3218 hci_connection_t * conn = hci_connection_for_handle(handle); 3219 if (!conn){ 3220 hci_emit_disconnection_complete(handle, 0); 3221 return BLE_PERIPHERAL_OK; 3222 } 3223 conn->state = SEND_DISCONNECT; 3224 hci_run(); 3225 return BLE_PERIPHERAL_OK; 3226 } 3227 3228 /** 3229 * @brief Get connection type 3230 * @param con_handle 3231 * @result connection_type 3232 */ 3233 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){ 3234 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 3235 if (!conn) return GAP_CONNECTION_INVALID; 3236 switch (conn->address_type){ 3237 case BD_ADDR_TYPE_LE_PUBLIC: 3238 case BD_ADDR_TYPE_LE_RANDOM: 3239 return GAP_CONNECTION_LE; 3240 case BD_ADDR_TYPE_SCO: 3241 return GAP_CONNECTION_SCO; 3242 case BD_ADDR_TYPE_CLASSIC: 3243 return GAP_CONNECTION_ACL; 3244 default: 3245 return GAP_CONNECTION_INVALID; 3246 } 3247 } 3248 3249 #ifdef HAVE_BLE 3250 3251 /** 3252 * @brief Auto Connection Establishment - Start Connecting to device 3253 * @param address_typ 3254 * @param address 3255 * @returns 0 if ok 3256 */ 3257 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){ 3258 // check capacity 3259 int num_entries = linked_list_count(&hci_stack->le_whitelist); 3260 if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED; 3261 whitelist_entry_t * entry = btstack_memory_whitelist_entry_get(); 3262 if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED; 3263 entry->address_type = address_type; 3264 memcpy(entry->address, address, 6); 3265 entry->state = LE_WHITELIST_ADD_TO_CONTROLLER; 3266 linked_list_add(&hci_stack->le_whitelist, (linked_item_t*) entry); 3267 hci_run(); 3268 return 0; 3269 } 3270 3271 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){ 3272 linked_list_iterator_t it; 3273 linked_list_iterator_init(&it, &hci_stack->le_whitelist); 3274 while (linked_list_iterator_has_next(&it)){ 3275 whitelist_entry_t * entry = (whitelist_entry_t*) linked_list_iterator_next(&it); 3276 if (entry->address_type != address_type) continue; 3277 if (memcmp(entry->address, address, 6) != 0) continue; 3278 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 3279 // remove from controller if already present 3280 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 3281 continue; 3282 } 3283 // direclty remove entry from whitelist 3284 linked_list_iterator_remove(&it); 3285 btstack_memory_whitelist_entry_free(entry); 3286 } 3287 } 3288 3289 /** 3290 * @brief Auto Connection Establishment - Stop Connecting to device 3291 * @param address_typ 3292 * @param address 3293 * @returns 0 if ok 3294 */ 3295 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){ 3296 hci_remove_from_whitelist(address_type, address); 3297 hci_run(); 3298 return 0; 3299 } 3300 3301 /** 3302 * @brief Auto Connection Establishment - Stop everything 3303 * @note Convenience function to stop all active auto connection attempts 3304 */ 3305 void gap_auto_connection_stop_all(void){ 3306 linked_list_iterator_t it; 3307 linked_list_iterator_init(&it, &hci_stack->le_whitelist); 3308 while (linked_list_iterator_has_next(&it)){ 3309 whitelist_entry_t * entry = (whitelist_entry_t*) linked_list_iterator_next(&it); 3310 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 3311 // remove from controller if already present 3312 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 3313 continue; 3314 } 3315 // directly remove entry from whitelist 3316 linked_list_iterator_remove(&it); 3317 btstack_memory_whitelist_entry_free(entry); 3318 } 3319 hci_run(); 3320 } 3321 3322 #endif 3323 3324 /** 3325 * @brief Configure Voice Setting for use with SCO data in HSP/HFP 3326 */ 3327 void hci_set_sco_voice_setting(uint16_t voice_setting){ 3328 hci_stack->sco_voice_setting = voice_setting; 3329 } 3330 3331 /** 3332 * @brief Get SCO Voice Setting 3333 * @return current voice setting 3334 */ 3335 uint16_t hci_get_sco_voice_setting(){ 3336 return hci_stack->sco_voice_setting; 3337 } 3338 3339 /** 3340 * @brief Set callback for Bluetooth Hardware Error 3341 */ 3342 void hci_set_hardware_error_callback(void (*fn)(void)){ 3343 hci_stack->hardware_error_callback = fn; 3344 } 3345 3346 3347 void hci_disconnect_all(void){ 3348 linked_list_iterator_t it; 3349 linked_list_iterator_init(&it, &hci_stack->connections); 3350 while (linked_list_iterator_has_next(&it)){ 3351 hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it); 3352 if (con->state == SENT_DISCONNECT) continue; 3353 con->state = SEND_DISCONNECT; 3354 } 3355 hci_run(); 3356 } 3357