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