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