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