1 /* 2 * Copyright (C) 2009 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 * 17 * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS 18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 20 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 21 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 23 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 24 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 25 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 27 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 28 * SUCH DAMAGE. 29 * 30 */ 31 32 /* 33 * hci.c 34 * 35 * Created by Matthias Ringwald on 4/29/09. 36 * 37 */ 38 39 #include "hci.h" 40 41 #include <stdarg.h> 42 #include <string.h> 43 #include <stdio.h> 44 45 #ifndef EMBEDDED 46 #include <unistd.h> // gethostbyname 47 #endif 48 49 #include "btstack_memory.h" 50 #include "debug.h" 51 #include "hci_dump.h" 52 53 #include <btstack/hci_cmds.h> 54 #include <btstack/version.h> 55 56 // tmpe 57 #include "l2cap.h" 58 59 #define HCI_CONNECTION_TIMEOUT_MS 10000 60 61 // the STACK is here 62 static hci_stack_t hci_stack; 63 64 /** 65 * get connection for a given handle 66 * 67 * @return connection OR NULL, if not found 68 */ 69 hci_connection_t * connection_for_handle(hci_con_handle_t con_handle){ 70 linked_item_t *it; 71 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 72 if ( ((hci_connection_t *) it)->con_handle == con_handle){ 73 return (hci_connection_t *) it; 74 } 75 } 76 return NULL; 77 } 78 79 static void hci_connection_timeout_handler(timer_source_t *timer){ 80 hci_connection_t * connection = linked_item_get_user(&timer->item); 81 #ifdef HAVE_TIME 82 struct timeval tv; 83 gettimeofday(&tv, NULL); 84 if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) { 85 // connections might be timed out 86 hci_emit_l2cap_check_timeout(connection); 87 } 88 #endif 89 #ifdef EMBEDDED 90 if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 91 // connections might be timed out 92 hci_emit_l2cap_check_timeout(connection); 93 } 94 #endif 95 run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS); 96 run_loop_add_timer(timer); 97 } 98 99 static void hci_connection_timestamp(hci_connection_t *connection){ 100 #ifdef HAVE_TIME 101 gettimeofday(&connection->timestamp, NULL); 102 #endif 103 #ifdef EMBEDDED 104 connection->timestamp = embedded_get_ticks(); 105 #endif 106 } 107 108 /** 109 * create connection for given address 110 * 111 * @return connection OR NULL, if no memory left 112 */ 113 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){ 114 hci_connection_t * conn = btstack_memory_hci_connection_get(); 115 if (!conn) return NULL; 116 BD_ADDR_COPY(conn->address, addr); 117 conn->con_handle = 0xffff; 118 conn->authentication_flags = AUTH_FLAGS_NONE; 119 linked_item_set_user(&conn->timeout.item, conn); 120 conn->timeout.process = hci_connection_timeout_handler; 121 hci_connection_timestamp(conn); 122 conn->acl_recombination_length = 0; 123 conn->acl_recombination_pos = 0; 124 conn->num_acl_packets_sent = 0; 125 linked_list_add(&hci_stack.connections, (linked_item_t *) conn); 126 return conn; 127 } 128 129 /** 130 * get connection for given address 131 * 132 * @return connection OR NULL, if not found 133 */ 134 static hci_connection_t * connection_for_address(bd_addr_t address){ 135 linked_item_t *it; 136 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 137 if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){ 138 return (hci_connection_t *) it; 139 } 140 } 141 return NULL; 142 } 143 144 /** 145 * add authentication flags and reset timer 146 */ 147 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 148 bd_addr_t addr; 149 bt_flip_addr(addr, *(bd_addr_t *) bd_addr); 150 hci_connection_t * conn = connection_for_address(addr); 151 if (conn) { 152 conn->authentication_flags |= flags; 153 hci_connection_timestamp(conn); 154 } 155 } 156 157 int hci_authentication_active_for_handle(hci_con_handle_t handle){ 158 hci_connection_t * conn = connection_for_handle(handle); 159 if (!conn) return 0; 160 if (!conn->authentication_flags) return 0; 161 if (conn->authentication_flags & SENT_LINK_KEY_REPLY) return 0; 162 if (conn->authentication_flags & RECV_LINK_KEY_NOTIFICATION) return 0; 163 return 1; 164 } 165 166 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){ 167 if (hci_stack.remote_device_db) { 168 hci_stack.remote_device_db->delete_link_key(addr); 169 } 170 } 171 172 173 /** 174 * count connections 175 */ 176 static int nr_hci_connections(void){ 177 int count = 0; 178 linked_item_t *it; 179 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++); 180 return count; 181 } 182 183 /** 184 * Dummy handler called by HCI 185 */ 186 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 187 } 188 189 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){ 190 hci_connection_t * connection = connection_for_handle(handle); 191 if (!connection) { 192 log_error("hci_number_outgoing_packets connectino for handle %u does not exist!\n", handle); 193 return 0; 194 } 195 return connection->num_acl_packets_sent; 196 } 197 198 uint8_t hci_number_free_acl_slots(){ 199 uint8_t free_slots = hci_stack.total_num_acl_packets; 200 linked_item_t *it; 201 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 202 hci_connection_t * connection = (hci_connection_t *) it; 203 if (free_slots < connection->num_acl_packets_sent) { 204 log_error("hci_number_free_acl_slots: sum of outgoing packets > total acl packets!\n"); 205 return 0; 206 } 207 free_slots -= connection->num_acl_packets_sent; 208 } 209 return free_slots; 210 } 211 212 uint16_t hci_max_acl_data_packet_length(){ 213 return hci_stack.acl_data_packet_length; 214 } 215 216 int hci_can_send_packet_now(uint8_t packet_type){ 217 218 // check for async hci transport implementations 219 if (hci_stack.hci_transport->can_send_packet_now){ 220 if (!hci_stack.hci_transport->can_send_packet_now(packet_type)){ 221 return 0; 222 } 223 } 224 225 // check regular Bluetooth flow control 226 switch (packet_type) { 227 case HCI_ACL_DATA_PACKET: 228 return hci_number_free_acl_slots(); 229 case HCI_COMMAND_DATA_PACKET: 230 return hci_stack.num_cmd_packets; 231 default: 232 return 0; 233 } 234 } 235 236 int hci_send_acl_packet(uint8_t *packet, int size){ 237 238 // check for free places on BT module 239 if (!hci_number_free_acl_slots()) return BTSTACK_ACL_BUFFERS_FULL; 240 241 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 242 hci_connection_t *connection = connection_for_handle( con_handle); 243 if (!connection) return 0; 244 hci_connection_timestamp(connection); 245 246 // count packet 247 connection->num_acl_packets_sent++; 248 // log_info("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent); 249 250 // send packet - ignore errors 251 hci_stack.hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 252 253 return 0; 254 } 255 256 static void acl_handler(uint8_t *packet, int size){ 257 258 // get info 259 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 260 hci_connection_t *conn = connection_for_handle(con_handle); 261 uint8_t acl_flags = READ_ACL_FLAGS(packet); 262 uint16_t acl_length = READ_ACL_LENGTH(packet); 263 264 // ignore non-registered handle 265 if (!conn){ 266 log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle); 267 return; 268 } 269 270 // update idle timestamp 271 hci_connection_timestamp(conn); 272 273 // handle different packet types 274 switch (acl_flags & 0x03) { 275 276 case 0x01: // continuation fragment 277 278 // sanity check 279 if (conn->acl_recombination_pos == 0) { 280 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle); 281 return; 282 } 283 284 // append fragment payload (header already stored) 285 memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length ); 286 conn->acl_recombination_pos += acl_length; 287 288 // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length, 289 // conn->acl_recombination_pos, conn->acl_recombination_length); 290 291 // forward complete L2CAP packet if complete. 292 if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header 293 294 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos); 295 // reset recombination buffer 296 conn->acl_recombination_length = 0; 297 conn->acl_recombination_pos = 0; 298 } 299 break; 300 301 case 0x02: { // first fragment 302 303 // sanity check 304 if (conn->acl_recombination_pos) { 305 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle); 306 return; 307 } 308 309 // peek into L2CAP packet! 310 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 311 312 // log_error( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length); 313 314 // compare fragment size to L2CAP packet size 315 if (acl_length >= l2cap_length + 4){ 316 317 // forward fragment as L2CAP packet 318 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4); 319 320 } else { 321 // store first fragment and tweak acl length for complete package 322 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4); 323 conn->acl_recombination_pos = acl_length + 4; 324 conn->acl_recombination_length = l2cap_length; 325 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4); 326 } 327 break; 328 329 } 330 default: 331 log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03); 332 return; 333 } 334 335 // execute main loop 336 hci_run(); 337 } 338 339 static void hci_shutdown_connection(hci_connection_t *conn){ 340 log_info("Connection closed: handle %u, ", conn->con_handle); 341 print_bd_addr( conn->address ); 342 log_info("\n"); 343 344 // cancel all l2cap connections 345 hci_emit_disconnection_complete(conn->con_handle, 0x16); // terminated by local host 346 347 run_loop_remove_timer(&conn->timeout); 348 349 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); 350 btstack_memory_hci_connection_free( conn ); 351 352 // now it's gone 353 hci_emit_nr_connections_changed(); 354 } 355 356 static uint16_t packet_type_sizes[] = { 357 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 358 HCI_ACL_DH1_SIZE, 0, 0, 0, 359 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 360 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 361 }; 362 363 static uint16_t hci_acl_packet_types_for_buffer_size(uint16_t buffer_size){ 364 uint16_t packet_types = 0; 365 int i; 366 for (i=0;i<16;i++){ 367 if (packet_type_sizes[i] == 0) continue; 368 if (packet_type_sizes[i] <= buffer_size){ 369 packet_types |= 1 << i; 370 } 371 } 372 // flip bits for "may not be used" 373 packet_types ^= 0x3306; 374 return packet_types; 375 } 376 377 uint16_t hci_usable_acl_packet_types(void){ 378 return hci_stack.packet_types; 379 } 380 381 // avoid huge local variables 382 static device_name_t device_name; 383 static void event_handler(uint8_t *packet, int size){ 384 bd_addr_t addr; 385 uint8_t link_type; 386 hci_con_handle_t handle; 387 hci_connection_t * conn; 388 int i; 389 390 switch (packet[0]) { 391 392 case HCI_EVENT_COMMAND_COMPLETE: 393 // get num cmd packets 394 // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack.num_cmd_packets, packet[2]); 395 hci_stack.num_cmd_packets = packet[2]; 396 397 if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){ 398 // from offset 5 399 // status 400 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 401 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6); 402 // ignore: SCO data packet len (8) 403 hci_stack.total_num_acl_packets = packet[9]; 404 // ignore: total num SCO packets 405 if (hci_stack.state == HCI_STATE_INITIALIZING){ 406 // determine usable packet types 407 uint16_t max_acl_payload = hci_stack.acl_data_packet_length; 408 if (HCI_ACL_BUFFER_SIZE < max_acl_payload) { 409 max_acl_payload = HCI_ACL_BUFFER_SIZE; 410 } 411 hci_stack.packet_types = hci_acl_packet_types_for_buffer_size(max_acl_payload); 412 413 log_error("hci_read_buffer_size: size %u, count %u, packet types %04x\n", 414 hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets, hci_stack.packet_types); 415 } 416 } 417 if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 418 hci_emit_discoverable_enabled(hci_stack.discoverable); 419 } 420 break; 421 422 case HCI_EVENT_COMMAND_STATUS: 423 // get num cmd packets 424 // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack.num_cmd_packets, packet[3]); 425 hci_stack.num_cmd_packets = packet[3]; 426 break; 427 428 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 429 for (i=0; i<packet[2];i++){ 430 handle = READ_BT_16(packet, 3 + 2*i); 431 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i); 432 conn = connection_for_handle(handle); 433 if (!conn){ 434 log_error("hci_number_completed_packet lists unused con handle %u\n", handle); 435 continue; 436 } 437 conn->num_acl_packets_sent -= num_packets; 438 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent); 439 } 440 break; 441 442 case HCI_EVENT_CONNECTION_REQUEST: 443 bt_flip_addr(addr, &packet[2]); 444 // TODO: eval COD 8-10 445 link_type = packet[11]; 446 log_info("Connection_incoming: "); print_bd_addr(addr); log_info(", type %u\n", link_type); 447 if (link_type == 1) { // ACL 448 conn = connection_for_address(addr); 449 if (!conn) { 450 conn = create_connection_for_addr(addr); 451 } 452 if (!conn) { 453 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 454 hci_stack.decline_reason = 0x0d; 455 BD_ADDR_COPY(hci_stack.decline_addr, addr); 456 break; 457 } 458 conn->state = RECEIVED_CONNECTION_REQUEST; 459 hci_run(); 460 } else { 461 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A) 462 hci_stack.decline_reason = 0x0a; 463 BD_ADDR_COPY(hci_stack.decline_addr, addr); 464 } 465 break; 466 467 case HCI_EVENT_CONNECTION_COMPLETE: 468 // Connection management 469 bt_flip_addr(addr, &packet[5]); 470 log_info("Connection_complete (status=%u)", packet[2]); print_bd_addr(addr); log_info("\n"); 471 conn = connection_for_address(addr); 472 if (conn) { 473 if (!packet[2]){ 474 conn->state = OPEN; 475 conn->con_handle = READ_BT_16(packet, 3); 476 477 // restart timer 478 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 479 run_loop_add_timer(&conn->timeout); 480 481 log_info("New connection: handle %u, ", conn->con_handle); 482 print_bd_addr( conn->address ); 483 log_info("\n"); 484 485 hci_emit_nr_connections_changed(); 486 } else { 487 // connection failed, remove entry 488 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); 489 btstack_memory_hci_connection_free( conn ); 490 491 // if authentication error, also delete link key 492 if (packet[2] == 0x05) { 493 hci_drop_link_key_for_bd_addr(&addr); 494 } 495 } 496 } 497 break; 498 499 case HCI_EVENT_LINK_KEY_REQUEST: 500 log_info("HCI_EVENT_LINK_KEY_REQUEST\n"); 501 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST); 502 if (!hci_stack.remote_device_db) break; 503 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST); 504 hci_run(); 505 // request already answered 506 return; 507 508 case HCI_EVENT_LINK_KEY_NOTIFICATION: 509 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION); 510 if (!hci_stack.remote_device_db) break; 511 bt_flip_addr(addr, &packet[2]); 512 hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]); 513 // still forward event to allow dismiss of pairing dialog 514 break; 515 516 case HCI_EVENT_PIN_CODE_REQUEST: 517 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST); 518 break; 519 520 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 521 if (!hci_stack.remote_device_db) break; 522 if (packet[2]) break; // status not ok 523 bt_flip_addr(addr, &packet[3]); 524 // fix for invalid remote names - terminate on 0xff 525 for (i=0; i<248;i++){ 526 if (packet[9+i] == 0xff){ 527 packet[9+i] = 0; 528 break; 529 } 530 } 531 bzero(&device_name, sizeof(device_name_t)); 532 strncpy((char*) device_name, (char*) &packet[9], 248); 533 hci_stack.remote_device_db->put_name(&addr, &device_name); 534 break; 535 536 case HCI_EVENT_INQUIRY_RESULT: 537 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 538 if (!hci_stack.remote_device_db) break; 539 // first send inq result packet 540 hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size); 541 // then send cached remote names 542 for (i=0; i<packet[2];i++){ 543 bt_flip_addr(addr, &packet[3+i*6]); 544 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){ 545 hci_emit_remote_name_cached(&addr, &device_name); 546 } 547 } 548 return; 549 550 case HCI_EVENT_DISCONNECTION_COMPLETE: 551 if (!packet[2]){ 552 handle = READ_BT_16(packet, 3); 553 hci_connection_t * conn = connection_for_handle(handle); 554 if (conn) { 555 hci_shutdown_connection(conn); 556 } 557 } 558 break; 559 560 case HCI_EVENT_HARDWARE_ERROR: 561 if(hci_stack.control->hw_error){ 562 (*hci_stack.control->hw_error)(); 563 } 564 break; 565 566 default: 567 break; 568 } 569 570 // handle BT initialization 571 if (hci_stack.state == HCI_STATE_INITIALIZING){ 572 // handle H4 synchronization loss on restart 573 // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){ 574 // hci_stack.substate = 0; 575 // } 576 // handle normal init sequence 577 if (hci_stack.substate % 2){ 578 // odd: waiting for event 579 if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){ 580 hci_stack.substate++; 581 } 582 } 583 } 584 585 // help with BT sleep 586 if (hci_stack.state == HCI_STATE_FALLING_ASLEEP 587 && hci_stack.substate == 1 588 && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 589 hci_stack.substate++; 590 } 591 592 hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size); 593 594 // execute main loop 595 hci_run(); 596 } 597 598 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 599 switch (packet_type) { 600 case HCI_EVENT_PACKET: 601 event_handler(packet, size); 602 break; 603 case HCI_ACL_DATA_PACKET: 604 acl_handler(packet, size); 605 break; 606 default: 607 break; 608 } 609 } 610 611 /** Register HCI packet handlers */ 612 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 613 hci_stack.packet_handler = handler; 614 } 615 616 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t * remote_device_db){ 617 618 // reference to use transport layer implementation 619 hci_stack.hci_transport = transport; 620 621 // references to used control implementation 622 hci_stack.control = control; 623 624 // reference to used config 625 hci_stack.config = config; 626 627 // no connections yet 628 hci_stack.connections = NULL; 629 hci_stack.discoverable = 0; 630 631 // higher level handler 632 hci_stack.packet_handler = dummy_handler; 633 634 // store and open remote device db 635 hci_stack.remote_device_db = remote_device_db; 636 if (hci_stack.remote_device_db) { 637 hci_stack.remote_device_db->open(); 638 } 639 640 // register packet handlers with transport 641 transport->register_packet_handler(&packet_handler); 642 } 643 644 void hci_close(){ 645 // close remote device db 646 if (hci_stack.remote_device_db) { 647 hci_stack.remote_device_db->close(); 648 } 649 } 650 651 // State-Module-Driver overview 652 // state module low-level 653 // HCI_STATE_OFF off close 654 // HCI_STATE_INITIALIZING, on open 655 // HCI_STATE_WORKING, on open 656 // HCI_STATE_HALTING, on open 657 // HCI_STATE_SLEEPING, off/sleep close 658 // HCI_STATE_FALLING_ASLEEP on open 659 660 static int hci_power_control_on(void){ 661 662 // power on 663 int err = 0; 664 if (hci_stack.control && hci_stack.control->on){ 665 err = (*hci_stack.control->on)(hci_stack.config); 666 } 667 if (err){ 668 log_error( "POWER_ON failed\n"); 669 hci_emit_hci_open_failed(); 670 return err; 671 } 672 673 // open low-level device 674 err = hci_stack.hci_transport->open(hci_stack.config); 675 if (err){ 676 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 677 if (hci_stack.control && hci_stack.control->off){ 678 (*hci_stack.control->off)(hci_stack.config); 679 } 680 hci_emit_hci_open_failed(); 681 return err; 682 } 683 return 0; 684 } 685 686 static void hci_power_control_off(void){ 687 688 log_info("hci_power_control_off\n"); 689 690 // close low-level device 691 hci_stack.hci_transport->close(hci_stack.config); 692 693 log_info("hci_power_control_off - hci_transport closed\n"); 694 695 // power off 696 if (hci_stack.control && hci_stack.control->off){ 697 (*hci_stack.control->off)(hci_stack.config); 698 } 699 700 log_info("hci_power_control_off - control closed\n"); 701 702 hci_stack.state = HCI_STATE_OFF; 703 } 704 705 static void hci_power_control_sleep(void){ 706 707 log_info("hci_power_control_sleep\n"); 708 709 #if 0 710 // don't close serial port during sleep 711 712 // close low-level device 713 hci_stack.hci_transport->close(hci_stack.config); 714 #endif 715 716 // sleep mode 717 if (hci_stack.control && hci_stack.control->sleep){ 718 (*hci_stack.control->sleep)(hci_stack.config); 719 } 720 721 hci_stack.state = HCI_STATE_SLEEPING; 722 } 723 724 static int hci_power_control_wake(void){ 725 726 log_info("hci_power_control_wake\n"); 727 728 // wake on 729 if (hci_stack.control && hci_stack.control->wake){ 730 (*hci_stack.control->wake)(hci_stack.config); 731 } 732 733 #if 0 734 // open low-level device 735 int err = hci_stack.hci_transport->open(hci_stack.config); 736 if (err){ 737 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 738 if (hci_stack.control && hci_stack.control->off){ 739 (*hci_stack.control->off)(hci_stack.config); 740 } 741 hci_emit_hci_open_failed(); 742 return err; 743 } 744 #endif 745 746 return 0; 747 } 748 749 750 int hci_power_control(HCI_POWER_MODE power_mode){ 751 752 log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state); 753 754 int err = 0; 755 switch (hci_stack.state){ 756 757 case HCI_STATE_OFF: 758 switch (power_mode){ 759 case HCI_POWER_ON: 760 err = hci_power_control_on(); 761 if (err) return err; 762 // set up state machine 763 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 764 hci_stack.state = HCI_STATE_INITIALIZING; 765 hci_stack.substate = 0; 766 break; 767 case HCI_POWER_OFF: 768 // do nothing 769 break; 770 case HCI_POWER_SLEEP: 771 // do nothing (with SLEEP == OFF) 772 break; 773 } 774 break; 775 776 case HCI_STATE_INITIALIZING: 777 switch (power_mode){ 778 case HCI_POWER_ON: 779 // do nothing 780 break; 781 case HCI_POWER_OFF: 782 // no connections yet, just turn it off 783 hci_power_control_off(); 784 break; 785 case HCI_POWER_SLEEP: 786 // no connections yet, just turn it off 787 hci_power_control_sleep(); 788 break; 789 } 790 break; 791 792 case HCI_STATE_WORKING: 793 switch (power_mode){ 794 case HCI_POWER_ON: 795 // do nothing 796 break; 797 case HCI_POWER_OFF: 798 // see hci_run 799 hci_stack.state = HCI_STATE_HALTING; 800 break; 801 case HCI_POWER_SLEEP: 802 // see hci_run 803 hci_stack.state = HCI_STATE_FALLING_ASLEEP; 804 hci_stack.substate = 0; 805 break; 806 } 807 break; 808 809 case HCI_STATE_HALTING: 810 switch (power_mode){ 811 case HCI_POWER_ON: 812 // set up state machine 813 hci_stack.state = HCI_STATE_INITIALIZING; 814 hci_stack.substate = 0; 815 break; 816 case HCI_POWER_OFF: 817 // do nothing 818 break; 819 case HCI_POWER_SLEEP: 820 // see hci_run 821 hci_stack.state = HCI_STATE_FALLING_ASLEEP; 822 hci_stack.substate = 0; 823 break; 824 } 825 break; 826 827 case HCI_STATE_FALLING_ASLEEP: 828 switch (power_mode){ 829 case HCI_POWER_ON: 830 // set up state machine 831 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 832 hci_stack.state = HCI_STATE_INITIALIZING; 833 hci_stack.substate = 0; 834 break; 835 case HCI_POWER_OFF: 836 // see hci_run 837 hci_stack.state = HCI_STATE_HALTING; 838 break; 839 case HCI_POWER_SLEEP: 840 // do nothing 841 break; 842 } 843 break; 844 845 case HCI_STATE_SLEEPING: 846 switch (power_mode){ 847 case HCI_POWER_ON: 848 err = hci_power_control_wake(); 849 if (err) return err; 850 // set up state machine 851 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 852 hci_stack.state = HCI_STATE_INITIALIZING; 853 hci_stack.substate = 0; 854 break; 855 case HCI_POWER_OFF: 856 hci_stack.state = HCI_STATE_HALTING; 857 break; 858 case HCI_POWER_SLEEP: 859 // do nothing 860 break; 861 } 862 break; 863 } 864 865 // create internal event 866 hci_emit_state(); 867 868 // trigger next/first action 869 hci_run(); 870 871 return 0; 872 } 873 874 void hci_discoverable_control(uint8_t enable){ 875 if (enable) enable = 1; // normalize argument 876 877 if (hci_stack.discoverable == enable){ 878 hci_emit_discoverable_enabled(hci_stack.discoverable); 879 return; 880 } 881 882 hci_send_cmd(&hci_write_scan_enable, 2 | enable); // 1 = inq scan, 2 = page scan 883 hci_stack.discoverable = enable; 884 } 885 886 void hci_run(){ 887 888 hci_connection_t * connection; 889 linked_item_t * it; 890 891 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 892 893 // global/non-connection oriented commands - decline incoming connections 894 if (hci_stack.decline_reason){ 895 uint8_t reason = hci_stack.decline_reason; 896 hci_stack.decline_reason = 0; 897 hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason); 898 } 899 900 // send pending HCI commands 901 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 902 903 connection = (hci_connection_t *) it; 904 905 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) { 906 // log_info("hci_run: cannot send command packet\n"); 907 return; 908 } 909 910 if (connection->state == RECEIVED_CONNECTION_REQUEST){ 911 log_info("sending hci_accept_connection_request\n"); 912 hci_send_cmd(&hci_accept_connection_request, connection->address, 1); 913 connection->state = ACCEPTED_CONNECTION_REQUEST; 914 } 915 916 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 917 918 if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){ 919 link_key_t link_key; 920 log_info("responding to link key request\n"); 921 if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){ 922 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key); 923 } else { 924 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 925 } 926 connection->authentication_flags &= ~HANDLE_LINK_KEY_REQUEST; 927 } 928 } 929 930 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 931 932 switch (hci_stack.state){ 933 case HCI_STATE_INITIALIZING: 934 // log_info("hci_init: substate %u\n", hci_stack.substate); 935 if (hci_stack.substate % 2) { 936 // odd: waiting for command completion 937 return; 938 } 939 switch (hci_stack.substate >> 1){ 940 case 0: // RESET 941 hci_send_cmd(&hci_reset); 942 if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){ 943 // skip baud change 944 hci_stack.substate = 4; // >> 1 = 2 945 } 946 break; 947 case 1: // SEND BAUD CHANGE 948 hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_cmd_buffer); 949 hci_send_cmd_packet(hci_stack.hci_cmd_buffer, 3 + hci_stack.hci_cmd_buffer[2]); 950 break; 951 case 2: // LOCAL BAUD CHANGE 952 hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main); 953 hci_stack.substate += 2; 954 // break missing here for fall through 955 956 case 3: 957 // custom initialization 958 if (hci_stack.control && hci_stack.control->next_command){ 959 uint8_t * cmd = (*hci_stack.control->next_command)(hci_stack.config); 960 if (cmd) { 961 int size = 3 + cmd[2]; 962 hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, cmd, size); 963 hci_stack.substate = 4; // more init commands 964 break; 965 } 966 printf("hci_run: init script done\n\r"); 967 } 968 // otherwise continue 969 hci_send_cmd(&hci_read_bd_addr); 970 break; 971 case 4: 972 hci_send_cmd(&hci_read_buffer_size); 973 break; 974 case 5: 975 // ca. 15 sec 976 hci_send_cmd(&hci_write_page_timeout, 0x6000); 977 break; 978 case 6: 979 hci_send_cmd(&hci_write_scan_enable, 2 | hci_stack.discoverable); // page scan 980 break; 981 case 7: 982 #ifndef EMBEDDED 983 { 984 char hostname[30]; 985 gethostname(hostname, 30); 986 hostname[29] = '\0'; 987 hci_send_cmd(&hci_write_local_name, hostname); 988 break; 989 } 990 case 8: 991 #ifdef USE_BLUETOOL 992 hci_send_cmd(&hci_write_class_of_device, 0x007a020c); // Smartphone 993 break; 994 995 case 9: 996 #endif 997 #endif 998 // done. 999 hci_stack.state = HCI_STATE_WORKING; 1000 hci_emit_state(); 1001 break; 1002 default: 1003 break; 1004 } 1005 hci_stack.substate++; 1006 break; 1007 1008 case HCI_STATE_HALTING: 1009 1010 log_info("HCI_STATE_HALTING\n"); 1011 // close all open connections 1012 connection = (hci_connection_t *) hci_stack.connections; 1013 if (connection){ 1014 1015 // send disconnect 1016 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1017 1018 log_info("HCI_STATE_HALTING, connection %lu, handle %u\n", (uintptr_t) connection, (uint16_t)connection->con_handle); 1019 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1020 1021 // send disconnected event right away - causes higher layer connections to get closed, too. 1022 hci_shutdown_connection(connection); 1023 return; 1024 } 1025 log_info("HCI_STATE_HALTING, calling off\n"); 1026 1027 // switch mode 1028 hci_power_control_off(); 1029 1030 log_info("HCI_STATE_HALTING, emitting state\n"); 1031 hci_emit_state(); 1032 log_info("HCI_STATE_HALTING, done\n"); 1033 break; 1034 1035 case HCI_STATE_FALLING_ASLEEP: 1036 switch(hci_stack.substate) { 1037 case 0: 1038 log_info("HCI_STATE_FALLING_ASLEEP\n"); 1039 // close all open connections 1040 connection = (hci_connection_t *) hci_stack.connections; 1041 if (connection){ 1042 1043 // send disconnect 1044 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1045 1046 log_info("HCI_STATE_FALLING_ASLEEP, connection %lu, handle %u\n", (uintptr_t) connection, (uint16_t)connection->con_handle); 1047 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1048 1049 // send disconnected event right away - causes higher layer connections to get closed, too. 1050 hci_shutdown_connection(connection); 1051 return; 1052 } 1053 1054 // disable page and inquiry scan 1055 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1056 1057 log_info("HCI_STATE_HALTING, disabling inq & page scans\n"); 1058 hci_send_cmd(&hci_write_scan_enable, 0); // none 1059 1060 // continue in next sub state 1061 hci_stack.substate++; 1062 break; 1063 case 1: 1064 // wait for command complete "hci_write_scan_enable" in event_handler(); 1065 break; 1066 case 2: 1067 log_info("HCI_STATE_HALTING, calling sleep\n"); 1068 // switch mode 1069 hci_power_control_sleep(); // changes hci_stack.state to SLEEP 1070 hci_emit_state(); 1071 default: 1072 break; 1073 } 1074 break; 1075 1076 default: 1077 break; 1078 } 1079 } 1080 1081 int hci_send_cmd_packet(uint8_t *packet, int size){ 1082 bd_addr_t addr; 1083 hci_connection_t * conn; 1084 // house-keeping 1085 1086 // create_connection? 1087 if (IS_COMMAND(packet, hci_create_connection)){ 1088 bt_flip_addr(addr, &packet[3]); 1089 log_info("Create_connection to "); print_bd_addr(addr); log_info("\n"); 1090 conn = connection_for_address(addr); 1091 if (conn) { 1092 // if connection exists 1093 if (conn->state == OPEN) { 1094 // and OPEN, emit connection complete command 1095 hci_emit_connection_complete(conn, 0); 1096 } 1097 // otherwise, just ignore as it is already in the open process 1098 return 0; // don't sent packet to controller 1099 1100 } 1101 // create connection struct and register, state = SENT_CREATE_CONNECTION 1102 conn = create_connection_for_addr(addr); 1103 if (!conn){ 1104 // notify client that alloc failed 1105 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 1106 return 0; // don't sent packet to controller 1107 } 1108 conn->state = SENT_CREATE_CONNECTION; 1109 } 1110 1111 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 1112 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 1113 } 1114 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 1115 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 1116 } 1117 if (IS_COMMAND(packet, hci_pin_code_request_reply)){ 1118 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY); 1119 } 1120 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){ 1121 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY); 1122 } 1123 1124 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 1125 if (hci_stack.remote_device_db){ 1126 bt_flip_addr(addr, &packet[3]); 1127 hci_stack.remote_device_db->delete_link_key(&addr); 1128 } 1129 } 1130 1131 hci_stack.num_cmd_packets--; 1132 return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 1133 } 1134 1135 /** 1136 * pre: numcmds >= 0 - it's allowed to send a command to the controller 1137 */ 1138 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 1139 va_list argptr; 1140 va_start(argptr, cmd); 1141 uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr); 1142 va_end(argptr); 1143 return hci_send_cmd_packet(hci_stack.hci_cmd_buffer, size); 1144 } 1145 1146 // Create various non-HCI events. 1147 // TODO: generalize, use table similar to hci_create_command 1148 1149 void hci_emit_state(){ 1150 uint8_t event[3]; 1151 event[0] = BTSTACK_EVENT_STATE; 1152 event[1] = sizeof(event) - 2; 1153 event[2] = hci_stack.state; 1154 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1155 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1156 } 1157 1158 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){ 1159 uint8_t event[13]; 1160 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 1161 event[1] = sizeof(event) - 2; 1162 event[2] = status; 1163 bt_store_16(event, 3, conn->con_handle); 1164 bt_flip_addr(&event[5], conn->address); 1165 event[11] = 1; // ACL connection 1166 event[12] = 0; // encryption disabled 1167 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1168 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1169 } 1170 1171 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 1172 uint8_t event[6]; 1173 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 1174 event[1] = sizeof(event) - 2; 1175 event[2] = 0; // status = OK 1176 bt_store_16(event, 3, handle); 1177 event[5] = reason; 1178 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1179 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1180 } 1181 1182 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 1183 uint8_t event[4]; 1184 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 1185 event[1] = sizeof(event) - 2; 1186 bt_store_16(event, 2, conn->con_handle); 1187 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1188 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1189 } 1190 1191 void hci_emit_nr_connections_changed(){ 1192 uint8_t event[3]; 1193 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 1194 event[1] = sizeof(event) - 2; 1195 event[2] = nr_hci_connections(); 1196 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1197 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1198 } 1199 1200 void hci_emit_hci_open_failed(){ 1201 uint8_t event[2]; 1202 event[0] = BTSTACK_EVENT_POWERON_FAILED; 1203 event[1] = sizeof(event) - 2; 1204 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1205 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1206 } 1207 1208 1209 void hci_emit_btstack_version() { 1210 uint8_t event[6]; 1211 event[0] = BTSTACK_EVENT_VERSION; 1212 event[1] = sizeof(event) - 2; 1213 event[2] = BTSTACK_MAJOR; 1214 event[3] = BTSTACK_MINOR; 1215 bt_store_16(event, 4, BTSTACK_REVISION); 1216 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1217 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1218 } 1219 1220 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 1221 uint8_t event[3]; 1222 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 1223 event[1] = sizeof(event) - 2; 1224 event[2] = enabled; 1225 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1226 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1227 } 1228 1229 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){ 1230 uint8_t event[2+1+6+248]; 1231 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 1232 event[1] = sizeof(event) - 2; 1233 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 1234 bt_flip_addr(&event[3], *addr); 1235 memcpy(&event[9], name, 248); 1236 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1237 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1238 } 1239 1240 void hci_emit_discoverable_enabled(uint8_t enabled){ 1241 uint8_t event[3]; 1242 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 1243 event[1] = sizeof(event) - 2; 1244 event[2] = enabled; 1245 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1246 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1247 } 1248