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