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 #define BTSTACK_FILE__ "hci.c" 39 40 /* 41 * hci.c 42 * 43 * Created by Matthias Ringwald on 4/29/09. 44 * 45 */ 46 47 #include "btstack_config.h" 48 49 50 #ifdef ENABLE_CLASSIC 51 #ifdef HAVE_EMBEDDED_TICK 52 #include "btstack_run_loop_embedded.h" 53 #endif 54 #endif 55 56 #ifdef HAVE_PLATFORM_IPHONE_OS 57 #include "../port/ios/src/btstack_control_iphone.h" 58 #endif 59 60 #ifdef ENABLE_BLE 61 #include "gap.h" 62 #endif 63 64 #include <stdarg.h> 65 #include <string.h> 66 #include <stdio.h> 67 #include <inttypes.h> 68 69 #include "btstack_debug.h" 70 #include "btstack_event.h" 71 #include "btstack_linked_list.h" 72 #include "btstack_memory.h" 73 #include "bluetooth_company_id.h" 74 #include "bluetooth_data_types.h" 75 #include "gap.h" 76 #include "hci.h" 77 #include "hci_cmd.h" 78 #include "hci_dump.h" 79 #include "ad_parser.h" 80 81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 82 #ifndef HCI_HOST_ACL_PACKET_NUM 83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM" 84 #endif 85 #ifndef HCI_HOST_ACL_PACKET_LEN 86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN" 87 #endif 88 #ifndef HCI_HOST_SCO_PACKET_NUM 89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM" 90 #endif 91 #ifndef HCI_HOST_SCO_PACKET_LEN 92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN" 93 #endif 94 #endif 95 96 #define HCI_CONNECTION_TIMEOUT_MS 10000 97 #define HCI_RESET_RESEND_TIMEOUT_MS 200 98 99 // Names are arbitrarily shortened to 32 bytes if not requested otherwise 100 #ifndef GAP_INQUIRY_MAX_NAME_LEN 101 #define GAP_INQUIRY_MAX_NAME_LEN 32 102 #endif 103 104 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested 105 #define GAP_INQUIRY_DURATION_MIN 0x01 106 #define GAP_INQUIRY_DURATION_MAX 0x30 107 #define GAP_INQUIRY_STATE_ACTIVE 0x80 108 #define GAP_INQUIRY_STATE_IDLE 0 109 #define GAP_INQUIRY_STATE_W2_CANCEL 0x81 110 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x82 111 112 // GAP Remote Name Request 113 #define GAP_REMOTE_NAME_STATE_IDLE 0 114 #define GAP_REMOTE_NAME_STATE_W2_SEND 1 115 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2 116 117 // GAP Pairing 118 #define GAP_PAIRING_STATE_IDLE 0 119 #define GAP_PAIRING_STATE_SEND_PIN 1 120 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE 2 121 #define GAP_PAIRING_STATE_SEND_PASSKEY 3 122 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE 4 123 #define GAP_PAIRING_STATE_SEND_CONFIRMATION 5 124 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6 125 126 127 // prototypes 128 #ifdef ENABLE_CLASSIC 129 static void hci_update_scan_enable(void); 130 static void hci_emit_discoverable_enabled(uint8_t enabled); 131 static int hci_local_ssp_activated(void); 132 static int hci_remote_ssp_supported(hci_con_handle_t con_handle); 133 static void hci_notify_if_sco_can_send_now(void); 134 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status); 135 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection); 136 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level); 137 static void hci_connection_timeout_handler(btstack_timer_source_t *timer); 138 static void hci_connection_timestamp(hci_connection_t *connection); 139 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn); 140 static void gap_inquiry_explode(uint8_t * packet); 141 #endif 142 143 static int hci_power_control_on(void); 144 static void hci_power_control_off(void); 145 static void hci_state_reset(void); 146 static void hci_emit_transport_packet_sent(void); 147 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason); 148 static void hci_emit_nr_connections_changed(void); 149 static void hci_emit_hci_open_failed(void); 150 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status); 151 static void hci_emit_event(uint8_t * event, uint16_t size, int dump); 152 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size); 153 static void hci_run(void); 154 static int hci_is_le_connection(hci_connection_t * connection); 155 static int hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type); 156 static int hci_have_usb_transport(void); 157 158 #ifdef ENABLE_BLE 159 #ifdef ENABLE_LE_CENTRAL 160 // called from test/ble_client/advertising_data_parser.c 161 void le_handle_advertisement_report(uint8_t *packet, uint16_t size); 162 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address); 163 static hci_connection_t * gap_get_outgoing_connection(void); 164 #endif 165 #endif 166 167 // the STACK is here 168 #ifndef HAVE_MALLOC 169 static hci_stack_t hci_stack_static; 170 #endif 171 static hci_stack_t * hci_stack = NULL; 172 173 #ifdef ENABLE_CLASSIC 174 // default name 175 static const char * default_classic_name = "BTstack 00:00:00:00:00:00"; 176 177 // test helper 178 static uint8_t disable_l2cap_timeouts = 0; 179 #endif 180 181 /** 182 * create connection for given address 183 * 184 * @return connection OR NULL, if no memory left 185 */ 186 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){ 187 log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type); 188 hci_connection_t * conn = btstack_memory_hci_connection_get(); 189 if (!conn) return NULL; 190 bd_addr_copy(conn->address, addr); 191 conn->address_type = addr_type; 192 conn->con_handle = 0xffff; 193 conn->authentication_flags = AUTH_FLAGS_NONE; 194 conn->bonding_flags = 0; 195 conn->requested_security_level = LEVEL_0; 196 #ifdef ENABLE_CLASSIC 197 btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler); 198 btstack_run_loop_set_timer_context(&conn->timeout, conn); 199 hci_connection_timestamp(conn); 200 #endif 201 conn->acl_recombination_length = 0; 202 conn->acl_recombination_pos = 0; 203 conn->num_packets_sent = 0; 204 205 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 206 #ifdef ENABLE_BLE 207 conn->le_phy_update_all_phys = 0xff; 208 #endif 209 btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn); 210 return conn; 211 } 212 213 214 /** 215 * get le connection parameter range 216 * 217 * @return le connection parameter range struct 218 */ 219 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){ 220 *range = hci_stack->le_connection_parameter_range; 221 } 222 223 /** 224 * set le connection parameter range 225 * 226 */ 227 228 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){ 229 hci_stack->le_connection_parameter_range = *range; 230 } 231 232 /** 233 * @brief Test if connection parameters are inside in existing rage 234 * @param conn_interval_min (unit: 1.25ms) 235 * @param conn_interval_max (unit: 1.25ms) 236 * @param conn_latency 237 * @param supervision_timeout (unit: 10ms) 238 * @returns 1 if included 239 */ 240 int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){ 241 if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0; 242 if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0; 243 244 if (le_conn_latency < existing_range->le_conn_latency_min) return 0; 245 if (le_conn_latency > existing_range->le_conn_latency_max) return 0; 246 247 if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0; 248 if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0; 249 250 return 1; 251 } 252 253 /** 254 * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it) 255 * @note: default: 1 256 * @param max_peripheral_connections 257 */ 258 #ifdef ENABLE_LE_PERIPHERAL 259 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){ 260 hci_stack->le_max_number_peripheral_connections = max_peripheral_connections; 261 } 262 #endif 263 264 /** 265 * get hci connections iterator 266 * 267 * @return hci connections iterator 268 */ 269 270 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){ 271 btstack_linked_list_iterator_init(it, &hci_stack->connections); 272 } 273 274 /** 275 * get connection for a given handle 276 * 277 * @return connection OR NULL, if not found 278 */ 279 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){ 280 btstack_linked_list_iterator_t it; 281 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 282 while (btstack_linked_list_iterator_has_next(&it)){ 283 hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 284 if ( item->con_handle == con_handle ) { 285 return item; 286 } 287 } 288 return NULL; 289 } 290 291 /** 292 * get connection for given address 293 * 294 * @return connection OR NULL, if not found 295 */ 296 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){ 297 btstack_linked_list_iterator_t it; 298 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 299 while (btstack_linked_list_iterator_has_next(&it)){ 300 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 301 if (connection->address_type != addr_type) continue; 302 if (memcmp(addr, connection->address, 6) != 0) continue; 303 return connection; 304 } 305 return NULL; 306 } 307 308 309 #ifdef ENABLE_CLASSIC 310 311 #ifdef ENABLE_SCO_OVER_HCI 312 static int hci_number_sco_connections(void){ 313 int connections = 0; 314 btstack_linked_list_iterator_t it; 315 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 316 while (btstack_linked_list_iterator_has_next(&it)){ 317 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 318 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 319 connections++; 320 } 321 return connections; 322 } 323 #endif 324 325 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){ 326 hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer); 327 #ifdef HAVE_EMBEDDED_TICK 328 if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 329 // connections might be timed out 330 hci_emit_l2cap_check_timeout(connection); 331 } 332 #else 333 if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){ 334 // connections might be timed out 335 hci_emit_l2cap_check_timeout(connection); 336 } 337 #endif 338 } 339 340 static void hci_connection_timestamp(hci_connection_t *connection){ 341 #ifdef HAVE_EMBEDDED_TICK 342 connection->timestamp = btstack_run_loop_embedded_get_ticks(); 343 #else 344 connection->timestamp = btstack_run_loop_get_time_ms(); 345 #endif 346 } 347 348 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 349 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags); 350 } 351 352 353 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 354 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags); 355 } 356 357 /** 358 * add authentication flags and reset timer 359 * @note: assumes classic connection 360 * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets 361 */ 362 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 363 bd_addr_t addr; 364 reverse_bd_addr(bd_addr, addr); 365 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 366 if (conn) { 367 connectionSetAuthenticationFlags(conn, flags); 368 hci_connection_timestamp(conn); 369 } 370 } 371 372 int hci_authentication_active_for_handle(hci_con_handle_t handle){ 373 hci_connection_t * conn = hci_connection_for_handle(handle); 374 if (!conn) return 0; 375 if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1; 376 if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1; 377 return 0; 378 } 379 380 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){ 381 if (!hci_stack->link_key_db) return; 382 log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr)); 383 hci_stack->link_key_db->delete_link_key(addr); 384 } 385 386 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){ 387 if (!hci_stack->link_key_db) return; 388 log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type); 389 hci_stack->link_key_db->put_link_key(addr, link_key, type); 390 } 391 392 void gap_delete_all_link_keys(void){ 393 bd_addr_t addr; 394 link_key_t link_key; 395 link_key_type_t type; 396 btstack_link_key_iterator_t it; 397 int ok = gap_link_key_iterator_init(&it); 398 if (!ok) { 399 log_error("could not initialize iterator"); 400 return; 401 } 402 while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){ 403 gap_drop_link_key_for_bd_addr(addr); 404 } 405 gap_link_key_iterator_done(&it); 406 } 407 408 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){ 409 if (!hci_stack->link_key_db) return 0; 410 if (!hci_stack->link_key_db->iterator_init) return 0; 411 return hci_stack->link_key_db->iterator_init(it); 412 } 413 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){ 414 if (!hci_stack->link_key_db) return 0; 415 return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type); 416 } 417 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){ 418 if (!hci_stack->link_key_db) return; 419 hci_stack->link_key_db->iterator_done(it); 420 } 421 #endif 422 423 static int hci_is_le_connection(hci_connection_t * connection){ 424 switch (connection->address_type){ 425 case BD_ADDR_TYPE_LE_PUBLIC: 426 case BD_ADDR_TYPE_LE_RANDOM: 427 case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC: 428 case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM: 429 return 1; 430 default: 431 return 0; 432 } 433 } 434 435 /** 436 * count connections 437 */ 438 static int nr_hci_connections(void){ 439 int count = 0; 440 btstack_linked_item_t *it; 441 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++); 442 return count; 443 } 444 445 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){ 446 447 unsigned int num_packets_sent_classic = 0; 448 unsigned int num_packets_sent_le = 0; 449 450 btstack_linked_item_t *it; 451 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 452 hci_connection_t * connection = (hci_connection_t *) it; 453 if (hci_is_le_connection(connection)){ 454 num_packets_sent_le += connection->num_packets_sent; 455 } 456 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){ 457 num_packets_sent_classic += connection->num_packets_sent; 458 } 459 } 460 log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num); 461 int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic; 462 int free_slots_le = 0; 463 464 if (free_slots_classic < 0){ 465 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); 466 return 0; 467 } 468 469 if (hci_stack->le_acl_packets_total_num){ 470 // if we have LE slots, they are used 471 free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le; 472 if (free_slots_le < 0){ 473 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); 474 return 0; 475 } 476 } else { 477 // otherwise, classic slots are used for LE, too 478 free_slots_classic -= num_packets_sent_le; 479 if (free_slots_classic < 0){ 480 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); 481 return 0; 482 } 483 } 484 485 switch (address_type){ 486 case BD_ADDR_TYPE_UNKNOWN: 487 log_error("hci_number_free_acl_slots: unknown address type"); 488 return 0; 489 490 case BD_ADDR_TYPE_CLASSIC: 491 return free_slots_classic; 492 493 default: 494 if (hci_stack->le_acl_packets_total_num){ 495 return free_slots_le; 496 } 497 return free_slots_classic; 498 } 499 } 500 501 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){ 502 // get connection type 503 hci_connection_t * connection = hci_connection_for_handle(con_handle); 504 if (!connection){ 505 log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle); 506 return 0; 507 } 508 return hci_number_free_acl_slots_for_connection_type(connection->address_type); 509 } 510 511 #ifdef ENABLE_CLASSIC 512 static int hci_number_free_sco_slots(void){ 513 unsigned int num_sco_packets_sent = 0; 514 btstack_linked_item_t *it; 515 if (hci_stack->synchronous_flow_control_enabled){ 516 // explicit flow control 517 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 518 hci_connection_t * connection = (hci_connection_t *) it; 519 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 520 num_sco_packets_sent += connection->num_packets_sent; 521 } 522 if (num_sco_packets_sent > hci_stack->sco_packets_total_num){ 523 log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num); 524 return 0; 525 } 526 return hci_stack->sco_packets_total_num - num_sco_packets_sent; 527 } else { 528 // implicit flow control -- TODO 529 int num_ready = 0; 530 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 531 hci_connection_t * connection = (hci_connection_t *) it; 532 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 533 if (connection->sco_tx_ready == 0) continue; 534 num_ready++; 535 } 536 return num_ready; 537 } 538 } 539 #endif 540 541 // only used to send HCI Host Number Completed Packets 542 static int hci_can_send_comand_packet_transport(void){ 543 if (hci_stack->hci_packet_buffer_reserved) return 0; 544 545 // check for async hci transport implementations 546 if (hci_stack->hci_transport->can_send_packet_now){ 547 if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){ 548 return 0; 549 } 550 } 551 return 1; 552 } 553 554 // new functions replacing hci_can_send_packet_now[_using_packet_buffer] 555 int hci_can_send_command_packet_now(void){ 556 if (hci_can_send_comand_packet_transport() == 0) return 0; 557 return hci_stack->num_cmd_packets > 0; 558 } 559 560 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){ 561 // check for async hci transport implementations 562 if (!hci_stack->hci_transport->can_send_packet_now) return 1; 563 return hci_stack->hci_transport->can_send_packet_now(packet_type); 564 } 565 566 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){ 567 if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0; 568 return hci_number_free_acl_slots_for_connection_type(address_type) > 0; 569 } 570 571 int hci_can_send_acl_le_packet_now(void){ 572 if (hci_stack->hci_packet_buffer_reserved) return 0; 573 return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC); 574 } 575 576 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) { 577 if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0; 578 return hci_number_free_acl_slots_for_handle(con_handle) > 0; 579 } 580 581 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){ 582 if (hci_stack->hci_packet_buffer_reserved) return 0; 583 return hci_can_send_prepared_acl_packet_now(con_handle); 584 } 585 586 #ifdef ENABLE_CLASSIC 587 int hci_can_send_acl_classic_packet_now(void){ 588 if (hci_stack->hci_packet_buffer_reserved) return 0; 589 return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC); 590 } 591 592 int hci_can_send_prepared_sco_packet_now(void){ 593 if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0; 594 if (hci_have_usb_transport()){ 595 return hci_stack->sco_can_send_now; 596 } else { 597 return hci_number_free_sco_slots() > 0; 598 } 599 } 600 601 int hci_can_send_sco_packet_now(void){ 602 if (hci_stack->hci_packet_buffer_reserved) return 0; 603 return hci_can_send_prepared_sco_packet_now(); 604 } 605 606 void hci_request_sco_can_send_now_event(void){ 607 hci_stack->sco_waiting_for_can_send_now = 1; 608 hci_notify_if_sco_can_send_now(); 609 } 610 #endif 611 612 // used for internal checks in l2cap.c 613 int hci_is_packet_buffer_reserved(void){ 614 return hci_stack->hci_packet_buffer_reserved; 615 } 616 617 // reserves outgoing packet buffer. @returns 1 if successful 618 int hci_reserve_packet_buffer(void){ 619 if (hci_stack->hci_packet_buffer_reserved) { 620 log_error("hci_reserve_packet_buffer called but buffer already reserved"); 621 return 0; 622 } 623 hci_stack->hci_packet_buffer_reserved = 1; 624 return 1; 625 } 626 627 void hci_release_packet_buffer(void){ 628 hci_stack->hci_packet_buffer_reserved = 0; 629 } 630 631 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call 632 static int hci_transport_synchronous(void){ 633 return hci_stack->hci_transport->can_send_packet_now == NULL; 634 } 635 636 static int hci_send_acl_packet_fragments(hci_connection_t *connection){ 637 638 // 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); 639 640 // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers 641 uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length; 642 if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){ 643 max_acl_data_packet_length = hci_stack->le_data_packets_length; 644 } 645 646 // testing: reduce buffer to minimum 647 // max_acl_data_packet_length = 52; 648 649 log_debug("hci_send_acl_packet_fragments entered"); 650 651 int err; 652 // multiple packets could be send on a synchronous HCI transport 653 while (1){ 654 655 log_debug("hci_send_acl_packet_fragments loop entered"); 656 657 // get current data 658 const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4; 659 int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos; 660 int more_fragments = 0; 661 662 // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length 663 if (current_acl_data_packet_length > max_acl_data_packet_length){ 664 more_fragments = 1; 665 current_acl_data_packet_length = max_acl_data_packet_length; 666 } 667 668 // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent) 669 if (acl_header_pos > 0){ 670 uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 671 handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12); 672 little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags); 673 } 674 675 // update header len 676 little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length); 677 678 // count packet 679 connection->num_packets_sent++; 680 log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments); 681 682 // update state for next fragment (if any) as "transport done" might be sent during send_packet already 683 if (more_fragments){ 684 // update start of next fragment to send 685 hci_stack->acl_fragmentation_pos += current_acl_data_packet_length; 686 } else { 687 // done 688 hci_stack->acl_fragmentation_pos = 0; 689 hci_stack->acl_fragmentation_total_size = 0; 690 } 691 692 // send packet 693 uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos]; 694 const int size = current_acl_data_packet_length + 4; 695 hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size); 696 hci_stack->acl_fragmentation_tx_active = 1; 697 err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 698 699 log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments); 700 701 // done yet? 702 if (!more_fragments) break; 703 704 // can send more? 705 if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err; 706 } 707 708 log_debug("hci_send_acl_packet_fragments loop over"); 709 710 // release buffer now for synchronous transport 711 if (hci_transport_synchronous()){ 712 hci_stack->acl_fragmentation_tx_active = 0; 713 hci_release_packet_buffer(); 714 hci_emit_transport_packet_sent(); 715 } 716 717 return err; 718 } 719 720 // pre: caller has reserved the packet buffer 721 int hci_send_acl_packet_buffer(int size){ 722 723 // log_info("hci_send_acl_packet_buffer size %u", size); 724 725 if (!hci_stack->hci_packet_buffer_reserved) { 726 log_error("hci_send_acl_packet_buffer called without reserving packet buffer"); 727 return 0; 728 } 729 730 uint8_t * packet = hci_stack->hci_packet_buffer; 731 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 732 733 // check for free places on Bluetooth module 734 if (!hci_can_send_prepared_acl_packet_now(con_handle)) { 735 log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller"); 736 hci_release_packet_buffer(); 737 hci_emit_transport_packet_sent(); 738 return BTSTACK_ACL_BUFFERS_FULL; 739 } 740 741 hci_connection_t *connection = hci_connection_for_handle( con_handle); 742 if (!connection) { 743 log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle); 744 hci_release_packet_buffer(); 745 hci_emit_transport_packet_sent(); 746 return 0; 747 } 748 749 #ifdef ENABLE_CLASSIC 750 hci_connection_timestamp(connection); 751 #endif 752 753 // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size); 754 755 // setup data 756 hci_stack->acl_fragmentation_total_size = size; 757 hci_stack->acl_fragmentation_pos = 4; // start of L2CAP packet 758 759 return hci_send_acl_packet_fragments(connection); 760 } 761 762 #ifdef ENABLE_CLASSIC 763 // pre: caller has reserved the packet buffer 764 int hci_send_sco_packet_buffer(int size){ 765 766 // log_info("hci_send_acl_packet_buffer size %u", size); 767 768 if (!hci_stack->hci_packet_buffer_reserved) { 769 log_error("hci_send_acl_packet_buffer called without reserving packet buffer"); 770 return 0; 771 } 772 773 uint8_t * packet = hci_stack->hci_packet_buffer; 774 775 // skip checks in loopback mode 776 if (!hci_stack->loopback_mode){ 777 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); // same for ACL and SCO 778 779 // check for free places on Bluetooth module 780 if (!hci_can_send_prepared_sco_packet_now()) { 781 log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller"); 782 hci_release_packet_buffer(); 783 hci_emit_transport_packet_sent(); 784 return BTSTACK_ACL_BUFFERS_FULL; 785 } 786 787 // track send packet in connection struct 788 hci_connection_t *connection = hci_connection_for_handle( con_handle); 789 if (!connection) { 790 log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle); 791 hci_release_packet_buffer(); 792 hci_emit_transport_packet_sent(); 793 return 0; 794 } 795 796 if (hci_have_usb_transport()){ 797 // token used 798 hci_stack->sco_can_send_now = 0; 799 } else { 800 if (hci_stack->synchronous_flow_control_enabled){ 801 connection->num_packets_sent++; 802 } else { 803 connection->sco_tx_ready--; 804 } 805 } 806 } 807 808 hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size); 809 int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size); 810 811 if (hci_transport_synchronous()){ 812 hci_release_packet_buffer(); 813 hci_emit_transport_packet_sent(); 814 } 815 816 return err; 817 } 818 #endif 819 820 static void acl_handler(uint8_t *packet, int size){ 821 822 // log_info("acl_handler: size %u", size); 823 824 // get info 825 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 826 hci_connection_t *conn = hci_connection_for_handle(con_handle); 827 uint8_t acl_flags = READ_ACL_FLAGS(packet); 828 uint16_t acl_length = READ_ACL_LENGTH(packet); 829 830 // ignore non-registered handle 831 if (!conn){ 832 log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle); 833 return; 834 } 835 836 // assert packet is complete 837 if (acl_length + 4 != size){ 838 log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4); 839 return; 840 } 841 842 #ifdef ENABLE_CLASSIC 843 // update idle timestamp 844 hci_connection_timestamp(conn); 845 #endif 846 847 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 848 hci_stack->host_completed_packets = 1; 849 conn->num_packets_completed++; 850 #endif 851 852 // handle different packet types 853 switch (acl_flags & 0x03) { 854 855 case 0x01: // continuation fragment 856 857 // sanity checks 858 if (conn->acl_recombination_pos == 0) { 859 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle); 860 return; 861 } 862 if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){ 863 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x", 864 conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle); 865 conn->acl_recombination_pos = 0; 866 return; 867 } 868 869 // append fragment payload (header already stored) 870 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length ); 871 conn->acl_recombination_pos += acl_length; 872 873 // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length, 874 // conn->acl_recombination_pos, conn->acl_recombination_length); 875 876 // forward complete L2CAP packet if complete. 877 if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header 878 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos); 879 // reset recombination buffer 880 conn->acl_recombination_length = 0; 881 conn->acl_recombination_pos = 0; 882 } 883 break; 884 885 case 0x02: { // first fragment 886 887 // sanity check 888 if (conn->acl_recombination_pos) { 889 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle); 890 conn->acl_recombination_pos = 0; 891 } 892 893 // peek into L2CAP packet! 894 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 895 896 // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length); 897 898 // compare fragment size to L2CAP packet size 899 if (acl_length >= l2cap_length + 4){ 900 // forward fragment as L2CAP packet 901 hci_emit_acl_packet(packet, acl_length + 4); 902 } else { 903 904 if (acl_length > HCI_ACL_BUFFER_SIZE){ 905 log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x", 906 4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle); 907 return; 908 } 909 910 // store first fragment and tweak acl length for complete package 911 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4); 912 conn->acl_recombination_pos = acl_length + 4; 913 conn->acl_recombination_length = l2cap_length; 914 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4); 915 } 916 break; 917 918 } 919 default: 920 log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03); 921 return; 922 } 923 924 // execute main loop 925 hci_run(); 926 } 927 928 static void hci_shutdown_connection(hci_connection_t *conn){ 929 log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address)); 930 931 #ifdef ENABLE_CLASSIC 932 #ifdef ENABLE_SCO_OVER_HCI 933 int addr_type = conn->address_type; 934 #endif 935 #endif 936 937 btstack_run_loop_remove_timer(&conn->timeout); 938 939 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 940 btstack_memory_hci_connection_free( conn ); 941 942 // now it's gone 943 hci_emit_nr_connections_changed(); 944 945 #ifdef ENABLE_CLASSIC 946 #ifdef ENABLE_SCO_OVER_HCI 947 // update SCO 948 if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){ 949 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections()); 950 } 951 #endif 952 #endif 953 } 954 955 #ifdef ENABLE_CLASSIC 956 957 static const uint16_t packet_type_sizes[] = { 958 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 959 HCI_ACL_DH1_SIZE, 0, 0, 0, 960 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 961 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 962 }; 963 static const uint8_t packet_type_feature_requirement_bit[] = { 964 0, // 3 slot packets 965 1, // 5 slot packets 966 25, // EDR 2 mpbs 967 26, // EDR 3 mbps 968 39, // 3 slot EDR packts 969 40, // 5 slot EDR packet 970 }; 971 static const uint16_t packet_type_feature_packet_mask[] = { 972 0x0f00, // 3 slot packets 973 0xf000, // 5 slot packets 974 0x1102, // EDR 2 mpbs 975 0x2204, // EDR 3 mbps 976 0x0300, // 3 slot EDR packts 977 0x3000, // 5 slot EDR packet 978 }; 979 980 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){ 981 // enable packet types based on size 982 uint16_t packet_types = 0; 983 unsigned int i; 984 for (i=0;i<16;i++){ 985 if (packet_type_sizes[i] == 0) continue; 986 if (packet_type_sizes[i] <= buffer_size){ 987 packet_types |= 1 << i; 988 } 989 } 990 // disable packet types due to missing local supported features 991 for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){ 992 unsigned int bit_idx = packet_type_feature_requirement_bit[i]; 993 int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0; 994 if (feature_set) continue; 995 log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]); 996 packet_types &= ~packet_type_feature_packet_mask[i]; 997 } 998 // flip bits for "may not be used" 999 packet_types ^= 0x3306; 1000 return packet_types; 1001 } 1002 1003 uint16_t hci_usable_acl_packet_types(void){ 1004 return hci_stack->packet_types; 1005 } 1006 #endif 1007 1008 uint8_t* hci_get_outgoing_packet_buffer(void){ 1009 // hci packet buffer is >= acl data packet length 1010 return hci_stack->hci_packet_buffer; 1011 } 1012 1013 uint16_t hci_max_acl_data_packet_length(void){ 1014 return hci_stack->acl_data_packet_length; 1015 } 1016 1017 #ifdef ENABLE_CLASSIC 1018 int hci_extended_sco_link_supported(void){ 1019 // No. 31, byte 3, bit 7 1020 return (hci_stack->local_supported_features[3] & (1 << 7)) != 0; 1021 } 1022 #endif 1023 1024 int hci_non_flushable_packet_boundary_flag_supported(void){ 1025 // No. 54, byte 6, bit 6 1026 return (hci_stack->local_supported_features[6] & (1 << 6)) != 0; 1027 } 1028 1029 static int gap_ssp_supported(void){ 1030 // No. 51, byte 6, bit 3 1031 return (hci_stack->local_supported_features[6] & (1 << 3)) != 0; 1032 } 1033 1034 static int hci_classic_supported(void){ 1035 #ifdef ENABLE_CLASSIC 1036 // No. 37, byte 4, bit 5, = No BR/EDR Support 1037 return (hci_stack->local_supported_features[4] & (1 << 5)) == 0; 1038 #else 1039 return 0; 1040 #endif 1041 } 1042 1043 static int hci_le_supported(void){ 1044 #ifdef ENABLE_BLE 1045 // No. 37, byte 4, bit 6 = LE Supported (Controller) 1046 return (hci_stack->local_supported_features[4] & (1 << 6)) != 0; 1047 #else 1048 return 0; 1049 #endif 1050 } 1051 1052 #ifdef ENABLE_BLE 1053 1054 /** 1055 * @brief Get addr type and address used for LE in Advertisements, Scan Responses, 1056 */ 1057 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){ 1058 *addr_type = hci_stack->le_own_addr_type; 1059 if (hci_stack->le_own_addr_type){ 1060 memcpy(addr, hci_stack->le_random_address, 6); 1061 } else { 1062 memcpy(addr, hci_stack->local_bd_addr, 6); 1063 } 1064 } 1065 1066 #ifdef ENABLE_LE_CENTRAL 1067 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){ 1068 1069 int offset = 3; 1070 int num_reports = packet[offset]; 1071 offset += 1; 1072 1073 int i; 1074 // log_info("HCI: handle adv report with num reports: %d", num_reports); 1075 uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var 1076 for (i=0; i<num_reports && offset < size;i++){ 1077 // sanity checks on data_length: 1078 uint8_t data_length = packet[offset + 8]; 1079 if (data_length > LE_ADVERTISING_DATA_SIZE) return; 1080 if (offset + 9 + data_length + 1 > size) return; 1081 // setup event 1082 uint8_t event_size = 10 + data_length; 1083 int pos = 0; 1084 event[pos++] = GAP_EVENT_ADVERTISING_REPORT; 1085 event[pos++] = event_size; 1086 memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address 1087 offset += 8; 1088 pos += 8; 1089 event[pos++] = packet[offset + 1 + data_length]; // rssi 1090 event[pos++] = data_length; 1091 offset++; 1092 memcpy(&event[pos], &packet[offset], data_length); 1093 pos += data_length; 1094 offset += data_length + 1; // rssi 1095 hci_emit_event(event, pos, 1); 1096 } 1097 } 1098 #endif 1099 #endif 1100 1101 #ifdef ENABLE_BLE 1102 #ifdef ENABLE_LE_PERIPHERAL 1103 static void hci_reenable_advertisements_if_needed(void){ 1104 if (!hci_stack->le_advertisements_active && hci_stack->le_advertisements_enabled){ 1105 // get number of active le slave connections 1106 int num_slave_connections = 0; 1107 btstack_linked_list_iterator_t it; 1108 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 1109 while (btstack_linked_list_iterator_has_next(&it)){ 1110 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 1111 log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con)); 1112 if (con->state != OPEN) continue; 1113 if (con->role != HCI_ROLE_SLAVE) continue; 1114 if (!hci_is_le_connection(con)) continue; 1115 num_slave_connections++; 1116 } 1117 log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections); 1118 if (num_slave_connections < hci_stack->le_max_number_peripheral_connections){ 1119 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE; 1120 } 1121 } 1122 } 1123 #endif 1124 #endif 1125 1126 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 1127 1128 static uint32_t hci_transport_uart_get_main_baud_rate(void){ 1129 if (!hci_stack->config) return 0; 1130 uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 1131 // Limit baud rate for Broadcom chipsets to 3 mbps 1132 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){ 1133 baud_rate = 3000000; 1134 } 1135 return baud_rate; 1136 } 1137 1138 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){ 1139 UNUSED(ds); 1140 1141 switch (hci_stack->substate){ 1142 case HCI_INIT_W4_SEND_RESET: 1143 log_info("Resend HCI Reset"); 1144 hci_stack->substate = HCI_INIT_SEND_RESET; 1145 hci_stack->num_cmd_packets = 1; 1146 hci_run(); 1147 break; 1148 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET: 1149 log_info("Resend HCI Reset - CSR Warm Boot with Link Reset"); 1150 if (hci_stack->hci_transport->reset_link){ 1151 hci_stack->hci_transport->reset_link(); 1152 } 1153 // no break - explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT 1154 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT: 1155 log_info("Resend HCI Reset - CSR Warm Boot"); 1156 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT; 1157 hci_stack->num_cmd_packets = 1; 1158 hci_run(); 1159 break; 1160 case HCI_INIT_W4_SEND_BAUD_CHANGE: 1161 if (hci_stack->hci_transport->set_baudrate){ 1162 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1163 log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate); 1164 hci_stack->hci_transport->set_baudrate(baud_rate); 1165 } 1166 // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP 1167 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){ 1168 if (hci_stack->hci_transport->reset_link){ 1169 log_info("Link Reset"); 1170 hci_stack->hci_transport->reset_link(); 1171 } 1172 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT; 1173 hci_run(); 1174 } 1175 break; 1176 case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY: 1177 // otherwise continue 1178 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS; 1179 hci_send_cmd(&hci_read_local_supported_commands); 1180 break; 1181 default: 1182 break; 1183 } 1184 } 1185 #endif 1186 1187 static void hci_initializing_next_state(void){ 1188 hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1); 1189 } 1190 1191 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_PERIPHERAL) 1192 static void hci_replace_bd_addr_placeholder(uint8_t * data, uint16_t size){ 1193 const int bd_addr_string_len = 17; 1194 int i = 0; 1195 while (i < size - bd_addr_string_len){ 1196 if (memcmp(&data[i], "00:00:00:00:00:00", bd_addr_string_len)) { 1197 i++; 1198 continue; 1199 } 1200 // set real address 1201 memcpy(&data[i], bd_addr_to_str(hci_stack->local_bd_addr), bd_addr_string_len); 1202 i += bd_addr_string_len; 1203 } 1204 } 1205 #endif 1206 1207 // assumption: hci_can_send_command_packet_now() == true 1208 static void hci_initializing_run(void){ 1209 log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now()); 1210 switch (hci_stack->substate){ 1211 case HCI_INIT_SEND_RESET: 1212 hci_state_reset(); 1213 1214 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 1215 // prepare reset if command complete not received in 100ms 1216 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1217 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1218 btstack_run_loop_add_timer(&hci_stack->timeout); 1219 #endif 1220 // send command 1221 hci_stack->substate = HCI_INIT_W4_SEND_RESET; 1222 hci_send_cmd(&hci_reset); 1223 break; 1224 case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION: 1225 hci_send_cmd(&hci_read_local_version_information); 1226 hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION; 1227 break; 1228 case HCI_INIT_SEND_READ_LOCAL_NAME: 1229 hci_send_cmd(&hci_read_local_name); 1230 hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME; 1231 break; 1232 1233 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 1234 case HCI_INIT_SEND_RESET_CSR_WARM_BOOT: 1235 hci_state_reset(); 1236 // prepare reset if command complete not received in 100ms 1237 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1238 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1239 btstack_run_loop_add_timer(&hci_stack->timeout); 1240 // send command 1241 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT; 1242 hci_send_cmd(&hci_reset); 1243 break; 1244 case HCI_INIT_SEND_RESET_ST_WARM_BOOT: 1245 hci_state_reset(); 1246 hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT; 1247 hci_send_cmd(&hci_reset); 1248 break; 1249 case HCI_INIT_SEND_BAUD_CHANGE: { 1250 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1251 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer); 1252 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1253 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE; 1254 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]); 1255 // STLC25000D: baudrate change happens within 0.5 s after command was send, 1256 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial) 1257 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){ 1258 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1259 btstack_run_loop_add_timer(&hci_stack->timeout); 1260 } 1261 break; 1262 } 1263 case HCI_INIT_SEND_BAUD_CHANGE_BCM: { 1264 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1265 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer); 1266 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1267 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM; 1268 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]); 1269 break; 1270 } 1271 case HCI_INIT_CUSTOM_INIT: 1272 // Custom initialization 1273 if (hci_stack->chipset && hci_stack->chipset->next_command){ 1274 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer); 1275 int send_cmd = 0; 1276 switch (hci_stack->chipset_result){ 1277 case BTSTACK_CHIPSET_VALID_COMMAND: 1278 send_cmd = 1; 1279 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT; 1280 break; 1281 case BTSTACK_CHIPSET_WARMSTART_REQUIRED: 1282 send_cmd = 1; 1283 // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete 1284 log_info("CSR Warm Boot"); 1285 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1286 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1287 btstack_run_loop_add_timer(&hci_stack->timeout); 1288 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO 1289 && hci_stack->config 1290 && hci_stack->chipset 1291 // && hci_stack->chipset->set_baudrate_command -- there's no such command 1292 && hci_stack->hci_transport->set_baudrate 1293 && hci_transport_uart_get_main_baud_rate()){ 1294 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE; 1295 } else { 1296 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET; 1297 } 1298 break; 1299 default: 1300 break; 1301 } 1302 1303 if (send_cmd){ 1304 int size = 3 + hci_stack->hci_packet_buffer[2]; 1305 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1306 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size); 1307 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size); 1308 break; 1309 } 1310 log_info("Init script done"); 1311 1312 // Init script download on Broadcom chipsets causes: 1313 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) && 1314 ( hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION 1315 || hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA) ){ 1316 1317 // - baud rate to reset, restore UART baud rate if needed 1318 int need_baud_change = hci_stack->config 1319 && hci_stack->chipset 1320 && hci_stack->chipset->set_baudrate_command 1321 && hci_stack->hci_transport->set_baudrate 1322 && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 1323 if (need_baud_change) { 1324 uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init; 1325 log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate); 1326 hci_stack->hci_transport->set_baudrate(baud_rate); 1327 } 1328 1329 // - RTS will raise during update, but manual RTS/CTS in WICED port on RedBear Duo cannot handle this 1330 // -> Work around: wait a few milliseconds here. 1331 log_info("BCM delay after init script"); 1332 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY; 1333 btstack_run_loop_set_timer(&hci_stack->timeout, 10); 1334 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1335 btstack_run_loop_add_timer(&hci_stack->timeout); 1336 break; 1337 } 1338 } 1339 // otherwise continue 1340 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS; 1341 hci_send_cmd(&hci_read_local_supported_commands); 1342 break; 1343 case HCI_INIT_SET_BD_ADDR: 1344 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr)); 1345 hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer); 1346 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1347 hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR; 1348 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]); 1349 break; 1350 #endif 1351 1352 case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS: 1353 log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset"); 1354 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS; 1355 hci_send_cmd(&hci_read_local_supported_commands); 1356 break; 1357 case HCI_INIT_READ_BD_ADDR: 1358 hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR; 1359 hci_send_cmd(&hci_read_bd_addr); 1360 break; 1361 case HCI_INIT_READ_BUFFER_SIZE: 1362 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE; 1363 hci_send_cmd(&hci_read_buffer_size); 1364 break; 1365 case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES: 1366 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES; 1367 hci_send_cmd(&hci_read_local_supported_features); 1368 break; 1369 1370 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 1371 case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL: 1372 hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL; 1373 hci_send_cmd(&hci_set_controller_to_host_flow_control, 3); // ACL + SCO Flow Control 1374 break; 1375 case HCI_INIT_HOST_BUFFER_SIZE: 1376 hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE; 1377 hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN, 1378 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM); 1379 break; 1380 #endif 1381 1382 case HCI_INIT_SET_EVENT_MASK: 1383 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK; 1384 if (hci_le_supported()){ 1385 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF); 1386 } else { 1387 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 1388 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF); 1389 } 1390 break; 1391 1392 #ifdef ENABLE_CLASSIC 1393 case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE: 1394 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE; 1395 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable); 1396 break; 1397 case HCI_INIT_WRITE_PAGE_TIMEOUT: 1398 hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT; 1399 hci_send_cmd(&hci_write_page_timeout, 0x6000); // ca. 15 sec 1400 break; 1401 case HCI_INIT_WRITE_DEFAULT_LINK_POLICY_SETTING: 1402 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_LINK_POLICY_SETTING; 1403 hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings); 1404 break; 1405 case HCI_INIT_WRITE_CLASS_OF_DEVICE: 1406 hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE; 1407 hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device); 1408 break; 1409 case HCI_INIT_WRITE_LOCAL_NAME: { 1410 hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME; 1411 hci_reserve_packet_buffer(); 1412 uint8_t * packet = hci_stack->hci_packet_buffer; 1413 // construct HCI Command and send 1414 uint16_t opcode = hci_write_local_name.opcode; 1415 hci_stack->last_cmd_opcode = opcode; 1416 packet[0] = opcode & 0xff; 1417 packet[1] = opcode >> 8; 1418 packet[2] = DEVICE_NAME_LEN; 1419 memset(&packet[3], 0, DEVICE_NAME_LEN); 1420 memcpy(&packet[3], hci_stack->local_name, strlen(hci_stack->local_name)); 1421 // expand '00:00:00:00:00:00' in name with bd_addr 1422 hci_replace_bd_addr_placeholder(&packet[3], DEVICE_NAME_LEN); 1423 hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN); 1424 break; 1425 } 1426 case HCI_INIT_WRITE_EIR_DATA: { 1427 hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA; 1428 hci_reserve_packet_buffer(); 1429 uint8_t * packet = hci_stack->hci_packet_buffer; 1430 // construct HCI Command and send 1431 uint16_t opcode = hci_write_extended_inquiry_response.opcode; 1432 hci_stack->last_cmd_opcode = opcode; 1433 packet[0] = opcode & 0xff; 1434 packet[1] = opcode >> 8; 1435 packet[2] = 1 + 240; 1436 packet[3] = 0; // FEC not required 1437 if (hci_stack->eir_data){ 1438 memcpy(&packet[4], hci_stack->eir_data, 240); 1439 } else { 1440 memset(&packet[4], 0, 240); 1441 int name_len = strlen(hci_stack->local_name); 1442 packet[4] = name_len + 1; 1443 packet[5] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME; 1444 memcpy(&packet[6], hci_stack->local_name, name_len); 1445 } 1446 // expand '00:00:00:00:00:00' in name with bd_addr 1447 hci_replace_bd_addr_placeholder(&packet[4], 240); 1448 hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + 240); 1449 break; 1450 } 1451 case HCI_INIT_WRITE_INQUIRY_MODE: 1452 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE; 1453 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode); 1454 break; 1455 case HCI_INIT_WRITE_SCAN_ENABLE: 1456 hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan 1457 hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE; 1458 break; 1459 // only sent if ENABLE_SCO_OVER_HCI is defined 1460 case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE: 1461 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE; 1462 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled 1463 break; 1464 case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING: 1465 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING; 1466 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1); 1467 break; 1468 // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom 1469 case HCI_INIT_BCM_WRITE_SCO_PCM_INT: 1470 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT; 1471 log_info("BCM: Route SCO data via HCI transport"); 1472 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0); 1473 break; 1474 1475 #endif 1476 #ifdef ENABLE_BLE 1477 // LE INIT 1478 case HCI_INIT_LE_READ_BUFFER_SIZE: 1479 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE; 1480 hci_send_cmd(&hci_le_read_buffer_size); 1481 break; 1482 case HCI_INIT_LE_SET_EVENT_MASK: 1483 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK; 1484 hci_send_cmd(&hci_le_set_event_mask, 0x809FF, 0x0); // bits 0-8, 11, 19 1485 break; 1486 case HCI_INIT_WRITE_LE_HOST_SUPPORTED: 1487 // LE Supported Host = 1, Simultaneous Host = 0 1488 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED; 1489 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 1490 break; 1491 #endif 1492 1493 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION 1494 case HCI_INIT_LE_READ_MAX_DATA_LENGTH: 1495 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH; 1496 hci_send_cmd(&hci_le_read_maximum_data_length); 1497 break; 1498 case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH: 1499 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH; 1500 hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time); 1501 break; 1502 #endif 1503 1504 #ifdef ENABLE_LE_CENTRAL 1505 case HCI_INIT_READ_WHITE_LIST_SIZE: 1506 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE; 1507 hci_send_cmd(&hci_le_read_white_list_size); 1508 break; 1509 case HCI_INIT_LE_SET_SCAN_PARAMETERS: 1510 // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs 1511 hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS; 1512 hci_send_cmd(&hci_le_set_scan_parameters, 1, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, 0); 1513 break; 1514 #endif 1515 default: 1516 return; 1517 } 1518 } 1519 1520 static void hci_init_done(void){ 1521 // done. tell the app 1522 log_info("hci_init_done -> HCI_STATE_WORKING"); 1523 hci_stack->state = HCI_STATE_WORKING; 1524 hci_emit_state(); 1525 hci_run(); 1526 } 1527 1528 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){ 1529 1530 UNUSED(size); // ok: less than 6 bytes are read from our buffer 1531 1532 uint8_t command_completed = 0; 1533 1534 if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){ 1535 uint16_t opcode = little_endian_read_16(packet,3); 1536 if (opcode == hci_stack->last_cmd_opcode){ 1537 command_completed = 1; 1538 log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate); 1539 } else { 1540 log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate); 1541 } 1542 } 1543 1544 if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){ 1545 uint8_t status = packet[2]; 1546 uint16_t opcode = little_endian_read_16(packet,4); 1547 if (opcode == hci_stack->last_cmd_opcode){ 1548 if (status){ 1549 command_completed = 1; 1550 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate); 1551 } else { 1552 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode); 1553 } 1554 } else { 1555 log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 1556 } 1557 } 1558 1559 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 1560 1561 // Vendor == CSR 1562 if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){ 1563 // TODO: track actual command 1564 command_completed = 1; 1565 } 1566 1567 // Vendor == Toshiba 1568 if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){ 1569 // TODO: track actual command 1570 command_completed = 1; 1571 // Fix: no HCI Command Complete received, so num_cmd_packets not reset 1572 hci_stack->num_cmd_packets = 1; 1573 } 1574 1575 // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661: 1576 // Command complete for HCI Reset arrives after we've resent the HCI Reset command 1577 // 1578 // HCI Reset 1579 // Timeout 100 ms 1580 // HCI Reset 1581 // Command Complete Reset 1582 // HCI Read Local Version Information 1583 // Command Complete Reset - but we expected Command Complete Read Local Version Information 1584 // hang... 1585 // 1586 // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend 1587 if (!command_completed 1588 && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE 1589 && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){ 1590 1591 uint16_t opcode = little_endian_read_16(packet,3); 1592 if (opcode == hci_reset.opcode){ 1593 hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION; 1594 return; 1595 } 1596 } 1597 1598 // CSR & H5 1599 // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend 1600 if (!command_completed 1601 && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE 1602 && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){ 1603 1604 uint16_t opcode = little_endian_read_16(packet,3); 1605 if (opcode == hci_reset.opcode){ 1606 hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS; 1607 return; 1608 } 1609 } 1610 1611 // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT 1612 // fix: Correct substate and behave as command below 1613 if (command_completed){ 1614 switch (hci_stack->substate){ 1615 case HCI_INIT_SEND_RESET: 1616 hci_stack->substate = HCI_INIT_W4_SEND_RESET; 1617 break; 1618 case HCI_INIT_SEND_RESET_CSR_WARM_BOOT: 1619 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT; 1620 break; 1621 default: 1622 break; 1623 } 1624 } 1625 1626 #endif 1627 1628 if (!command_completed) return; 1629 1630 int need_baud_change = 0; 1631 int need_addr_change = 0; 1632 1633 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 1634 need_baud_change = hci_stack->config 1635 && hci_stack->chipset 1636 && hci_stack->chipset->set_baudrate_command 1637 && hci_stack->hci_transport->set_baudrate 1638 && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 1639 1640 need_addr_change = hci_stack->custom_bd_addr_set 1641 && hci_stack->chipset 1642 && hci_stack->chipset->set_bd_addr_command; 1643 #endif 1644 1645 switch(hci_stack->substate){ 1646 1647 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 1648 case HCI_INIT_SEND_RESET: 1649 // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET 1650 // fix: just correct substate and behave as command below 1651 hci_stack->substate = HCI_INIT_W4_SEND_RESET; 1652 btstack_run_loop_remove_timer(&hci_stack->timeout); 1653 break; 1654 case HCI_INIT_W4_SEND_RESET: 1655 btstack_run_loop_remove_timer(&hci_stack->timeout); 1656 break; 1657 case HCI_INIT_W4_SEND_READ_LOCAL_NAME: 1658 log_info("Received local name, need baud change %d", need_baud_change); 1659 if (need_baud_change){ 1660 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE; 1661 return; 1662 } 1663 // skip baud change 1664 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1665 return; 1666 case HCI_INIT_W4_SEND_BAUD_CHANGE: 1667 // for STLC2500D, baud rate change already happened. 1668 // for others, baud rate gets changed now 1669 if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){ 1670 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1671 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate); 1672 hci_stack->hci_transport->set_baudrate(baud_rate); 1673 } 1674 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1675 return; 1676 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT: 1677 btstack_run_loop_remove_timer(&hci_stack->timeout); 1678 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1679 return; 1680 case HCI_INIT_W4_CUSTOM_INIT: 1681 // repeat custom init 1682 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 1683 return; 1684 #else 1685 case HCI_INIT_W4_SEND_RESET: 1686 hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS; 1687 return ; 1688 #endif 1689 1690 case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS: 1691 if (need_baud_change && hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT && 1692 ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) || 1693 (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) { 1694 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM; 1695 return; 1696 } 1697 if (need_addr_change){ 1698 hci_stack->substate = HCI_INIT_SET_BD_ADDR; 1699 return; 1700 } 1701 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 1702 return; 1703 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 1704 case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM: 1705 if (need_baud_change){ 1706 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1707 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate); 1708 hci_stack->hci_transport->set_baudrate(baud_rate); 1709 } 1710 if (need_addr_change){ 1711 hci_stack->substate = HCI_INIT_SET_BD_ADDR; 1712 return; 1713 } 1714 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 1715 return; 1716 case HCI_INIT_W4_SET_BD_ADDR: 1717 // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command 1718 if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) 1719 || (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){ 1720 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT; 1721 return; 1722 } 1723 // skipping st warm boot 1724 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 1725 return; 1726 case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT: 1727 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 1728 return; 1729 #endif 1730 case HCI_INIT_W4_READ_BD_ADDR: 1731 // only read buffer size if supported 1732 if (hci_stack->local_supported_commands[0] & 0x01) { 1733 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE; 1734 return; 1735 } 1736 // skipping read buffer size 1737 hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES; 1738 return; 1739 case HCI_INIT_W4_SET_EVENT_MASK: 1740 // skip Classic init commands for LE only chipsets 1741 if (!hci_classic_supported()){ 1742 #ifdef ENABLE_BLE 1743 if (hci_le_supported()){ 1744 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command 1745 return; 1746 } 1747 #endif 1748 log_error("Neither BR/EDR nor LE supported"); 1749 hci_init_done(); 1750 return; 1751 } 1752 if (!gap_ssp_supported()){ 1753 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT; 1754 return; 1755 } 1756 break; 1757 #ifdef ENABLE_BLE 1758 case HCI_INIT_W4_LE_READ_BUFFER_SIZE: 1759 // skip write le host if not supported (e.g. on LE only EM9301) 1760 if (hci_stack->local_supported_commands[0] & 0x02) break; 1761 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK; 1762 return; 1763 1764 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION 1765 case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED: 1766 log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30); 1767 if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){ 1768 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK; 1769 return; 1770 } 1771 // explicit fall through to reduce repetitions 1772 1773 #ifdef ENABLE_LE_CENTRAL 1774 hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE; 1775 #else 1776 hci_init_done(); 1777 #endif 1778 return; 1779 #endif /* ENABLE_LE_DATA_LENGTH_EXTENSION */ 1780 1781 #endif /* ENABLE_BLE */ 1782 1783 #ifdef ENABLE_SCO_OVER_HCI 1784 case HCI_INIT_W4_WRITE_SCAN_ENABLE: 1785 // skip write synchronous flow control if not supported 1786 if (hci_stack->local_supported_commands[0] & 0x04) break; 1787 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE; 1788 // explicit fall through to reduce repetitions 1789 1790 case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE: 1791 // skip write default erroneous data reporting if not supported 1792 if (hci_stack->local_supported_commands[0] & 0x08) break; 1793 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING; 1794 // explicit fall through to reduce repetitions 1795 1796 case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING: 1797 // skip bcm set sco pcm config on non-Broadcom chipsets 1798 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break; 1799 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT; 1800 // explicit fall through to reduce repetitions 1801 1802 case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT: 1803 if (!hci_le_supported()){ 1804 // SKIP LE init for Classic only configuration 1805 hci_init_done(); 1806 return; 1807 } 1808 break; 1809 1810 #else /* !ENABLE_SCO_OVER_HCI */ 1811 1812 case HCI_INIT_W4_WRITE_SCAN_ENABLE: 1813 #ifdef ENABLE_BLE 1814 if (hci_le_supported()){ 1815 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; 1816 return; 1817 } 1818 #endif 1819 // SKIP LE init for Classic only configuration 1820 hci_init_done(); 1821 return; 1822 #endif /* ENABLE_SCO_OVER_HCI */ 1823 1824 // avoid compile error due to duplicate cases: HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT == HCI_INIT_DONE-1 1825 #if defined(ENABLE_BLE) || defined(ENABLE_LE_DATA_LENGTH_EXTENSION) || defined(ENABLE_LE_CENTRAL) 1826 // Response to command before init done state -> init done 1827 case (HCI_INIT_DONE-1): 1828 hci_init_done(); 1829 return; 1830 #endif 1831 1832 default: 1833 break; 1834 } 1835 hci_initializing_next_state(); 1836 } 1837 1838 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){ 1839 log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address)); 1840 bd_addr_t bd_address; 1841 memcpy(&bd_address, conn->address, 6); 1842 1843 #ifdef ENABLE_CLASSIC 1844 // cache needed data 1845 int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED; 1846 #endif 1847 1848 // connection failed, remove entry 1849 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 1850 btstack_memory_hci_connection_free( conn ); 1851 1852 #ifdef ENABLE_CLASSIC 1853 // notify client if dedicated bonding 1854 if (notify_dedicated_bonding_failed){ 1855 log_info("hci notify_dedicated_bonding_failed"); 1856 hci_emit_dedicated_bonding_result(bd_address, status); 1857 } 1858 1859 // if authentication error, also delete link key 1860 if (status == ERROR_CODE_AUTHENTICATION_FAILURE) { 1861 gap_drop_link_key_for_bd_addr(bd_address); 1862 } 1863 #endif 1864 } 1865 1866 static void event_handler(uint8_t *packet, int size){ 1867 1868 uint16_t event_length = packet[1]; 1869 1870 // assert packet is complete 1871 if (size != event_length + 2){ 1872 log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2); 1873 return; 1874 } 1875 1876 bd_addr_t addr; 1877 bd_addr_type_t addr_type; 1878 hci_con_handle_t handle; 1879 hci_connection_t * conn; 1880 int i; 1881 int create_connection_cmd; 1882 1883 #ifdef ENABLE_CLASSIC 1884 uint8_t link_type; 1885 #endif 1886 1887 // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet)); 1888 1889 switch (hci_event_packet_get_type(packet)) { 1890 1891 case HCI_EVENT_COMMAND_COMPLETE: 1892 // get num cmd packets - limit to 1 to reduce complexity 1893 hci_stack->num_cmd_packets = packet[2] ? 1 : 0; 1894 1895 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){ 1896 if (packet[5]) break; 1897 // terminate, name 248 chars 1898 packet[6+248] = 0; 1899 log_info("local name: %s", &packet[6]); 1900 } 1901 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){ 1902 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 1903 if (hci_stack->state == HCI_STATE_INITIALIZING){ 1904 uint16_t acl_len = little_endian_read_16(packet, 6); 1905 uint16_t sco_len = packet[8]; 1906 1907 // determine usable ACL/SCO payload size 1908 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE); 1909 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE); 1910 1911 hci_stack->acl_packets_total_num = little_endian_read_16(packet, 9); 1912 hci_stack->sco_packets_total_num = little_endian_read_16(packet, 11); 1913 1914 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u", 1915 acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num, 1916 hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num); 1917 } 1918 } 1919 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_rssi)){ 1920 if (packet[5] == 0){ 1921 uint8_t event[5]; 1922 event[0] = GAP_EVENT_RSSI_MEASUREMENT; 1923 event[1] = 3; 1924 memcpy(&event[2], &packet[6], 3); 1925 hci_emit_event(event, sizeof(event), 1); 1926 } 1927 } 1928 #ifdef ENABLE_BLE 1929 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){ 1930 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6); 1931 hci_stack->le_acl_packets_total_num = packet[8]; 1932 // determine usable ACL payload size 1933 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){ 1934 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE; 1935 } 1936 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num); 1937 } 1938 #endif 1939 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION 1940 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){ 1941 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6); 1942 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8); 1943 log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time); 1944 } 1945 #endif 1946 #ifdef ENABLE_LE_CENTRAL 1947 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){ 1948 hci_stack->le_whitelist_capacity = packet[6]; 1949 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity); 1950 } 1951 #endif 1952 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) { 1953 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 1954 hci_stack->local_bd_addr); 1955 log_info("Local Address, Status: 0x%02x: Addr: %s", 1956 packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr)); 1957 #ifdef ENABLE_CLASSIC 1958 if (hci_stack->link_key_db){ 1959 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr); 1960 } 1961 #endif 1962 } 1963 #ifdef ENABLE_CLASSIC 1964 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){ 1965 hci_emit_discoverable_enabled(hci_stack->discoverable); 1966 } 1967 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){ 1968 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){ 1969 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 1970 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 1971 hci_emit_event(event, sizeof(event), 1); 1972 } 1973 } 1974 #endif 1975 1976 // Note: HCI init checks 1977 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){ 1978 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8); 1979 1980 #ifdef ENABLE_CLASSIC 1981 // determine usable ACL packet types based on host buffer size and supported features 1982 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]); 1983 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported()); 1984 #endif 1985 // Classic/LE 1986 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported()); 1987 } 1988 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){ 1989 // hci_stack->hci_version = little_endian_read_16(packet, 4); 1990 // hci_stack->hci_revision = little_endian_read_16(packet, 6); 1991 uint16_t manufacturer = little_endian_read_16(packet, 10); 1992 // map Cypress to Broadcom 1993 if (manufacturer == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){ 1994 log_info("Treat Cypress as Broadcom"); 1995 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION; 1996 little_endian_store_16(packet, 10, manufacturer); 1997 } 1998 hci_stack->manufacturer = manufacturer; 1999 // hci_stack->lmp_version = little_endian_read_16(packet, 8); 2000 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12); 2001 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer); 2002 } 2003 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){ 2004 hci_stack->local_supported_commands[0] = 2005 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 | // bit 0 = Octet 14, bit 7 / Read Buffer Size 2006 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 | // bit 1 = Octet 24, bit 6 / Write Le Host Supported 2007 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 | // bit 2 = Octet 10, bit 4 / Write Synchronous Flow Control Enable 2008 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08) | // bit 3 = Octet 18, bit 3 / Write Default Erroneous Data Reporting 2009 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 | // bit 4 = Octet 34, bit 0 / LE Write Suggested Default Data Length 2010 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2 | // bit 5 = Octet 35, bit 3 / LE Read Maximum Data Length 2011 (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x20) << 1; // bit 6 = Octet 35, bit 5 / LE Set Default PHY 2012 log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]); 2013 } 2014 #ifdef ENABLE_CLASSIC 2015 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){ 2016 if (packet[5] == 0){ 2017 hci_stack->synchronous_flow_control_enabled = 1; 2018 } 2019 } 2020 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_encryption_key_size)){ 2021 uint8_t status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2022 handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1); 2023 conn = hci_connection_for_handle(handle); 2024 if (!conn) break; 2025 if (status == 0){ 2026 uint8_t key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3]; 2027 log_info("Handle %x04x key Size: %u", handle, key_size); 2028 conn->encryption_key_size = key_size; 2029 } else { 2030 log_info("Read Encryption Key Size failed -> assuming insecure connection with key size of 1"); 2031 conn->encryption_key_size = 1; 2032 } 2033 conn->authentication_flags |= CONNECTION_ENCRYPTED; 2034 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 2035 } 2036 #endif 2037 break; 2038 2039 case HCI_EVENT_COMMAND_STATUS: 2040 // get num cmd packets - limit to 1 to reduce complexity 2041 hci_stack->num_cmd_packets = packet[3] ? 1 : 0; 2042 2043 // check command status to detected failed outgoing connections 2044 create_connection_cmd = 0; 2045 #ifdef ENABLE_CLASSIC 2046 if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){ 2047 create_connection_cmd = 1; 2048 } 2049 #endif 2050 #ifdef ENABLE_LE_CENTRAL 2051 if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){ 2052 create_connection_cmd = 1; 2053 } 2054 #endif 2055 if (create_connection_cmd) { 2056 uint8_t status = hci_event_command_status_get_status(packet); 2057 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, hci_stack->outgoing_addr_type); 2058 log_info("command status (create connection), status %x, connection %p, addr %s, type %x", status, conn, bd_addr_to_str(hci_stack->outgoing_addr), hci_stack->outgoing_addr_type); 2059 2060 // reset outgoing address info 2061 memset(hci_stack->outgoing_addr, 0, 6); 2062 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN; 2063 2064 // error => outgoing connection failed 2065 if ((conn != NULL) && (status != 0)){ 2066 hci_handle_connection_failed(conn, status); 2067 } 2068 } 2069 break; 2070 2071 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{ 2072 int offset = 3; 2073 for (i=0; i<packet[2];i++){ 2074 handle = little_endian_read_16(packet, offset) & 0x0fff; 2075 offset += 2; 2076 uint16_t num_packets = little_endian_read_16(packet, offset); 2077 offset += 2; 2078 2079 conn = hci_connection_for_handle(handle); 2080 if (!conn){ 2081 log_error("hci_number_completed_packet lists unused con handle %u", handle); 2082 continue; 2083 } 2084 2085 if (conn->num_packets_sent >= num_packets){ 2086 conn->num_packets_sent -= num_packets; 2087 } else { 2088 log_error("hci_number_completed_packets, more packet slots freed then sent."); 2089 conn->num_packets_sent = 0; 2090 } 2091 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent); 2092 2093 #ifdef ENABLE_CLASSIC 2094 // For SCO, we do the can_send_now_check here 2095 hci_notify_if_sco_can_send_now(); 2096 #endif 2097 } 2098 break; 2099 } 2100 2101 #ifdef ENABLE_CLASSIC 2102 case HCI_EVENT_INQUIRY_COMPLETE: 2103 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){ 2104 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 2105 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 2106 hci_emit_event(event, sizeof(event), 1); 2107 } 2108 break; 2109 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 2110 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){ 2111 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE; 2112 } 2113 break; 2114 case HCI_EVENT_CONNECTION_REQUEST: 2115 reverse_bd_addr(&packet[2], addr); 2116 if (hci_stack->gap_classic_accept_callback != NULL){ 2117 if ((*hci_stack->gap_classic_accept_callback)(addr) == 0){ 2118 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR; 2119 bd_addr_copy(hci_stack->decline_addr, addr); 2120 break; 2121 } 2122 } 2123 2124 // TODO: eval COD 8-10 2125 link_type = packet[11]; 2126 log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type); 2127 addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO; 2128 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 2129 if (!conn) { 2130 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 2131 } 2132 if (!conn) { 2133 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 2134 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES; 2135 bd_addr_copy(hci_stack->decline_addr, addr); 2136 break; 2137 } 2138 conn->role = HCI_ROLE_SLAVE; 2139 conn->state = RECEIVED_CONNECTION_REQUEST; 2140 // store info about eSCO 2141 if (link_type == 0x02){ 2142 conn->remote_supported_feature_eSCO = 1; 2143 } 2144 hci_run(); 2145 break; 2146 2147 case HCI_EVENT_CONNECTION_COMPLETE: 2148 // Connection management 2149 reverse_bd_addr(&packet[5], addr); 2150 log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr)); 2151 addr_type = BD_ADDR_TYPE_CLASSIC; 2152 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 2153 if (conn) { 2154 if (!packet[2]){ 2155 conn->state = OPEN; 2156 conn->con_handle = little_endian_read_16(packet, 3); 2157 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES; 2158 2159 // restart timer 2160 btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 2161 btstack_run_loop_add_timer(&conn->timeout); 2162 2163 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 2164 2165 hci_emit_nr_connections_changed(); 2166 } else { 2167 // connection failed 2168 hci_handle_connection_failed(conn, packet[2]); 2169 } 2170 } 2171 break; 2172 2173 case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE: 2174 reverse_bd_addr(&packet[5], addr); 2175 log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr)); 2176 if (packet[2]){ 2177 // connection failed 2178 break; 2179 } 2180 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 2181 if (!conn) { 2182 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 2183 } 2184 if (!conn) { 2185 break; 2186 } 2187 conn->state = OPEN; 2188 conn->con_handle = little_endian_read_16(packet, 3); 2189 2190 #ifdef ENABLE_SCO_OVER_HCI 2191 // update SCO 2192 if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){ 2193 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections()); 2194 } 2195 // trigger can send now 2196 if (hci_have_usb_transport()){ 2197 hci_stack->sco_can_send_now = 1; 2198 } 2199 #endif 2200 break; 2201 2202 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 2203 handle = little_endian_read_16(packet, 3); 2204 conn = hci_connection_for_handle(handle); 2205 if (!conn) break; 2206 if (!packet[2]){ 2207 uint8_t * features = &packet[5]; 2208 if (features[6] & (1 << 3)){ 2209 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP; 2210 } 2211 if (features[3] & (1<<7)){ 2212 conn->remote_supported_feature_eSCO = 1; 2213 } 2214 } 2215 conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES; 2216 log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO); 2217 if (conn->bonding_flags & BONDING_DEDICATED){ 2218 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2219 } 2220 break; 2221 2222 case HCI_EVENT_LINK_KEY_REQUEST: 2223 log_info("HCI_EVENT_LINK_KEY_REQUEST"); 2224 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST); 2225 // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST 2226 if (hci_stack->bondable && !hci_stack->link_key_db) break; 2227 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST); 2228 hci_run(); 2229 // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set 2230 return; 2231 2232 case HCI_EVENT_LINK_KEY_NOTIFICATION: { 2233 reverse_bd_addr(&packet[2], addr); 2234 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 2235 if (!conn) break; 2236 conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION; 2237 link_key_type_t link_key_type = (link_key_type_t)packet[24]; 2238 // Change Connection Encryption keeps link key type 2239 if (link_key_type != CHANGED_COMBINATION_KEY){ 2240 conn->link_key_type = link_key_type; 2241 } 2242 gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type); 2243 // still forward event to allow dismiss of pairing dialog 2244 break; 2245 } 2246 2247 case HCI_EVENT_PIN_CODE_REQUEST: 2248 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE); 2249 // non-bondable mode: pin code negative reply will be sent 2250 if (!hci_stack->bondable){ 2251 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST); 2252 hci_run(); 2253 return; 2254 } 2255 // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key 2256 if (!hci_stack->link_key_db) break; 2257 hci_event_pin_code_request_get_bd_addr(packet, addr); 2258 hci_stack->link_key_db->delete_link_key(addr); 2259 break; 2260 2261 case HCI_EVENT_IO_CAPABILITY_REQUEST: 2262 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST); 2263 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY); 2264 break; 2265 2266 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 2267 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 2268 if (!hci_stack->ssp_auto_accept) break; 2269 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY); 2270 break; 2271 2272 case HCI_EVENT_USER_PASSKEY_REQUEST: 2273 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 2274 if (!hci_stack->ssp_auto_accept) break; 2275 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY); 2276 break; 2277 case HCI_EVENT_MODE_CHANGE: 2278 handle = hci_event_mode_change_get_handle(packet); 2279 conn = hci_connection_for_handle(handle); 2280 if (!conn) break; 2281 conn->connection_mode = hci_event_mode_change_get_mode(packet); 2282 log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode); 2283 break; 2284 #endif 2285 2286 case HCI_EVENT_ENCRYPTION_CHANGE: 2287 handle = little_endian_read_16(packet, 3); 2288 conn = hci_connection_for_handle(handle); 2289 if (!conn) break; 2290 if (packet[2] == 0) { 2291 if (packet[5]){ 2292 if (hci_is_le_connection(conn)){ 2293 // For LE, we accept connection as encrypted 2294 conn->authentication_flags |= CONNECTION_ENCRYPTED; 2295 } 2296 #ifdef ENABLE_CLASSIC 2297 else { 2298 // For Classic, we need to validate encryption key size first 2299 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE; 2300 } 2301 #endif 2302 } else { 2303 conn->authentication_flags &= ~CONNECTION_ENCRYPTED; 2304 } 2305 } 2306 2307 break; 2308 2309 #ifdef ENABLE_CLASSIC 2310 case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT: 2311 handle = little_endian_read_16(packet, 3); 2312 conn = hci_connection_for_handle(handle); 2313 if (!conn) break; 2314 2315 // dedicated bonding: send result and disconnect 2316 if (conn->bonding_flags & BONDING_DEDICATED){ 2317 conn->bonding_flags &= ~BONDING_DEDICATED; 2318 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 2319 conn->bonding_status = packet[2]; 2320 break; 2321 } 2322 2323 if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){ 2324 // link key sufficient for requested security 2325 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 2326 break; 2327 } 2328 // not enough 2329 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 2330 break; 2331 #endif 2332 2333 // HCI_EVENT_DISCONNECTION_COMPLETE 2334 // has been split, to first notify stack before shutting connection down 2335 // see end of function, too. 2336 case HCI_EVENT_DISCONNECTION_COMPLETE: 2337 if (packet[2]) break; // status != 0 2338 handle = little_endian_read_16(packet, 3); 2339 // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active 2340 if (hci_stack->acl_fragmentation_total_size > 0) { 2341 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){ 2342 int release_buffer = hci_stack->acl_fragmentation_tx_active == 0; 2343 log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer); 2344 hci_stack->acl_fragmentation_total_size = 0; 2345 hci_stack->acl_fragmentation_pos = 0; 2346 if (release_buffer){ 2347 hci_release_packet_buffer(); 2348 } 2349 } 2350 } 2351 2352 // re-enable advertisements for le connections if active 2353 conn = hci_connection_for_handle(handle); 2354 if (!conn) break; 2355 conn->state = RECEIVED_DISCONNECTION_COMPLETE; 2356 #ifdef ENABLE_BLE 2357 #ifdef ENABLE_LE_PERIPHERAL 2358 if (hci_is_le_connection(conn)){ 2359 hci_reenable_advertisements_if_needed(); 2360 } 2361 #endif 2362 #endif 2363 break; 2364 2365 case HCI_EVENT_HARDWARE_ERROR: 2366 log_error("Hardware Error: 0x%02x", packet[2]); 2367 if (hci_stack->hardware_error_callback){ 2368 (*hci_stack->hardware_error_callback)(packet[2]); 2369 } else { 2370 // if no special requests, just reboot stack 2371 hci_power_control_off(); 2372 hci_power_control_on(); 2373 } 2374 break; 2375 2376 #ifdef ENABLE_CLASSIC 2377 case HCI_EVENT_ROLE_CHANGE: 2378 if (packet[2]) break; // status != 0 2379 reverse_bd_addr(&packet[3], addr); 2380 addr_type = BD_ADDR_TYPE_CLASSIC; 2381 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 2382 if (!conn) break; 2383 conn->role = packet[9]; 2384 break; 2385 #endif 2386 2387 case HCI_EVENT_TRANSPORT_PACKET_SENT: 2388 // release packet buffer only for asynchronous transport and if there are not further fragements 2389 if (hci_transport_synchronous()) { 2390 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT"); 2391 return; // instead of break: to avoid re-entering hci_run() 2392 } 2393 hci_stack->acl_fragmentation_tx_active = 0; 2394 if (hci_stack->acl_fragmentation_total_size) break; 2395 hci_release_packet_buffer(); 2396 2397 // L2CAP receives this event via the hci_emit_event below 2398 2399 #ifdef ENABLE_CLASSIC 2400 // For SCO, we do the can_send_now_check here 2401 hci_notify_if_sco_can_send_now(); 2402 #endif 2403 break; 2404 2405 #ifdef ENABLE_CLASSIC 2406 case HCI_EVENT_SCO_CAN_SEND_NOW: 2407 // For SCO, we do the can_send_now_check here 2408 hci_stack->sco_can_send_now = 1; 2409 hci_notify_if_sco_can_send_now(); 2410 return; 2411 2412 // explode inquriy results for easier consumption 2413 case HCI_EVENT_INQUIRY_RESULT: 2414 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 2415 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 2416 gap_inquiry_explode(packet); 2417 break; 2418 #endif 2419 2420 #ifdef ENABLE_BLE 2421 case HCI_EVENT_LE_META: 2422 switch (packet[2]){ 2423 #ifdef ENABLE_LE_CENTRAL 2424 case HCI_SUBEVENT_LE_ADVERTISING_REPORT: 2425 // log_info("advertising report received"); 2426 if (!hci_stack->le_scanning_enabled) break; 2427 le_handle_advertisement_report(packet, size); 2428 break; 2429 #endif 2430 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 2431 // Connection management 2432 reverse_bd_addr(&packet[8], addr); 2433 addr_type = (bd_addr_type_t)packet[7]; 2434 log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr)); 2435 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 2436 2437 #ifdef ENABLE_LE_CENTRAL 2438 // if auto-connect, remove from whitelist in both roles 2439 if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){ 2440 hci_remove_from_whitelist(addr_type, addr); 2441 } 2442 // handle error: error is reported only to the initiator -> outgoing connection 2443 if (packet[3]){ 2444 2445 // handle cancelled outgoing connection 2446 // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command, 2447 // either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated. 2448 // In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)." 2449 if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){ 2450 conn = gap_get_outgoing_connection(); 2451 } 2452 2453 // outgoing connection establishment is done 2454 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 2455 // remove entry 2456 if (conn){ 2457 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 2458 btstack_memory_hci_connection_free( conn ); 2459 } 2460 break; 2461 } 2462 #endif 2463 // on success, both hosts receive connection complete event 2464 if (packet[6] == HCI_ROLE_MASTER){ 2465 #ifdef ENABLE_LE_CENTRAL 2466 // if we're master, it was an outgoing connection and we're done with it 2467 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 2468 #endif 2469 } else { 2470 #ifdef ENABLE_LE_PERIPHERAL 2471 // if we're slave, it was an incoming connection, advertisements have stopped 2472 hci_stack->le_advertisements_active = 0; 2473 #endif 2474 } 2475 // LE connections are auto-accepted, so just create a connection if there isn't one already 2476 if (!conn){ 2477 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 2478 } 2479 // no memory, sorry. 2480 if (!conn){ 2481 break; 2482 } 2483 2484 conn->state = OPEN; 2485 conn->role = packet[6]; 2486 conn->con_handle = hci_subevent_le_connection_complete_get_connection_handle(packet); 2487 conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet); 2488 2489 #ifdef ENABLE_LE_PERIPHERAL 2490 if (packet[6] == HCI_ROLE_SLAVE){ 2491 hci_reenable_advertisements_if_needed(); 2492 } 2493 #endif 2494 2495 // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock 2496 2497 // restart timer 2498 // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 2499 // btstack_run_loop_add_timer(&conn->timeout); 2500 2501 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 2502 2503 hci_emit_nr_connections_changed(); 2504 break; 2505 2506 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]); 2507 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE: 2508 handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet); 2509 conn = hci_connection_for_handle(handle); 2510 if (!conn) break; 2511 conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet); 2512 break; 2513 2514 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST: 2515 // connection 2516 handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet); 2517 conn = hci_connection_for_handle(handle); 2518 if (conn) { 2519 // read arguments 2520 uint16_t le_conn_interval_min = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet); 2521 uint16_t le_conn_interval_max = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet); 2522 uint16_t le_conn_latency = hci_subevent_le_remote_connection_parameter_request_get_latency(packet); 2523 uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet); 2524 2525 // validate against current connection parameter range 2526 le_connection_parameter_range_t existing_range; 2527 gap_get_connection_parameter_range(&existing_range); 2528 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout); 2529 if (update_parameter){ 2530 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY; 2531 conn->le_conn_interval_min = le_conn_interval_min; 2532 conn->le_conn_interval_max = le_conn_interval_max; 2533 conn->le_conn_latency = le_conn_latency; 2534 conn->le_supervision_timeout = le_supervision_timeout; 2535 } else { 2536 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY; 2537 } 2538 } 2539 break; 2540 default: 2541 break; 2542 } 2543 break; 2544 #endif 2545 case HCI_EVENT_VENDOR_SPECIFIC: 2546 // Vendor specific commands often create vendor specific event instead of num completed packets 2547 // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour 2548 switch (hci_stack->manufacturer){ 2549 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO: 2550 hci_stack->num_cmd_packets = 1; 2551 break; 2552 default: 2553 break; 2554 } 2555 break; 2556 default: 2557 break; 2558 } 2559 2560 // handle BT initialization 2561 if (hci_stack->state == HCI_STATE_INITIALIZING){ 2562 hci_initializing_event_handler(packet, size); 2563 } 2564 2565 // help with BT sleep 2566 if (hci_stack->state == HCI_STATE_FALLING_ASLEEP 2567 && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE 2568 && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){ 2569 hci_initializing_next_state(); 2570 } 2571 2572 // notify upper stack 2573 hci_emit_event(packet, size, 0); // don't dump, already happened in packet handler 2574 2575 // moved here to give upper stack a chance to close down everything with hci_connection_t intact 2576 if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){ 2577 if (!packet[2]){ 2578 handle = little_endian_read_16(packet, 3); 2579 hci_connection_t * aConn = hci_connection_for_handle(handle); 2580 if (aConn) { 2581 uint8_t status = aConn->bonding_status; 2582 uint16_t flags = aConn->bonding_flags; 2583 bd_addr_t bd_address; 2584 memcpy(&bd_address, aConn->address, 6); 2585 hci_shutdown_connection(aConn); 2586 // connection struct is gone, don't access anymore 2587 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){ 2588 hci_emit_dedicated_bonding_result(bd_address, status); 2589 } 2590 } 2591 } 2592 } 2593 2594 // execute main loop 2595 hci_run(); 2596 } 2597 2598 #ifdef ENABLE_CLASSIC 2599 2600 static void sco_tx_timeout_handler(btstack_timer_source_t * ts); 2601 static void sco_schedule_tx(hci_connection_t * conn); 2602 2603 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){ 2604 log_debug("SCO TX Timeout"); 2605 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts); 2606 hci_connection_t * conn = hci_connection_for_handle(con_handle); 2607 if (!conn) return; 2608 2609 // trigger send 2610 conn->sco_tx_ready = 1; 2611 // extra packet if CVSD but SCO buffer is too short 2612 if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && hci_stack->sco_data_packet_length < 123){ 2613 conn->sco_tx_ready++; 2614 } 2615 hci_notify_if_sco_can_send_now(); 2616 } 2617 2618 2619 #define SCO_TX_AFTER_RX_MS (6) 2620 2621 static void sco_schedule_tx(hci_connection_t * conn){ 2622 2623 uint32_t now = btstack_run_loop_get_time_ms(); 2624 uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS; 2625 int time_delta_ms = sco_tx_ms - now; 2626 2627 btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco; 2628 2629 // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms); 2630 btstack_run_loop_set_timer(timer, time_delta_ms); 2631 btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle); 2632 btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler); 2633 btstack_run_loop_add_timer(timer); 2634 } 2635 2636 static void sco_handler(uint8_t * packet, uint16_t size){ 2637 // lookup connection struct 2638 hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet); 2639 hci_connection_t * conn = hci_connection_for_handle(con_handle); 2640 if (!conn) return; 2641 2642 // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes 2643 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){ 2644 if (size == 83 && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){ 2645 packet[2] = 0x3c; 2646 memmove(&packet[3], &packet[23], 63); 2647 size = 63; 2648 } 2649 } 2650 2651 if (hci_have_usb_transport()){ 2652 // Nothing to do 2653 } else { 2654 // log_debug("sco flow %u, handle 0x%04x, packets sent %u, bytes send %u", hci_stack->synchronous_flow_control_enabled, (int) con_handle, conn->num_packets_sent, conn->num_sco_bytes_sent); 2655 if (hci_stack->synchronous_flow_control_enabled == 0){ 2656 uint32_t now = btstack_run_loop_get_time_ms(); 2657 2658 if (!conn->sco_rx_valid){ 2659 // ignore first 10 packets 2660 conn->sco_rx_count++; 2661 // log_debug("sco rx count %u", conn->sco_rx_count); 2662 if (conn->sco_rx_count == 10) { 2663 // use first timestamp as is and pretent it just started 2664 conn->sco_rx_ms = now; 2665 conn->sco_rx_valid = 1; 2666 conn->sco_rx_count = 0; 2667 sco_schedule_tx(conn); 2668 } 2669 } else { 2670 // track expected arrival timme 2671 conn->sco_rx_count++; 2672 conn->sco_rx_ms += 7; 2673 int delta = (int32_t) (now - conn->sco_rx_ms); 2674 if (delta > 0){ 2675 conn->sco_rx_ms++; 2676 } 2677 // log_debug("sco rx %u", conn->sco_rx_ms); 2678 sco_schedule_tx(conn); 2679 } 2680 } 2681 } 2682 // deliver to app 2683 if (hci_stack->sco_packet_handler) { 2684 hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size); 2685 } 2686 2687 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 2688 conn->num_packets_completed++; 2689 hci_stack->host_completed_packets = 1; 2690 hci_run(); 2691 #endif 2692 } 2693 #endif 2694 2695 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 2696 hci_dump_packet(packet_type, 1, packet, size); 2697 switch (packet_type) { 2698 case HCI_EVENT_PACKET: 2699 event_handler(packet, size); 2700 break; 2701 case HCI_ACL_DATA_PACKET: 2702 acl_handler(packet, size); 2703 break; 2704 #ifdef ENABLE_CLASSIC 2705 case HCI_SCO_DATA_PACKET: 2706 sco_handler(packet, size); 2707 break; 2708 #endif 2709 default: 2710 break; 2711 } 2712 } 2713 2714 /** 2715 * @brief Add event packet handler. 2716 */ 2717 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){ 2718 btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler); 2719 } 2720 2721 2722 /** Register HCI packet handlers */ 2723 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){ 2724 hci_stack->acl_packet_handler = handler; 2725 } 2726 2727 #ifdef ENABLE_CLASSIC 2728 /** 2729 * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles. 2730 */ 2731 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){ 2732 hci_stack->sco_packet_handler = handler; 2733 } 2734 #endif 2735 2736 static void hci_state_reset(void){ 2737 // no connections yet 2738 hci_stack->connections = NULL; 2739 2740 // keep discoverable/connectable as this has been requested by the client(s) 2741 // hci_stack->discoverable = 0; 2742 // hci_stack->connectable = 0; 2743 // hci_stack->bondable = 1; 2744 // hci_stack->own_addr_type = 0; 2745 2746 // buffer is free 2747 hci_stack->hci_packet_buffer_reserved = 0; 2748 2749 // no pending cmds 2750 hci_stack->decline_reason = 0; 2751 hci_stack->new_scan_enable_value = 0xff; 2752 2753 // LE 2754 #ifdef ENABLE_BLE 2755 memset(hci_stack->le_random_address, 0, 6); 2756 hci_stack->le_random_address_set = 0; 2757 #endif 2758 #ifdef ENABLE_LE_CENTRAL 2759 hci_stack->le_scanning_active = 0; 2760 hci_stack->le_scan_type = 0xff; 2761 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 2762 hci_stack->le_whitelist = 0; 2763 hci_stack->le_whitelist_capacity = 0; 2764 #endif 2765 } 2766 2767 #ifdef ENABLE_CLASSIC 2768 /** 2769 * @brief Configure Bluetooth hardware control. Has to be called before power on. 2770 */ 2771 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){ 2772 // store and open remote device db 2773 hci_stack->link_key_db = link_key_db; 2774 if (hci_stack->link_key_db) { 2775 hci_stack->link_key_db->open(); 2776 } 2777 } 2778 #endif 2779 2780 void hci_init(const hci_transport_t *transport, const void *config){ 2781 2782 #ifdef HAVE_MALLOC 2783 if (!hci_stack) { 2784 hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t)); 2785 } 2786 #else 2787 hci_stack = &hci_stack_static; 2788 #endif 2789 memset(hci_stack, 0, sizeof(hci_stack_t)); 2790 2791 // reference to use transport layer implementation 2792 hci_stack->hci_transport = transport; 2793 2794 // reference to used config 2795 hci_stack->config = config; 2796 2797 // setup pointer for outgoing packet buffer 2798 hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE]; 2799 2800 // max acl payload size defined in config.h 2801 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 2802 2803 // register packet handlers with transport 2804 transport->register_packet_handler(&packet_handler); 2805 2806 hci_stack->state = HCI_STATE_OFF; 2807 2808 // class of device 2809 hci_stack->class_of_device = 0x007a020c; // Smartphone 2810 2811 // bondable by default 2812 hci_stack->bondable = 1; 2813 2814 #ifdef ENABLE_CLASSIC 2815 // classic name 2816 hci_stack->local_name = default_classic_name; 2817 2818 // Master slave policy 2819 hci_stack->master_slave_policy = 1; 2820 2821 // Errata-11838 mandates 7 bytes for GAP Security Level 1-3, we use 16 as default 2822 hci_stack->gap_required_encyrption_key_size = 16; 2823 #endif 2824 2825 // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept 2826 hci_stack->ssp_enable = 1; 2827 hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 2828 hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 2829 hci_stack->ssp_auto_accept = 1; 2830 2831 // voice setting - signed 16 bit pcm data with CVSD over the air 2832 hci_stack->sco_voice_setting = 0x60; 2833 2834 #ifdef ENABLE_LE_CENTRAL 2835 // connection parameter to use for outgoing connections 2836 hci_stack->le_connection_scan_interval = 0x0060; // 60ms 2837 hci_stack->le_connection_scan_window = 0x0030; // 30ms 2838 hci_stack->le_connection_interval_min = 0x0008; // 10 ms 2839 hci_stack->le_connection_interval_max = 0x0018; // 30 ms 2840 hci_stack->le_connection_latency = 4; // 4 2841 hci_stack->le_supervision_timeout = 0x0048; // 720 ms 2842 hci_stack->le_minimum_ce_length = 2; // 1.25 ms 2843 hci_stack->le_maximum_ce_length = 0x0030; // 30 ms 2844 2845 // default LE Scanning 2846 hci_stack->le_scan_interval = 0x1e0; 2847 hci_stack->le_scan_window = 0x30; 2848 #endif 2849 2850 #ifdef ENABLE_LE_PERIPHERAL 2851 hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral 2852 #endif 2853 2854 // connection parameter range used to answer connection parameter update requests in l2cap 2855 hci_stack->le_connection_parameter_range.le_conn_interval_min = 6; 2856 hci_stack->le_connection_parameter_range.le_conn_interval_max = 3200; 2857 hci_stack->le_connection_parameter_range.le_conn_latency_min = 0; 2858 hci_stack->le_connection_parameter_range.le_conn_latency_max = 500; 2859 hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 10; 2860 hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200; 2861 2862 hci_state_reset(); 2863 } 2864 2865 /** 2866 * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information 2867 */ 2868 void hci_set_chipset(const btstack_chipset_t *chipset_driver){ 2869 hci_stack->chipset = chipset_driver; 2870 2871 // reset chipset driver - init is also called on power_up 2872 if (hci_stack->chipset && hci_stack->chipset->init){ 2873 hci_stack->chipset->init(hci_stack->config); 2874 } 2875 } 2876 2877 /** 2878 * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on. 2879 */ 2880 void hci_set_control(const btstack_control_t *hardware_control){ 2881 // references to used control implementation 2882 hci_stack->control = hardware_control; 2883 // init with transport config 2884 hardware_control->init(hci_stack->config); 2885 } 2886 2887 void hci_close(void){ 2888 // close remote device db 2889 if (hci_stack->link_key_db) { 2890 hci_stack->link_key_db->close(); 2891 } 2892 2893 btstack_linked_list_iterator_t lit; 2894 btstack_linked_list_iterator_init(&lit, &hci_stack->connections); 2895 while (btstack_linked_list_iterator_has_next(&lit)){ 2896 // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection 2897 hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit); 2898 hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host 2899 hci_shutdown_connection(connection); 2900 } 2901 2902 hci_power_control(HCI_POWER_OFF); 2903 2904 #ifdef HAVE_MALLOC 2905 free(hci_stack); 2906 #endif 2907 hci_stack = NULL; 2908 } 2909 2910 #ifdef ENABLE_CLASSIC 2911 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){ 2912 // validate ranage and set 2913 if (encryption_key_size < 7) return; 2914 if (encryption_key_size > 16) return; 2915 hci_stack->gap_required_encyrption_key_size = encryption_key_size; 2916 } 2917 #endif 2918 2919 #ifdef ENABLE_CLASSIC 2920 void gap_set_class_of_device(uint32_t class_of_device){ 2921 hci_stack->class_of_device = class_of_device; 2922 } 2923 2924 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){ 2925 hci_stack->default_link_policy_settings = default_link_policy_settings; 2926 } 2927 2928 void hci_disable_l2cap_timeout_check(void){ 2929 disable_l2cap_timeouts = 1; 2930 } 2931 #endif 2932 2933 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 2934 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h 2935 void hci_set_bd_addr(bd_addr_t addr){ 2936 memcpy(hci_stack->custom_bd_addr, addr, 6); 2937 hci_stack->custom_bd_addr_set = 1; 2938 } 2939 #endif 2940 2941 // State-Module-Driver overview 2942 // state module low-level 2943 // HCI_STATE_OFF off close 2944 // HCI_STATE_INITIALIZING, on open 2945 // HCI_STATE_WORKING, on open 2946 // HCI_STATE_HALTING, on open 2947 // HCI_STATE_SLEEPING, off/sleep close 2948 // HCI_STATE_FALLING_ASLEEP on open 2949 2950 static int hci_power_control_on(void){ 2951 2952 // power on 2953 int err = 0; 2954 if (hci_stack->control && hci_stack->control->on){ 2955 err = (*hci_stack->control->on)(); 2956 } 2957 if (err){ 2958 log_error( "POWER_ON failed"); 2959 hci_emit_hci_open_failed(); 2960 return err; 2961 } 2962 2963 // int chipset driver 2964 if (hci_stack->chipset && hci_stack->chipset->init){ 2965 hci_stack->chipset->init(hci_stack->config); 2966 } 2967 2968 // init transport 2969 if (hci_stack->hci_transport->init){ 2970 hci_stack->hci_transport->init(hci_stack->config); 2971 } 2972 2973 // open transport 2974 err = hci_stack->hci_transport->open(); 2975 if (err){ 2976 log_error( "HCI_INIT failed, turning Bluetooth off again"); 2977 if (hci_stack->control && hci_stack->control->off){ 2978 (*hci_stack->control->off)(); 2979 } 2980 hci_emit_hci_open_failed(); 2981 return err; 2982 } 2983 return 0; 2984 } 2985 2986 static void hci_power_control_off(void){ 2987 2988 log_info("hci_power_control_off"); 2989 2990 // close low-level device 2991 hci_stack->hci_transport->close(); 2992 2993 log_info("hci_power_control_off - hci_transport closed"); 2994 2995 // power off 2996 if (hci_stack->control && hci_stack->control->off){ 2997 (*hci_stack->control->off)(); 2998 } 2999 3000 log_info("hci_power_control_off - control closed"); 3001 3002 hci_stack->state = HCI_STATE_OFF; 3003 } 3004 3005 static void hci_power_control_sleep(void){ 3006 3007 log_info("hci_power_control_sleep"); 3008 3009 #if 0 3010 // don't close serial port during sleep 3011 3012 // close low-level device 3013 hci_stack->hci_transport->close(hci_stack->config); 3014 #endif 3015 3016 // sleep mode 3017 if (hci_stack->control && hci_stack->control->sleep){ 3018 (*hci_stack->control->sleep)(); 3019 } 3020 3021 hci_stack->state = HCI_STATE_SLEEPING; 3022 } 3023 3024 static int hci_power_control_wake(void){ 3025 3026 log_info("hci_power_control_wake"); 3027 3028 // wake on 3029 if (hci_stack->control && hci_stack->control->wake){ 3030 (*hci_stack->control->wake)(); 3031 } 3032 3033 #if 0 3034 // open low-level device 3035 int err = hci_stack->hci_transport->open(hci_stack->config); 3036 if (err){ 3037 log_error( "HCI_INIT failed, turning Bluetooth off again"); 3038 if (hci_stack->control && hci_stack->control->off){ 3039 (*hci_stack->control->off)(); 3040 } 3041 hci_emit_hci_open_failed(); 3042 return err; 3043 } 3044 #endif 3045 3046 return 0; 3047 } 3048 3049 static void hci_power_transition_to_initializing(void){ 3050 // set up state machine 3051 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 3052 hci_stack->hci_packet_buffer_reserved = 0; 3053 hci_stack->state = HCI_STATE_INITIALIZING; 3054 hci_stack->substate = HCI_INIT_SEND_RESET; 3055 } 3056 3057 int hci_power_control(HCI_POWER_MODE power_mode){ 3058 3059 log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state); 3060 3061 int err = 0; 3062 switch (hci_stack->state){ 3063 3064 case HCI_STATE_OFF: 3065 switch (power_mode){ 3066 case HCI_POWER_ON: 3067 err = hci_power_control_on(); 3068 if (err) { 3069 log_error("hci_power_control_on() error %d", err); 3070 return err; 3071 } 3072 hci_power_transition_to_initializing(); 3073 break; 3074 case HCI_POWER_OFF: 3075 // do nothing 3076 break; 3077 case HCI_POWER_SLEEP: 3078 // do nothing (with SLEEP == OFF) 3079 break; 3080 } 3081 break; 3082 3083 case HCI_STATE_INITIALIZING: 3084 switch (power_mode){ 3085 case HCI_POWER_ON: 3086 // do nothing 3087 break; 3088 case HCI_POWER_OFF: 3089 // no connections yet, just turn it off 3090 hci_power_control_off(); 3091 break; 3092 case HCI_POWER_SLEEP: 3093 // no connections yet, just turn it off 3094 hci_power_control_sleep(); 3095 break; 3096 } 3097 break; 3098 3099 case HCI_STATE_WORKING: 3100 switch (power_mode){ 3101 case HCI_POWER_ON: 3102 // do nothing 3103 break; 3104 case HCI_POWER_OFF: 3105 // see hci_run 3106 hci_stack->state = HCI_STATE_HALTING; 3107 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER; 3108 break; 3109 case HCI_POWER_SLEEP: 3110 // see hci_run 3111 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 3112 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 3113 break; 3114 } 3115 break; 3116 3117 case HCI_STATE_HALTING: 3118 switch (power_mode){ 3119 case HCI_POWER_ON: 3120 hci_power_transition_to_initializing(); 3121 break; 3122 case HCI_POWER_OFF: 3123 // do nothing 3124 break; 3125 case HCI_POWER_SLEEP: 3126 // see hci_run 3127 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 3128 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 3129 break; 3130 } 3131 break; 3132 3133 case HCI_STATE_FALLING_ASLEEP: 3134 switch (power_mode){ 3135 case HCI_POWER_ON: 3136 3137 #ifdef HAVE_PLATFORM_IPHONE_OS 3138 // nothing to do, if H4 supports power management 3139 if (btstack_control_iphone_power_management_enabled()){ 3140 hci_stack->state = HCI_STATE_INITIALIZING; 3141 hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE; // init after sleep 3142 break; 3143 } 3144 #endif 3145 hci_power_transition_to_initializing(); 3146 break; 3147 case HCI_POWER_OFF: 3148 // see hci_run 3149 hci_stack->state = HCI_STATE_HALTING; 3150 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER; 3151 break; 3152 case HCI_POWER_SLEEP: 3153 // do nothing 3154 break; 3155 } 3156 break; 3157 3158 case HCI_STATE_SLEEPING: 3159 switch (power_mode){ 3160 case HCI_POWER_ON: 3161 3162 #ifdef HAVE_PLATFORM_IPHONE_OS 3163 // nothing to do, if H4 supports power management 3164 if (btstack_control_iphone_power_management_enabled()){ 3165 hci_stack->state = HCI_STATE_INITIALIZING; 3166 hci_stack->substate = HCI_INIT_AFTER_SLEEP; 3167 hci_update_scan_enable(); 3168 break; 3169 } 3170 #endif 3171 err = hci_power_control_wake(); 3172 if (err) return err; 3173 hci_power_transition_to_initializing(); 3174 break; 3175 case HCI_POWER_OFF: 3176 hci_stack->state = HCI_STATE_HALTING; 3177 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER; 3178 break; 3179 case HCI_POWER_SLEEP: 3180 // do nothing 3181 break; 3182 } 3183 break; 3184 } 3185 3186 // create internal event 3187 hci_emit_state(); 3188 3189 // trigger next/first action 3190 hci_run(); 3191 3192 return 0; 3193 } 3194 3195 3196 #ifdef ENABLE_CLASSIC 3197 3198 static void hci_update_scan_enable(void){ 3199 // 2 = page scan, 1 = inq scan 3200 hci_stack->new_scan_enable_value = hci_stack->connectable << 1 | hci_stack->discoverable; 3201 hci_run(); 3202 } 3203 3204 void gap_discoverable_control(uint8_t enable){ 3205 if (enable) enable = 1; // normalize argument 3206 3207 if (hci_stack->discoverable == enable){ 3208 hci_emit_discoverable_enabled(hci_stack->discoverable); 3209 return; 3210 } 3211 3212 hci_stack->discoverable = enable; 3213 hci_update_scan_enable(); 3214 } 3215 3216 void gap_connectable_control(uint8_t enable){ 3217 if (enable) enable = 1; // normalize argument 3218 3219 // don't emit event 3220 if (hci_stack->connectable == enable) return; 3221 3222 hci_stack->connectable = enable; 3223 hci_update_scan_enable(); 3224 } 3225 #endif 3226 3227 void gap_local_bd_addr(bd_addr_t address_buffer){ 3228 memcpy(address_buffer, hci_stack->local_bd_addr, 6); 3229 } 3230 3231 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 3232 static void hci_host_num_completed_packets(void){ 3233 3234 // create packet manually as arrays are not supported and num_commands should not get reduced 3235 hci_reserve_packet_buffer(); 3236 uint8_t * packet = hci_get_outgoing_packet_buffer(); 3237 3238 uint16_t size = 0; 3239 uint16_t num_handles = 0; 3240 packet[size++] = 0x35; 3241 packet[size++] = 0x0c; 3242 size++; // skip param len 3243 size++; // skip num handles 3244 3245 // add { handle, packets } entries 3246 btstack_linked_item_t * it; 3247 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 3248 hci_connection_t * connection = (hci_connection_t *) it; 3249 if (connection->num_packets_completed){ 3250 little_endian_store_16(packet, size, connection->con_handle); 3251 size += 2; 3252 little_endian_store_16(packet, size, connection->num_packets_completed); 3253 size += 2; 3254 // 3255 num_handles++; 3256 connection->num_packets_completed = 0; 3257 } 3258 } 3259 3260 packet[2] = size - 3; 3261 packet[3] = num_handles; 3262 3263 hci_stack->host_completed_packets = 0; 3264 3265 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 3266 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 3267 3268 // release packet buffer for synchronous transport implementations 3269 if (hci_transport_synchronous()){ 3270 hci_release_packet_buffer(); 3271 hci_emit_transport_packet_sent(); 3272 } 3273 } 3274 #endif 3275 3276 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){ 3277 UNUSED(ds); 3278 hci_stack->substate = HCI_HALTING_CLOSE; 3279 // allow packet handlers to defer final shutdown 3280 hci_emit_state(); 3281 hci_run(); 3282 } 3283 3284 static void hci_run(void){ 3285 3286 // log_info("hci_run: entered"); 3287 btstack_linked_item_t * it; 3288 3289 // send continuation fragments first, as they block the prepared packet buffer 3290 if (hci_stack->acl_fragmentation_total_size > 0) { 3291 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer); 3292 hci_connection_t *connection = hci_connection_for_handle(con_handle); 3293 if (connection) { 3294 if (hci_can_send_prepared_acl_packet_now(con_handle)){ 3295 hci_send_acl_packet_fragments(connection); 3296 return; 3297 } 3298 } else { 3299 // connection gone -> discard further fragments 3300 log_info("hci_run: fragmented ACL packet no connection -> discard fragment"); 3301 hci_stack->acl_fragmentation_total_size = 0; 3302 hci_stack->acl_fragmentation_pos = 0; 3303 } 3304 } 3305 3306 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 3307 // send host num completed packets next as they don't require num_cmd_packets > 0 3308 if (!hci_can_send_comand_packet_transport()) return; 3309 if (hci_stack->host_completed_packets){ 3310 hci_host_num_completed_packets(); 3311 return; 3312 } 3313 #endif 3314 3315 if (!hci_can_send_command_packet_now()) return; 3316 3317 // global/non-connection oriented commands 3318 3319 #ifdef ENABLE_CLASSIC 3320 // decline incoming connections 3321 if (hci_stack->decline_reason){ 3322 uint8_t reason = hci_stack->decline_reason; 3323 hci_stack->decline_reason = 0; 3324 hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason); 3325 return; 3326 } 3327 // send scan enable 3328 if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){ 3329 hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value); 3330 hci_stack->new_scan_enable_value = 0xff; 3331 return; 3332 } 3333 // start/stop inquiry 3334 if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){ 3335 uint8_t duration = hci_stack->inquiry_state; 3336 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE; 3337 hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0); 3338 return; 3339 } 3340 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){ 3341 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED; 3342 hci_send_cmd(&hci_inquiry_cancel); 3343 return; 3344 } 3345 // remote name request 3346 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){ 3347 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE; 3348 hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr, 3349 hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset); 3350 return; 3351 } 3352 // pairing 3353 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){ 3354 uint8_t state = hci_stack->gap_pairing_state; 3355 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 3356 switch (state){ 3357 case GAP_PAIRING_STATE_SEND_PIN: 3358 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_input.gap_pairing_pin), hci_stack->gap_pairing_input.gap_pairing_pin); 3359 break; 3360 case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE: 3361 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr); 3362 break; 3363 case GAP_PAIRING_STATE_SEND_PASSKEY: 3364 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey); 3365 break; 3366 case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE: 3367 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr); 3368 break; 3369 case GAP_PAIRING_STATE_SEND_CONFIRMATION: 3370 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr); 3371 break; 3372 case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE: 3373 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr); 3374 break; 3375 default: 3376 break; 3377 } 3378 return; 3379 } 3380 #endif 3381 3382 #ifdef ENABLE_BLE 3383 // advertisements, active scanning, and creating connections requires randaom address to be set if using private address 3384 if ((hci_stack->state == HCI_STATE_WORKING) 3385 && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){ 3386 3387 #ifdef ENABLE_LE_CENTRAL 3388 // handle le scan 3389 if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){ 3390 hci_stack->le_scanning_active = hci_stack->le_scanning_enabled; 3391 hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0); 3392 return; 3393 } 3394 if (hci_stack->le_scan_type != 0xff){ 3395 // defaults: active scanning, accept all advertisement packets 3396 int scan_type = hci_stack->le_scan_type; 3397 hci_stack->le_scan_type = 0xff; 3398 hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, 0); 3399 return; 3400 } 3401 #endif 3402 #ifdef ENABLE_LE_PERIPHERAL 3403 // le advertisement control 3404 if (hci_stack->le_advertisements_todo){ 3405 log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo ); 3406 } 3407 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){ 3408 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE; 3409 hci_send_cmd(&hci_le_set_advertise_enable, 0); 3410 return; 3411 } 3412 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){ 3413 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS; 3414 hci_send_cmd(&hci_le_set_advertising_parameters, 3415 hci_stack->le_advertisements_interval_min, 3416 hci_stack->le_advertisements_interval_max, 3417 hci_stack->le_advertisements_type, 3418 hci_stack->le_own_addr_type, 3419 hci_stack->le_advertisements_direct_address_type, 3420 hci_stack->le_advertisements_direct_address, 3421 hci_stack->le_advertisements_channel_map, 3422 hci_stack->le_advertisements_filter_policy); 3423 return; 3424 } 3425 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){ 3426 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 3427 uint8_t adv_data_clean[31]; 3428 memset(adv_data_clean, 0, sizeof(adv_data_clean)); 3429 memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len); 3430 hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len); 3431 hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean); 3432 return; 3433 } 3434 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){ 3435 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 3436 uint8_t scan_data_clean[31]; 3437 memset(scan_data_clean, 0, sizeof(scan_data_clean)); 3438 memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len); 3439 hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len); 3440 hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean); 3441 return; 3442 } 3443 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){ 3444 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE; 3445 hci_send_cmd(&hci_le_set_advertise_enable, 1); 3446 return; 3447 } 3448 #endif 3449 3450 #ifdef ENABLE_LE_CENTRAL 3451 // 3452 // LE Whitelist Management 3453 // 3454 3455 // check if whitelist needs modification 3456 btstack_linked_list_iterator_t lit; 3457 int modification_pending = 0; 3458 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 3459 while (btstack_linked_list_iterator_has_next(&lit)){ 3460 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 3461 if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){ 3462 modification_pending = 1; 3463 break; 3464 } 3465 } 3466 3467 if (modification_pending){ 3468 // stop connnecting if modification pending 3469 if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){ 3470 hci_send_cmd(&hci_le_create_connection_cancel); 3471 return; 3472 } 3473 3474 // add/remove entries 3475 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 3476 while (btstack_linked_list_iterator_has_next(&lit)){ 3477 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 3478 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){ 3479 entry->state = LE_WHITELIST_ON_CONTROLLER; 3480 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address); 3481 return; 3482 3483 } 3484 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){ 3485 bd_addr_t address; 3486 bd_addr_type_t address_type = entry->address_type; 3487 memcpy(address, entry->address, 6); 3488 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry); 3489 btstack_memory_whitelist_entry_free(entry); 3490 hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address); 3491 return; 3492 } 3493 } 3494 } 3495 3496 // start connecting 3497 if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE && 3498 !btstack_linked_list_empty(&hci_stack->le_whitelist)){ 3499 bd_addr_t null_addr; 3500 memset(null_addr, 0, 6); 3501 hci_send_cmd(&hci_le_create_connection, 3502 hci_stack->le_connection_scan_interval, // scan interval: 60 ms 3503 hci_stack->le_connection_scan_window, // scan interval: 30 ms 3504 1, // use whitelist 3505 0, // peer address type 3506 null_addr, // peer bd addr 3507 hci_stack->le_own_addr_type, // our addr type: 3508 hci_stack->le_connection_interval_min, // conn interval min 3509 hci_stack->le_connection_interval_max, // conn interval max 3510 hci_stack->le_connection_latency, // conn latency 3511 hci_stack->le_supervision_timeout, // conn latency 3512 hci_stack->le_minimum_ce_length, // min ce length 3513 hci_stack->le_maximum_ce_length // max ce length 3514 ); 3515 return; 3516 } 3517 #endif 3518 } 3519 #endif 3520 3521 // send pending HCI commands 3522 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 3523 hci_connection_t * connection = (hci_connection_t *) it; 3524 3525 switch(connection->state){ 3526 case SEND_CREATE_CONNECTION: 3527 switch(connection->address_type){ 3528 #ifdef ENABLE_CLASSIC 3529 case BD_ADDR_TYPE_CLASSIC: 3530 log_info("sending hci_create_connection"); 3531 hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1); 3532 break; 3533 #endif 3534 default: 3535 #ifdef ENABLE_BLE 3536 #ifdef ENABLE_LE_CENTRAL 3537 // track outgoing connection 3538 hci_stack->outgoing_addr_type = connection->address_type; 3539 memcpy(hci_stack->outgoing_addr, connection->address, 6); 3540 log_info("sending hci_le_create_connection"); 3541 hci_send_cmd(&hci_le_create_connection, 3542 hci_stack->le_connection_scan_interval, // conn scan interval 3543 hci_stack->le_connection_scan_window, // conn scan windows 3544 0, // don't use whitelist 3545 connection->address_type, // peer address type 3546 connection->address, // peer bd addr 3547 hci_stack->le_own_addr_type, // our addr type: 3548 hci_stack->le_connection_interval_min, // conn interval min 3549 hci_stack->le_connection_interval_max, // conn interval max 3550 hci_stack->le_connection_latency, // conn latency 3551 hci_stack->le_supervision_timeout, // conn latency 3552 hci_stack->le_minimum_ce_length, // min ce length 3553 hci_stack->le_maximum_ce_length // max ce length 3554 ); 3555 connection->state = SENT_CREATE_CONNECTION; 3556 #endif 3557 #endif 3558 break; 3559 } 3560 return; 3561 3562 #ifdef ENABLE_CLASSIC 3563 case RECEIVED_CONNECTION_REQUEST: 3564 connection->role = HCI_ROLE_SLAVE; 3565 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){ 3566 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO); 3567 connection->state = ACCEPTED_CONNECTION_REQUEST; 3568 hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy); 3569 } 3570 return; 3571 #endif 3572 3573 #ifdef ENABLE_BLE 3574 #ifdef ENABLE_LE_CENTRAL 3575 case SEND_CANCEL_CONNECTION: 3576 connection->state = SENT_CANCEL_CONNECTION; 3577 hci_send_cmd(&hci_le_create_connection_cancel); 3578 return; 3579 #endif 3580 #endif 3581 case SEND_DISCONNECT: 3582 connection->state = SENT_DISCONNECT; 3583 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 3584 return; 3585 3586 default: 3587 break; 3588 } 3589 3590 // no further commands if connection is about to get shut down 3591 if (connection->state == SENT_DISCONNECT) continue; 3592 3593 if (connection->authentication_flags & READ_RSSI){ 3594 connectionClearAuthenticationFlags(connection, READ_RSSI); 3595 hci_send_cmd(&hci_read_rssi, connection->con_handle); 3596 return; 3597 } 3598 3599 #ifdef ENABLE_CLASSIC 3600 if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){ 3601 log_info("responding to link key request"); 3602 connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST); 3603 link_key_t link_key; 3604 link_key_type_t link_key_type; 3605 if ( hci_stack->link_key_db 3606 && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type) 3607 && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){ 3608 connection->link_key_type = link_key_type; 3609 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key); 3610 } else { 3611 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 3612 } 3613 return; 3614 } 3615 3616 if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){ 3617 log_info("denying to pin request"); 3618 connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST); 3619 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 3620 return; 3621 } 3622 3623 if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){ 3624 connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY); 3625 log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability); 3626 if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){ 3627 // tweak authentication requirements 3628 uint8_t authreq = hci_stack->ssp_authentication_requirement; 3629 if (connection->bonding_flags & BONDING_DEDICATED){ 3630 authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 3631 } 3632 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){ 3633 authreq |= 1; 3634 } 3635 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq); 3636 } else { 3637 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 3638 } 3639 return; 3640 } 3641 3642 if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){ 3643 connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY); 3644 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 3645 return; 3646 } 3647 3648 if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){ 3649 connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY); 3650 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 3651 return; 3652 } 3653 3654 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){ 3655 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES; 3656 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 3657 return; 3658 } 3659 3660 if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){ 3661 connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE; 3662 connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT; 3663 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // authentication done 3664 return; 3665 } 3666 3667 if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){ 3668 connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST; 3669 hci_send_cmd(&hci_authentication_requested, connection->con_handle); 3670 return; 3671 } 3672 3673 if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){ 3674 connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST; 3675 hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1); 3676 return; 3677 } 3678 if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){ 3679 connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE; 3680 hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1); 3681 return; 3682 } 3683 #endif 3684 3685 if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){ 3686 connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK; 3687 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005); // authentication failure 3688 return; 3689 } 3690 3691 #ifdef ENABLE_CLASSIC 3692 uint16_t sniff_min_interval; 3693 switch (connection->sniff_min_interval){ 3694 case 0: 3695 break; 3696 case 0xffff: 3697 connection->sniff_min_interval = 0; 3698 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle); 3699 return; 3700 default: 3701 sniff_min_interval = connection->sniff_min_interval; 3702 connection->sniff_min_interval = 0; 3703 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout); 3704 return; 3705 } 3706 #endif 3707 3708 #ifdef ENABLE_BLE 3709 switch (connection->le_con_parameter_update_state){ 3710 // response to L2CAP CON PARAMETER UPDATE REQUEST 3711 case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS: 3712 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 3713 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min, 3714 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 3715 0x0000, 0xffff); 3716 return; 3717 case CON_PARAMETER_UPDATE_REPLY: 3718 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 3719 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min, 3720 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 3721 0x0000, 0xffff); 3722 return; 3723 case CON_PARAMETER_UPDATE_NEGATIVE_REPLY: 3724 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 3725 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE); 3726 return; 3727 default: 3728 break; 3729 } 3730 if (connection->le_phy_update_all_phys != 0xff){ 3731 uint8_t all_phys = connection->le_phy_update_all_phys; 3732 connection->le_phy_update_all_phys = 0xff; 3733 hci_send_cmd(&hci_le_set_phy, connection->con_handle, all_phys, connection->le_phy_update_tx_phys, connection->le_phy_update_rx_phys, connection->le_phy_update_phy_options); 3734 return; 3735 } 3736 #endif 3737 } 3738 3739 hci_connection_t * connection; 3740 switch (hci_stack->state){ 3741 case HCI_STATE_INITIALIZING: 3742 hci_initializing_run(); 3743 break; 3744 3745 case HCI_STATE_HALTING: 3746 3747 log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate); 3748 switch (hci_stack->substate){ 3749 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER: 3750 case HCI_HALTING_DISCONNECT_ALL_TIMER: 3751 3752 #ifdef ENABLE_BLE 3753 #ifdef ENABLE_LE_CENTRAL 3754 // free whitelist entries 3755 { 3756 btstack_linked_list_iterator_t lit; 3757 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 3758 while (btstack_linked_list_iterator_has_next(&lit)){ 3759 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 3760 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry); 3761 btstack_memory_whitelist_entry_free(entry); 3762 } 3763 } 3764 #endif 3765 #endif 3766 // close all open connections 3767 connection = (hci_connection_t *) hci_stack->connections; 3768 if (connection){ 3769 hci_con_handle_t con_handle = (uint16_t) connection->con_handle; 3770 if (!hci_can_send_command_packet_now()) return; 3771 3772 // check state 3773 if (connection->state == SENT_DISCONNECT) return; 3774 connection->state = SENT_DISCONNECT; 3775 3776 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle); 3777 3778 // cancel all l2cap connections right away instead of waiting for disconnection complete event ... 3779 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host 3780 3781 // ... which would be ignored anyway as we shutdown (free) the connection now 3782 hci_shutdown_connection(connection); 3783 3784 // finally, send the disconnect command 3785 hci_send_cmd(&hci_disconnect, con_handle, 0x13); // remote closed connection 3786 return; 3787 } 3788 3789 if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){ 3790 // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event 3791 log_info("HCI_STATE_HALTING: wait 50 ms"); 3792 hci_stack->substate = HCI_HALTING_W4_TIMER; 3793 btstack_run_loop_set_timer(&hci_stack->timeout, 50); 3794 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler); 3795 btstack_run_loop_add_timer(&hci_stack->timeout); 3796 break; 3797 } 3798 3799 /* explicit fall-through */ 3800 3801 case HCI_HALTING_CLOSE: 3802 log_info("HCI_STATE_HALTING, calling off"); 3803 3804 // switch mode 3805 hci_power_control_off(); 3806 3807 log_info("HCI_STATE_HALTING, emitting state"); 3808 hci_emit_state(); 3809 log_info("HCI_STATE_HALTING, done"); 3810 break; 3811 3812 case HCI_HALTING_W4_TIMER: 3813 // keep waiting 3814 3815 break; 3816 default: 3817 break; 3818 } 3819 3820 break; 3821 3822 case HCI_STATE_FALLING_ASLEEP: 3823 switch(hci_stack->substate) { 3824 case HCI_FALLING_ASLEEP_DISCONNECT: 3825 log_info("HCI_STATE_FALLING_ASLEEP"); 3826 // close all open connections 3827 connection = (hci_connection_t *) hci_stack->connections; 3828 3829 #ifdef HAVE_PLATFORM_IPHONE_OS 3830 // don't close connections, if H4 supports power management 3831 if (btstack_control_iphone_power_management_enabled()){ 3832 connection = NULL; 3833 } 3834 #endif 3835 if (connection){ 3836 3837 // send disconnect 3838 if (!hci_can_send_command_packet_now()) return; 3839 3840 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle); 3841 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 3842 3843 // send disconnected event right away - causes higher layer connections to get closed, too. 3844 hci_shutdown_connection(connection); 3845 return; 3846 } 3847 3848 if (hci_classic_supported()){ 3849 // disable page and inquiry scan 3850 if (!hci_can_send_command_packet_now()) return; 3851 3852 log_info("HCI_STATE_HALTING, disabling inq scans"); 3853 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 3854 3855 // continue in next sub state 3856 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE; 3857 break; 3858 } 3859 // no break - fall through for ble-only chips 3860 3861 case HCI_FALLING_ASLEEP_COMPLETE: 3862 log_info("HCI_STATE_HALTING, calling sleep"); 3863 #ifdef HAVE_PLATFORM_IPHONE_OS 3864 // don't actually go to sleep, if H4 supports power management 3865 if (btstack_control_iphone_power_management_enabled()){ 3866 // SLEEP MODE reached 3867 hci_stack->state = HCI_STATE_SLEEPING; 3868 hci_emit_state(); 3869 break; 3870 } 3871 #endif 3872 // switch mode 3873 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 3874 hci_emit_state(); 3875 break; 3876 3877 default: 3878 break; 3879 } 3880 break; 3881 3882 default: 3883 break; 3884 } 3885 } 3886 3887 int hci_send_cmd_packet(uint8_t *packet, int size){ 3888 // house-keeping 3889 3890 if (IS_COMMAND(packet, hci_write_loopback_mode)){ 3891 hci_stack->loopback_mode = packet[3]; 3892 } 3893 3894 #ifdef ENABLE_CLASSIC 3895 bd_addr_t addr; 3896 hci_connection_t * conn; 3897 3898 // create_connection? 3899 if (IS_COMMAND(packet, hci_create_connection)){ 3900 reverse_bd_addr(&packet[3], addr); 3901 log_info("Create_connection to %s", bd_addr_to_str(addr)); 3902 3903 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 3904 if (!conn){ 3905 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 3906 if (!conn){ 3907 // notify client that alloc failed 3908 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 3909 return -1; // packet not sent to controller 3910 } 3911 conn->state = SEND_CREATE_CONNECTION; 3912 } 3913 log_info("conn state %u", conn->state); 3914 switch (conn->state){ 3915 // if connection active exists 3916 case OPEN: 3917 // and OPEN, emit connection complete command 3918 hci_emit_connection_complete(addr, conn->con_handle, 0); 3919 return -1; // packet not sent to controller 3920 case SEND_CREATE_CONNECTION: 3921 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now 3922 break; 3923 default: 3924 // otherwise, just ignore as it is already in the open process 3925 return -1; // packet not sent to controller 3926 } 3927 conn->state = SENT_CREATE_CONNECTION; 3928 3929 // track outgoing connection 3930 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_CLASSIC; 3931 memcpy(hci_stack->outgoing_addr, addr, 6); 3932 } 3933 3934 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 3935 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 3936 } 3937 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 3938 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 3939 } 3940 3941 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 3942 if (hci_stack->link_key_db){ 3943 reverse_bd_addr(&packet[3], addr); 3944 hci_stack->link_key_db->delete_link_key(addr); 3945 } 3946 } 3947 3948 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply) 3949 || IS_COMMAND(packet, hci_pin_code_request_reply)){ 3950 reverse_bd_addr(&packet[3], addr); 3951 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 3952 if (conn){ 3953 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE); 3954 } 3955 } 3956 3957 if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply) 3958 || IS_COMMAND(packet, hci_user_confirmation_request_reply) 3959 || IS_COMMAND(packet, hci_user_passkey_request_negative_reply) 3960 || IS_COMMAND(packet, hci_user_passkey_request_reply)) { 3961 reverse_bd_addr(&packet[3], addr); 3962 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 3963 if (conn){ 3964 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE); 3965 } 3966 } 3967 3968 #ifdef ENABLE_SCO_OVER_HCI 3969 // setup_synchronous_connection? Voice setting at offset 22 3970 if (IS_COMMAND(packet, hci_setup_synchronous_connection)){ 3971 // TODO: compare to current setting if sco connection already active 3972 hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15); 3973 } 3974 // accept_synchronus_connection? Voice setting at offset 18 3975 if (IS_COMMAND(packet, hci_accept_synchronous_connection)){ 3976 // TODO: compare to current setting if sco connection already active 3977 hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19); 3978 } 3979 #endif 3980 #endif 3981 3982 #ifdef ENABLE_BLE 3983 if (IS_COMMAND(packet, hci_le_set_random_address)){ 3984 hci_stack->le_random_address_set = 1; 3985 reverse_bd_addr(&packet[3], hci_stack->le_random_address); 3986 } 3987 #ifdef ENABLE_LE_PERIPHERAL 3988 if (IS_COMMAND(packet, hci_le_set_advertise_enable)){ 3989 hci_stack->le_advertisements_active = packet[3]; 3990 } 3991 #endif 3992 #ifdef ENABLE_LE_CENTRAL 3993 if (IS_COMMAND(packet, hci_le_create_connection)){ 3994 // white list used? 3995 uint8_t initiator_filter_policy = packet[7]; 3996 switch (initiator_filter_policy){ 3997 case 0: 3998 // whitelist not used 3999 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT; 4000 break; 4001 case 1: 4002 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST; 4003 break; 4004 default: 4005 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy); 4006 break; 4007 } 4008 } 4009 if (IS_COMMAND(packet, hci_le_create_connection_cancel)){ 4010 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 4011 } 4012 #endif 4013 #endif 4014 4015 hci_stack->num_cmd_packets--; 4016 4017 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 4018 return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 4019 } 4020 4021 // disconnect because of security block 4022 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 4023 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4024 if (!connection) return; 4025 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 4026 } 4027 4028 4029 // Configure Secure Simple Pairing 4030 4031 #ifdef ENABLE_CLASSIC 4032 4033 // enable will enable SSP during init 4034 void gap_ssp_set_enable(int enable){ 4035 hci_stack->ssp_enable = enable; 4036 } 4037 4038 static int hci_local_ssp_activated(void){ 4039 return gap_ssp_supported() && hci_stack->ssp_enable; 4040 } 4041 4042 // if set, BTstack will respond to io capability request using authentication requirement 4043 void gap_ssp_set_io_capability(int io_capability){ 4044 hci_stack->ssp_io_capability = io_capability; 4045 } 4046 void gap_ssp_set_authentication_requirement(int authentication_requirement){ 4047 hci_stack->ssp_authentication_requirement = authentication_requirement; 4048 } 4049 4050 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 4051 void gap_ssp_set_auto_accept(int auto_accept){ 4052 hci_stack->ssp_auto_accept = auto_accept; 4053 } 4054 #endif 4055 4056 // va_list part of hci_send_cmd 4057 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){ 4058 if (!hci_can_send_command_packet_now()){ 4059 log_error("hci_send_cmd called but cannot send packet now"); 4060 return 0; 4061 } 4062 4063 // for HCI INITIALIZATION 4064 // log_info("hci_send_cmd: opcode %04x", cmd->opcode); 4065 hci_stack->last_cmd_opcode = cmd->opcode; 4066 4067 hci_reserve_packet_buffer(); 4068 uint8_t * packet = hci_stack->hci_packet_buffer; 4069 uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr); 4070 int err = hci_send_cmd_packet(packet, size); 4071 4072 // release packet buffer for synchronous transport implementations 4073 if (hci_transport_synchronous()){ 4074 hci_release_packet_buffer(); 4075 hci_emit_transport_packet_sent(); 4076 } 4077 4078 return err; 4079 } 4080 4081 /** 4082 * pre: numcmds >= 0 - it's allowed to send a command to the controller 4083 */ 4084 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 4085 va_list argptr; 4086 va_start(argptr, cmd); 4087 int res = hci_send_cmd_va_arg(cmd, argptr); 4088 va_end(argptr); 4089 return res; 4090 } 4091 4092 // Create various non-HCI events. 4093 // TODO: generalize, use table similar to hci_create_command 4094 4095 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){ 4096 // dump packet 4097 if (dump) { 4098 hci_dump_packet( HCI_EVENT_PACKET, 0, event, size); 4099 } 4100 4101 // dispatch to all event handlers 4102 btstack_linked_list_iterator_t it; 4103 btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers); 4104 while (btstack_linked_list_iterator_has_next(&it)){ 4105 btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it); 4106 entry->callback(HCI_EVENT_PACKET, 0, event, size); 4107 } 4108 } 4109 4110 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){ 4111 if (!hci_stack->acl_packet_handler) return; 4112 hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size); 4113 } 4114 4115 #ifdef ENABLE_CLASSIC 4116 static void hci_notify_if_sco_can_send_now(void){ 4117 // notify SCO sender if waiting 4118 if (!hci_stack->sco_waiting_for_can_send_now) return; 4119 if (hci_can_send_sco_packet_now()){ 4120 hci_stack->sco_waiting_for_can_send_now = 0; 4121 uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 }; 4122 hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event)); 4123 hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event)); 4124 } 4125 } 4126 4127 // parsing end emitting has been merged to reduce code size 4128 static void gap_inquiry_explode(uint8_t * packet){ 4129 uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN]; 4130 4131 uint8_t * eir_data; 4132 ad_context_t context; 4133 const uint8_t * name; 4134 uint8_t name_len; 4135 4136 int event_type = hci_event_packet_get_type(packet); 4137 int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1; // 2 for old event, 1 otherwise 4138 int num_responses = hci_event_inquiry_result_get_num_responses(packet); 4139 4140 // event[1] is set at the end 4141 int i; 4142 for (i=0; i<num_responses;i++){ 4143 memset(event, 0, sizeof(event)); 4144 event[0] = GAP_EVENT_INQUIRY_RESULT; 4145 uint8_t event_size = 18; // if name is not set by EIR 4146 4147 memcpy(&event[2], &packet[3 + i*6], 6); // bd_addr 4148 event[8] = packet[3 + num_responses*(6) + i*1]; // page_scan_repetition_mode 4149 memcpy(&event[9], &packet[3 + num_responses*(6+1+num_reserved_fields) + i*3], 3); // class of device 4150 memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset 4151 4152 switch (event_type){ 4153 case HCI_EVENT_INQUIRY_RESULT: 4154 // 14,15,16,17 = 0, size 18 4155 break; 4156 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 4157 event[14] = 1; 4158 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi 4159 // 16,17 = 0, size 18 4160 break; 4161 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 4162 event[14] = 1; 4163 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi 4164 // for EIR packets, there is only one reponse in it 4165 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)]; 4166 name = NULL; 4167 // EIR data is 240 bytes in EIR event 4168 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){ 4169 uint8_t data_type = ad_iterator_get_data_type(&context); 4170 uint8_t data_size = ad_iterator_get_data_len(&context); 4171 const uint8_t * data = ad_iterator_get_data(&context); 4172 // Prefer Complete Local Name over Shortend Local Name 4173 switch (data_type){ 4174 case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME: 4175 if (name) continue; 4176 /* explicit fall-through */ 4177 case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME: 4178 name = data; 4179 name_len = data_size; 4180 break; 4181 default: 4182 break; 4183 } 4184 } 4185 if (name){ 4186 event[16] = 1; 4187 // truncate name if needed 4188 int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN); 4189 event[17] = len; 4190 memcpy(&event[18], name, len); 4191 event_size += len; 4192 } 4193 break; 4194 } 4195 event[1] = event_size - 2; 4196 hci_emit_event(event, event_size, 1); 4197 } 4198 } 4199 #endif 4200 4201 void hci_emit_state(void){ 4202 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 4203 uint8_t event[3]; 4204 event[0] = BTSTACK_EVENT_STATE; 4205 event[1] = sizeof(event) - 2; 4206 event[2] = hci_stack->state; 4207 hci_emit_event(event, sizeof(event), 1); 4208 } 4209 4210 #ifdef ENABLE_CLASSIC 4211 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){ 4212 uint8_t event[13]; 4213 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 4214 event[1] = sizeof(event) - 2; 4215 event[2] = status; 4216 little_endian_store_16(event, 3, con_handle); 4217 reverse_bd_addr(address, &event[5]); 4218 event[11] = 1; // ACL connection 4219 event[12] = 0; // encryption disabled 4220 hci_emit_event(event, sizeof(event), 1); 4221 } 4222 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 4223 if (disable_l2cap_timeouts) return; 4224 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 4225 uint8_t event[4]; 4226 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 4227 event[1] = sizeof(event) - 2; 4228 little_endian_store_16(event, 2, conn->con_handle); 4229 hci_emit_event(event, sizeof(event), 1); 4230 } 4231 #endif 4232 4233 #ifdef ENABLE_BLE 4234 #ifdef ENABLE_LE_CENTRAL 4235 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){ 4236 uint8_t event[21]; 4237 event[0] = HCI_EVENT_LE_META; 4238 event[1] = sizeof(event) - 2; 4239 event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE; 4240 event[3] = status; 4241 little_endian_store_16(event, 4, con_handle); 4242 event[6] = 0; // TODO: role 4243 event[7] = address_type; 4244 reverse_bd_addr(address, &event[8]); 4245 little_endian_store_16(event, 14, 0); // interval 4246 little_endian_store_16(event, 16, 0); // latency 4247 little_endian_store_16(event, 18, 0); // supervision timeout 4248 event[20] = 0; // master clock accuracy 4249 hci_emit_event(event, sizeof(event), 1); 4250 } 4251 #endif 4252 #endif 4253 4254 static void hci_emit_transport_packet_sent(void){ 4255 // notify upper stack that it might be possible to send again 4256 uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0}; 4257 hci_emit_event(&event[0], sizeof(event), 0); // don't dump 4258 } 4259 4260 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){ 4261 uint8_t event[6]; 4262 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 4263 event[1] = sizeof(event) - 2; 4264 event[2] = 0; // status = OK 4265 little_endian_store_16(event, 3, con_handle); 4266 event[5] = reason; 4267 hci_emit_event(event, sizeof(event), 1); 4268 } 4269 4270 static void hci_emit_nr_connections_changed(void){ 4271 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 4272 uint8_t event[3]; 4273 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 4274 event[1] = sizeof(event) - 2; 4275 event[2] = nr_hci_connections(); 4276 hci_emit_event(event, sizeof(event), 1); 4277 } 4278 4279 static void hci_emit_hci_open_failed(void){ 4280 log_info("BTSTACK_EVENT_POWERON_FAILED"); 4281 uint8_t event[2]; 4282 event[0] = BTSTACK_EVENT_POWERON_FAILED; 4283 event[1] = sizeof(event) - 2; 4284 hci_emit_event(event, sizeof(event), 1); 4285 } 4286 4287 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){ 4288 log_info("hci_emit_dedicated_bonding_result %u ", status); 4289 uint8_t event[9]; 4290 int pos = 0; 4291 event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED; 4292 event[pos++] = sizeof(event) - 2; 4293 event[pos++] = status; 4294 reverse_bd_addr(address, &event[pos]); 4295 hci_emit_event(event, sizeof(event), 1); 4296 } 4297 4298 4299 #ifdef ENABLE_CLASSIC 4300 4301 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 4302 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 4303 uint8_t event[5]; 4304 int pos = 0; 4305 event[pos++] = GAP_EVENT_SECURITY_LEVEL; 4306 event[pos++] = sizeof(event) - 2; 4307 little_endian_store_16(event, 2, con_handle); 4308 pos += 2; 4309 event[pos++] = level; 4310 hci_emit_event(event, sizeof(event), 1); 4311 } 4312 4313 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 4314 if (!connection) return LEVEL_0; 4315 if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 4316 if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0; 4317 gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type); 4318 // LEVEL 4 always requires 128 bit encrytion key size 4319 if (security_level == LEVEL_4 && connection->encryption_key_size < 16){ 4320 security_level = LEVEL_3; 4321 } 4322 return security_level; 4323 } 4324 4325 static void hci_emit_discoverable_enabled(uint8_t enabled){ 4326 log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled); 4327 uint8_t event[3]; 4328 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 4329 event[1] = sizeof(event) - 2; 4330 event[2] = enabled; 4331 hci_emit_event(event, sizeof(event), 1); 4332 } 4333 4334 // query if remote side supports eSCO 4335 int hci_remote_esco_supported(hci_con_handle_t con_handle){ 4336 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4337 if (!connection) return 0; 4338 return connection->remote_supported_feature_eSCO; 4339 } 4340 4341 // query if remote side supports SSP 4342 int hci_remote_ssp_supported(hci_con_handle_t con_handle){ 4343 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4344 if (!connection) return 0; 4345 return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0; 4346 } 4347 4348 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){ 4349 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 4350 } 4351 4352 // GAP API 4353 /** 4354 * @bbrief enable/disable bonding. default is enabled 4355 * @praram enabled 4356 */ 4357 void gap_set_bondable_mode(int enable){ 4358 hci_stack->bondable = enable ? 1 : 0; 4359 } 4360 /** 4361 * @brief Get bondable mode. 4362 * @return 1 if bondable 4363 */ 4364 int gap_get_bondable_mode(void){ 4365 return hci_stack->bondable; 4366 } 4367 4368 /** 4369 * @brief map link keys to security levels 4370 */ 4371 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 4372 switch (link_key_type){ 4373 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 4374 return LEVEL_4; 4375 case COMBINATION_KEY: 4376 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 4377 return LEVEL_3; 4378 default: 4379 return LEVEL_2; 4380 } 4381 } 4382 4383 /** 4384 * @brief map link keys to secure connection yes/no 4385 */ 4386 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){ 4387 switch (link_key_type){ 4388 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 4389 case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 4390 return 1; 4391 default: 4392 return 0; 4393 } 4394 } 4395 4396 /** 4397 * @brief map link keys to authenticated 4398 */ 4399 int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){ 4400 switch (link_key_type){ 4401 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 4402 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 4403 return 1; 4404 default: 4405 return 0; 4406 } 4407 } 4408 4409 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 4410 log_info("gap_mitm_protection_required_for_security_level %u", level); 4411 return level > LEVEL_2; 4412 } 4413 4414 /** 4415 * @brief get current security level 4416 */ 4417 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 4418 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4419 if (!connection) return LEVEL_0; 4420 return gap_security_level_for_connection(connection); 4421 } 4422 4423 /** 4424 * @brief request connection to device to 4425 * @result GAP_AUTHENTICATION_RESULT 4426 */ 4427 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 4428 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4429 if (!connection){ 4430 hci_emit_security_level(con_handle, LEVEL_0); 4431 return; 4432 } 4433 gap_security_level_t current_level = gap_security_level(con_handle); 4434 log_info("gap_request_security_level requested level %u, planned level %u, current level %u", 4435 requested_level, connection->requested_security_level, current_level); 4436 4437 // assumption: earlier requested security higher than current level => security request is active 4438 if (current_level < connection->requested_security_level){ 4439 if (connection->requested_security_level < requested_level){ 4440 // increase requested level as new level is higher 4441 4442 // TODO: handle re-authentication when done 4443 4444 connection->requested_security_level = requested_level; 4445 } 4446 return; 4447 } 4448 4449 // no request active, notify if security sufficient 4450 if (requested_level <= current_level){ 4451 hci_emit_security_level(con_handle, current_level); 4452 return; 4453 } 4454 4455 // start pairing to increase security level 4456 connection->requested_security_level = requested_level; 4457 4458 #if 0 4459 // sending encryption request without a link key results in an error. 4460 // TODO: figure out how to use it properly 4461 4462 // would enabling ecnryption suffice (>= LEVEL_2)? 4463 if (hci_stack->link_key_db){ 4464 link_key_type_t link_key_type; 4465 link_key_t link_key; 4466 if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){ 4467 if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){ 4468 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 4469 return; 4470 } 4471 } 4472 } 4473 #endif 4474 4475 // start to authenticate connection 4476 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 4477 hci_run(); 4478 } 4479 4480 /** 4481 * @brief start dedicated bonding with device. disconnect after bonding 4482 * @param device 4483 * @param request MITM protection 4484 * @result GAP_DEDICATED_BONDING_COMPLETE 4485 */ 4486 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 4487 4488 // create connection state machine 4489 hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC); 4490 4491 if (!connection){ 4492 return BTSTACK_MEMORY_ALLOC_FAILED; 4493 } 4494 4495 // delete linkn key 4496 gap_drop_link_key_for_bd_addr(device); 4497 4498 // configure LEVEL_2/3, dedicated bonding 4499 connection->state = SEND_CREATE_CONNECTION; 4500 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 4501 log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level); 4502 connection->bonding_flags = BONDING_DEDICATED; 4503 4504 // wait for GAP Security Result and send GAP Dedicated Bonding complete 4505 4506 // handle: connnection failure (connection complete != ok) 4507 // handle: authentication failure 4508 // handle: disconnect on done 4509 4510 hci_run(); 4511 4512 return 0; 4513 } 4514 #endif 4515 4516 void gap_set_local_name(const char * local_name){ 4517 hci_stack->local_name = local_name; 4518 } 4519 4520 4521 #ifdef ENABLE_BLE 4522 4523 #ifdef ENABLE_LE_CENTRAL 4524 void gap_start_scan(void){ 4525 hci_stack->le_scanning_enabled = 1; 4526 hci_run(); 4527 } 4528 4529 void gap_stop_scan(void){ 4530 hci_stack->le_scanning_enabled = 0; 4531 hci_run(); 4532 } 4533 4534 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){ 4535 hci_stack->le_scan_type = scan_type; 4536 hci_stack->le_scan_interval = scan_interval; 4537 hci_stack->le_scan_window = scan_window; 4538 hci_run(); 4539 } 4540 4541 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){ 4542 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 4543 if (!conn){ 4544 log_info("gap_connect: no connection exists yet, creating context"); 4545 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 4546 if (!conn){ 4547 // notify client that alloc failed 4548 hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 4549 log_info("gap_connect: failed to alloc hci_connection_t"); 4550 return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller 4551 } 4552 conn->state = SEND_CREATE_CONNECTION; 4553 log_info("gap_connect: send create connection next"); 4554 hci_run(); 4555 return 0; 4556 } 4557 4558 if (!hci_is_le_connection(conn) || 4559 conn->state == SEND_CREATE_CONNECTION || 4560 conn->state == SENT_CREATE_CONNECTION) { 4561 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED); 4562 log_error("gap_connect: classic connection or connect is already being created"); 4563 return GATT_CLIENT_IN_WRONG_STATE; 4564 } 4565 4566 log_info("gap_connect: context exists with state %u", conn->state); 4567 hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0); 4568 hci_run(); 4569 return 0; 4570 } 4571 4572 // @assumption: only a single outgoing LE Connection exists 4573 static hci_connection_t * gap_get_outgoing_connection(void){ 4574 btstack_linked_item_t *it; 4575 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 4576 hci_connection_t * conn = (hci_connection_t *) it; 4577 if (!hci_is_le_connection(conn)) continue; 4578 switch (conn->state){ 4579 case SEND_CREATE_CONNECTION: 4580 case SENT_CREATE_CONNECTION: 4581 case SENT_CANCEL_CONNECTION: 4582 return conn; 4583 default: 4584 break; 4585 }; 4586 } 4587 return NULL; 4588 } 4589 4590 uint8_t gap_connect_cancel(void){ 4591 hci_connection_t * conn = gap_get_outgoing_connection(); 4592 if (!conn) return 0; 4593 switch (conn->state){ 4594 case SEND_CREATE_CONNECTION: 4595 // skip sending create connection and emit event instead 4596 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER); 4597 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 4598 btstack_memory_hci_connection_free( conn ); 4599 break; 4600 case SENT_CREATE_CONNECTION: 4601 // request to send cancel connection 4602 conn->state = SEND_CANCEL_CONNECTION; 4603 hci_run(); 4604 break; 4605 default: 4606 break; 4607 } 4608 return 0; 4609 } 4610 #endif 4611 4612 #ifdef ENABLE_LE_CENTRAL 4613 /** 4614 * @brief Set connection parameters for outgoing connections 4615 * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms 4616 * @param conn_scan_window (unit: 0.625 msec), default: 30 ms 4617 * @param conn_interval_min (unit: 1.25ms), default: 10 ms 4618 * @param conn_interval_max (unit: 1.25ms), default: 30 ms 4619 * @param conn_latency, default: 4 4620 * @param supervision_timeout (unit: 10ms), default: 720 ms 4621 * @param min_ce_length (unit: 0.625ms), default: 10 ms 4622 * @param max_ce_length (unit: 0.625ms), default: 30 ms 4623 */ 4624 4625 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window, 4626 uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, 4627 uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){ 4628 hci_stack->le_connection_scan_interval = conn_scan_interval; 4629 hci_stack->le_connection_scan_window = conn_scan_window; 4630 hci_stack->le_connection_interval_min = conn_interval_min; 4631 hci_stack->le_connection_interval_max = conn_interval_max; 4632 hci_stack->le_connection_latency = conn_latency; 4633 hci_stack->le_supervision_timeout = supervision_timeout; 4634 hci_stack->le_minimum_ce_length = min_ce_length; 4635 hci_stack->le_maximum_ce_length = max_ce_length; 4636 } 4637 #endif 4638 4639 /** 4640 * @brief Updates the connection parameters for a given LE connection 4641 * @param handle 4642 * @param conn_interval_min (unit: 1.25ms) 4643 * @param conn_interval_max (unit: 1.25ms) 4644 * @param conn_latency 4645 * @param supervision_timeout (unit: 10ms) 4646 * @returns 0 if ok 4647 */ 4648 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min, 4649 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 4650 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4651 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 4652 connection->le_conn_interval_min = conn_interval_min; 4653 connection->le_conn_interval_max = conn_interval_max; 4654 connection->le_conn_latency = conn_latency; 4655 connection->le_supervision_timeout = supervision_timeout; 4656 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS; 4657 hci_run(); 4658 return 0; 4659 } 4660 4661 /** 4662 * @brief Request an update of the connection parameter for a given LE connection 4663 * @param handle 4664 * @param conn_interval_min (unit: 1.25ms) 4665 * @param conn_interval_max (unit: 1.25ms) 4666 * @param conn_latency 4667 * @param supervision_timeout (unit: 10ms) 4668 * @returns 0 if ok 4669 */ 4670 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min, 4671 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 4672 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4673 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 4674 connection->le_conn_interval_min = conn_interval_min; 4675 connection->le_conn_interval_max = conn_interval_max; 4676 connection->le_conn_latency = conn_latency; 4677 connection->le_supervision_timeout = supervision_timeout; 4678 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST; 4679 hci_run(); 4680 return 0; 4681 } 4682 4683 #ifdef ENABLE_LE_PERIPHERAL 4684 4685 static void gap_advertisments_changed(void){ 4686 // disable advertisements before updating adv, scan data, or adv params 4687 if (hci_stack->le_advertisements_active){ 4688 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE; 4689 } 4690 hci_run(); 4691 } 4692 4693 /** 4694 * @brief Set Advertisement Data 4695 * @param advertising_data_length 4696 * @param advertising_data (max 31 octets) 4697 * @note data is not copied, pointer has to stay valid 4698 */ 4699 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){ 4700 hci_stack->le_advertisements_data_len = advertising_data_length; 4701 hci_stack->le_advertisements_data = advertising_data; 4702 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 4703 gap_advertisments_changed(); 4704 } 4705 4706 /** 4707 * @brief Set Scan Response Data 4708 * @param advertising_data_length 4709 * @param advertising_data (max 31 octets) 4710 * @note data is not copied, pointer has to stay valid 4711 */ 4712 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){ 4713 hci_stack->le_scan_response_data_len = scan_response_data_length; 4714 hci_stack->le_scan_response_data = scan_response_data; 4715 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 4716 gap_advertisments_changed(); 4717 } 4718 4719 /** 4720 * @brief Set Advertisement Parameters 4721 * @param adv_int_min 4722 * @param adv_int_max 4723 * @param adv_type 4724 * @param direct_address_type 4725 * @param direct_address 4726 * @param channel_map 4727 * @param filter_policy 4728 * 4729 * @note internal use. use gap_advertisements_set_params from gap_le.h instead. 4730 */ 4731 void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, 4732 uint8_t direct_address_typ, bd_addr_t direct_address, 4733 uint8_t channel_map, uint8_t filter_policy) { 4734 4735 hci_stack->le_advertisements_interval_min = adv_int_min; 4736 hci_stack->le_advertisements_interval_max = adv_int_max; 4737 hci_stack->le_advertisements_type = adv_type; 4738 hci_stack->le_advertisements_direct_address_type = direct_address_typ; 4739 hci_stack->le_advertisements_channel_map = channel_map; 4740 hci_stack->le_advertisements_filter_policy = filter_policy; 4741 memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6); 4742 4743 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 4744 gap_advertisments_changed(); 4745 } 4746 4747 /** 4748 * @brief Enable/Disable Advertisements 4749 * @param enabled 4750 */ 4751 void gap_advertisements_enable(int enabled){ 4752 hci_stack->le_advertisements_enabled = enabled; 4753 if (enabled && !hci_stack->le_advertisements_active){ 4754 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE; 4755 } 4756 if (!enabled && hci_stack->le_advertisements_active){ 4757 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE; 4758 } 4759 hci_run(); 4760 } 4761 4762 #endif 4763 4764 void hci_le_set_own_address_type(uint8_t own_address_type){ 4765 log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type); 4766 if (own_address_type == hci_stack->le_own_addr_type) return; 4767 hci_stack->le_own_addr_type = own_address_type; 4768 4769 #ifdef ENABLE_LE_PERIPHERAL 4770 // update advertisement parameters, too 4771 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 4772 gap_advertisments_changed(); 4773 #endif 4774 #ifdef ENABLE_LE_CENTRAL 4775 // note: we don't update scan parameters or modify ongoing connection attempts 4776 #endif 4777 } 4778 4779 #endif 4780 4781 uint8_t gap_disconnect(hci_con_handle_t handle){ 4782 hci_connection_t * conn = hci_connection_for_handle(handle); 4783 if (!conn){ 4784 hci_emit_disconnection_complete(handle, 0); 4785 return 0; 4786 } 4787 // ignore if already disconnected 4788 if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){ 4789 return 0; 4790 } 4791 conn->state = SEND_DISCONNECT; 4792 hci_run(); 4793 return 0; 4794 } 4795 4796 /** 4797 * @brief Get connection type 4798 * @param con_handle 4799 * @result connection_type 4800 */ 4801 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){ 4802 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 4803 if (!conn) return GAP_CONNECTION_INVALID; 4804 switch (conn->address_type){ 4805 case BD_ADDR_TYPE_LE_PUBLIC: 4806 case BD_ADDR_TYPE_LE_RANDOM: 4807 return GAP_CONNECTION_LE; 4808 case BD_ADDR_TYPE_SCO: 4809 return GAP_CONNECTION_SCO; 4810 case BD_ADDR_TYPE_CLASSIC: 4811 return GAP_CONNECTION_ACL; 4812 default: 4813 return GAP_CONNECTION_INVALID; 4814 } 4815 } 4816 4817 #ifdef ENABLE_BLE 4818 4819 uint8_t gap_le_set_phy(hci_con_handle_t connection_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){ 4820 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 4821 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 4822 4823 conn->le_phy_update_all_phys = all_phys; 4824 conn->le_phy_update_tx_phys = tx_phys; 4825 conn->le_phy_update_rx_phys = rx_phys; 4826 conn->le_phy_update_phy_options = phy_options; 4827 4828 hci_run(); 4829 4830 return 0; 4831 } 4832 4833 #ifdef ENABLE_LE_CENTRAL 4834 /** 4835 * @brief Auto Connection Establishment - Start Connecting to device 4836 * @param address_typ 4837 * @param address 4838 * @returns 0 if ok 4839 */ 4840 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){ 4841 // check capacity 4842 int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist); 4843 if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED; 4844 whitelist_entry_t * entry = btstack_memory_whitelist_entry_get(); 4845 if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED; 4846 entry->address_type = address_type; 4847 memcpy(entry->address, address, 6); 4848 entry->state = LE_WHITELIST_ADD_TO_CONTROLLER; 4849 btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry); 4850 hci_run(); 4851 return 0; 4852 } 4853 4854 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){ 4855 btstack_linked_list_iterator_t it; 4856 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 4857 while (btstack_linked_list_iterator_has_next(&it)){ 4858 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it); 4859 if (entry->address_type != address_type) continue; 4860 if (memcmp(entry->address, address, 6) != 0) continue; 4861 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 4862 // remove from controller if already present 4863 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 4864 continue; 4865 } 4866 // direclty remove entry from whitelist 4867 btstack_linked_list_iterator_remove(&it); 4868 btstack_memory_whitelist_entry_free(entry); 4869 } 4870 } 4871 4872 /** 4873 * @brief Auto Connection Establishment - Stop Connecting to device 4874 * @param address_typ 4875 * @param address 4876 * @returns 0 if ok 4877 */ 4878 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){ 4879 hci_remove_from_whitelist(address_type, address); 4880 hci_run(); 4881 return 0; 4882 } 4883 4884 /** 4885 * @brief Auto Connection Establishment - Stop everything 4886 * @note Convenience function to stop all active auto connection attempts 4887 */ 4888 void gap_auto_connection_stop_all(void){ 4889 btstack_linked_list_iterator_t it; 4890 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 4891 while (btstack_linked_list_iterator_has_next(&it)){ 4892 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it); 4893 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 4894 // remove from controller if already present 4895 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 4896 continue; 4897 } 4898 // directly remove entry from whitelist 4899 btstack_linked_list_iterator_remove(&it); 4900 btstack_memory_whitelist_entry_free(entry); 4901 } 4902 hci_run(); 4903 } 4904 4905 uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){ 4906 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 4907 if (!conn) return 0; 4908 return conn->le_connection_interval; 4909 } 4910 #endif 4911 #endif 4912 4913 #ifdef ENABLE_CLASSIC 4914 /** 4915 * @brief Set Extended Inquiry Response data 4916 * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup 4917 * @note has to be done before stack starts up 4918 */ 4919 void gap_set_extended_inquiry_response(const uint8_t * data){ 4920 hci_stack->eir_data = data; 4921 } 4922 4923 /** 4924 * @brief Start GAP Classic Inquiry 4925 * @param duration in 1.28s units 4926 * @return 0 if ok 4927 * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE 4928 */ 4929 int gap_inquiry_start(uint8_t duration_in_1280ms_units){ 4930 if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED; 4931 if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 4932 if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){ 4933 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 4934 } 4935 hci_stack->inquiry_state = duration_in_1280ms_units; 4936 hci_run(); 4937 return 0; 4938 } 4939 4940 /** 4941 * @brief Stop GAP Classic Inquiry 4942 * @returns 0 if ok 4943 */ 4944 int gap_inquiry_stop(void){ 4945 if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) { 4946 // emit inquiry complete event, before it even started 4947 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 4948 hci_emit_event(event, sizeof(event), 1); 4949 return 0; 4950 } 4951 if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED; 4952 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL; 4953 hci_run(); 4954 return 0; 4955 } 4956 4957 4958 /** 4959 * @brief Remote Name Request 4960 * @param addr 4961 * @param page_scan_repetition_mode 4962 * @param clock_offset only used when bit 15 is set 4963 * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 4964 */ 4965 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){ 4966 if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 4967 memcpy(hci_stack->remote_name_addr, addr, 6); 4968 hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode; 4969 hci_stack->remote_name_clock_offset = clock_offset; 4970 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND; 4971 hci_run(); 4972 return 0; 4973 } 4974 4975 int gap_read_rssi(hci_con_handle_t con_handle){ 4976 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 4977 if (hci_connection == NULL) return 0; 4978 connectionSetAuthenticationFlags(hci_connection, READ_RSSI); 4979 hci_run(); 4980 return 1; 4981 } 4982 4983 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){ 4984 hci_stack->gap_pairing_state = state; 4985 memcpy(hci_stack->gap_pairing_addr, addr, 6); 4986 hci_run(); 4987 return 0; 4988 } 4989 4990 /** 4991 * @brief Legacy Pairing Pin Code Response 4992 * @param addr 4993 * @param pin 4994 * @return 0 if ok 4995 */ 4996 int gap_pin_code_response(bd_addr_t addr, const char * pin){ 4997 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 4998 hci_stack->gap_pairing_input.gap_pairing_pin = pin; 4999 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN); 5000 } 5001 5002 /** 5003 * @brief Abort Legacy Pairing 5004 * @param addr 5005 * @param pin 5006 * @return 0 if ok 5007 */ 5008 int gap_pin_code_negative(bd_addr_t addr){ 5009 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 5010 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE); 5011 } 5012 5013 /** 5014 * @brief SSP Passkey Response 5015 * @param addr 5016 * @param passkey 5017 * @return 0 if ok 5018 */ 5019 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){ 5020 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 5021 hci_stack->gap_pairing_input.gap_pairing_passkey = passkey; 5022 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY); 5023 } 5024 5025 /** 5026 * @brief Abort SSP Passkey Entry/Pairing 5027 * @param addr 5028 * @param pin 5029 * @return 0 if ok 5030 */ 5031 int gap_ssp_passkey_negative(bd_addr_t addr){ 5032 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 5033 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE); 5034 } 5035 5036 /** 5037 * @brief Accept SSP Numeric Comparison 5038 * @param addr 5039 * @param passkey 5040 * @return 0 if ok 5041 */ 5042 int gap_ssp_confirmation_response(bd_addr_t addr){ 5043 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 5044 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION); 5045 } 5046 5047 /** 5048 * @brief Abort SSP Numeric Comparison/Pairing 5049 * @param addr 5050 * @param pin 5051 * @return 0 if ok 5052 */ 5053 int gap_ssp_confirmation_negative(bd_addr_t addr){ 5054 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 5055 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE); 5056 } 5057 5058 /** 5059 * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on. 5060 * @param inquiry_mode see bluetooth_defines.h 5061 */ 5062 void hci_set_inquiry_mode(inquiry_mode_t mode){ 5063 hci_stack->inquiry_mode = mode; 5064 } 5065 5066 /** 5067 * @brief Configure Voice Setting for use with SCO data in HSP/HFP 5068 */ 5069 void hci_set_sco_voice_setting(uint16_t voice_setting){ 5070 hci_stack->sco_voice_setting = voice_setting; 5071 } 5072 5073 /** 5074 * @brief Get SCO Voice Setting 5075 * @return current voice setting 5076 */ 5077 uint16_t hci_get_sco_voice_setting(void){ 5078 return hci_stack->sco_voice_setting; 5079 } 5080 5081 #ifdef ENABLE_CLASSIC 5082 static int hci_have_usb_transport(void){ 5083 if (!hci_stack->hci_transport) return 0; 5084 const char * transport_name = hci_stack->hci_transport->name; 5085 if (!transport_name) return 0; 5086 return (transport_name[0] == 'H') && (transport_name[1] == '2'); 5087 } 5088 #endif 5089 5090 /** @brief Get SCO packet length for current SCO Voice setting 5091 * @note Using SCO packets of the exact length is required for USB transfer 5092 * @return Length of SCO packets in bytes (not audio frames) 5093 */ 5094 int hci_get_sco_packet_length(void){ 5095 int sco_packet_length = 0; 5096 5097 #ifdef ENABLE_CLASSIC 5098 #ifdef ENABLE_SCO_OVER_HCI 5099 5100 // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes 5101 int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2; 5102 5103 if (hci_have_usb_transport()){ 5104 // see Core Spec for H2 USB Transfer. 5105 // 3 byte SCO header + 24 bytes per connection 5106 int num_sco_connections = btstack_max(1, hci_number_sco_connections()); 5107 sco_packet_length = 3 + 24 * num_sco_connections * multiplier; 5108 } else { 5109 // 3 byte SCO header + SCO packet size over the air (60 bytes) 5110 sco_packet_length = 3 + 60 * multiplier; 5111 // assert that it still fits inside an SCO buffer 5112 if (sco_packet_length > hci_stack->sco_data_packet_length){ 5113 sco_packet_length = 3 + 60; 5114 } 5115 } 5116 #endif 5117 #endif 5118 return sco_packet_length; 5119 } 5120 5121 /** 5122 * @brief Sets the master/slave policy 5123 * @param policy (0: attempt to become master, 1: let connecting device decide) 5124 */ 5125 void hci_set_master_slave_policy(uint8_t policy){ 5126 hci_stack->master_slave_policy = policy; 5127 } 5128 5129 #endif 5130 5131 HCI_STATE hci_get_state(void){ 5132 return hci_stack->state; 5133 } 5134 5135 #ifdef ENABLE_CLASSIC 5136 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr)){ 5137 hci_stack->gap_classic_accept_callback = accept_callback; 5138 } 5139 #endif 5140 5141 /** 5142 * @brief Set callback for Bluetooth Hardware Error 5143 */ 5144 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){ 5145 hci_stack->hardware_error_callback = fn; 5146 } 5147 5148 void hci_disconnect_all(void){ 5149 btstack_linked_list_iterator_t it; 5150 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 5151 while (btstack_linked_list_iterator_has_next(&it)){ 5152 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 5153 if (con->state == SENT_DISCONNECT) continue; 5154 con->state = SEND_DISCONNECT; 5155 } 5156 hci_run(); 5157 } 5158 5159 uint16_t hci_get_manufacturer(void){ 5160 return hci_stack->manufacturer; 5161 } 5162 5163 #ifdef ENABLE_BLE 5164 5165 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){ 5166 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 5167 if (!hci_con) return NULL; 5168 return &hci_con->sm_connection; 5169 } 5170 5171 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build 5172 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated 5173 5174 int gap_encryption_key_size(hci_con_handle_t con_handle){ 5175 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 5176 if (hci_connection == NULL) return 0; 5177 if (hci_is_le_connection(hci_connection)){ 5178 sm_connection_t * sm_conn = &hci_connection->sm_connection; 5179 if (sm_conn->sm_connection_encrypted) { 5180 return sm_conn->sm_actual_encryption_key_size; 5181 } 5182 } 5183 #ifdef ENABLE_CLASSIC 5184 else { 5185 if ((hci_connection->authentication_flags & CONNECTION_ENCRYPTED)){ 5186 return hci_connection->encryption_key_size; 5187 } 5188 } 5189 #endif 5190 return 0; 5191 } 5192 5193 int gap_authenticated(hci_con_handle_t con_handle){ 5194 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 5195 if (hci_connection == NULL) return 0; 5196 5197 switch (hci_connection->address_type){ 5198 case BD_ADDR_TYPE_LE_PUBLIC: 5199 case BD_ADDR_TYPE_LE_RANDOM: 5200 if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated 5201 return hci_connection->sm_connection.sm_connection_authenticated; 5202 #ifdef ENABLE_CLASSIC 5203 case BD_ADDR_TYPE_SCO: 5204 case BD_ADDR_TYPE_CLASSIC: 5205 return gap_authenticated_for_link_key_type(hci_connection->link_key_type); 5206 #endif 5207 default: 5208 return 0; 5209 } 5210 } 5211 5212 int gap_secure_connection(hci_con_handle_t con_handle){ 5213 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 5214 if (hci_connection == NULL) return 0; 5215 5216 switch (hci_connection->address_type){ 5217 case BD_ADDR_TYPE_LE_PUBLIC: 5218 case BD_ADDR_TYPE_LE_RANDOM: 5219 if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated 5220 return hci_connection->sm_connection.sm_connection_sc; 5221 #ifdef ENABLE_CLASSIC 5222 case BD_ADDR_TYPE_SCO: 5223 case BD_ADDR_TYPE_CLASSIC: 5224 return gap_secure_connection_for_link_key_type(hci_connection->link_key_type); 5225 #endif 5226 default: 5227 return 0; 5228 } 5229 } 5230 5231 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){ 5232 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5233 if (!sm_conn) return AUTHORIZATION_UNKNOWN; // wrong connection 5234 if (!sm_conn->sm_connection_encrypted) return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized 5235 if (!sm_conn->sm_connection_authenticated) return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized 5236 return sm_conn->sm_connection_authorization_state; 5237 } 5238 #endif 5239 5240 #ifdef ENABLE_CLASSIC 5241 uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){ 5242 hci_connection_t * conn = hci_connection_for_handle(con_handle); 5243 if (!conn) return GAP_CONNECTION_INVALID; 5244 conn->sniff_min_interval = sniff_min_interval; 5245 conn->sniff_max_interval = sniff_max_interval; 5246 conn->sniff_attempt = sniff_attempt; 5247 conn->sniff_timeout = sniff_timeout; 5248 hci_run(); 5249 return 0; 5250 } 5251 5252 /** 5253 * @brief Exit Sniff mode 5254 * @param con_handle 5255 @ @return 0 if ok 5256 */ 5257 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){ 5258 hci_connection_t * conn = hci_connection_for_handle(con_handle); 5259 if (!conn) return GAP_CONNECTION_INVALID; 5260 conn->sniff_min_interval = 0xffff; 5261 hci_run(); 5262 return 0; 5263 } 5264 #endif 5265 5266 void hci_halting_defer(void){ 5267 if (hci_stack->state != HCI_STATE_HALTING) return; 5268 switch (hci_stack->substate){ 5269 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER: 5270 case HCI_HALTING_CLOSE: 5271 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER; 5272 break; 5273 default: 5274 break; 5275 } 5276 } 5277