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