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