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