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