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 case HCI_EVENT_HARDWARE_ERROR: 496 if(hci_stack.control->hw_error){ 497 (*hci_stack.control->hw_error)(); 498 } 499 break; 500 501 default: 502 break; 503 } 504 505 // handle BT initialization 506 if (hci_stack.state == HCI_STATE_INITIALIZING){ 507 // handle H4 synchronization loss on restart 508 // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){ 509 // hci_stack.substate = 0; 510 // } 511 // handle normal init sequence 512 if (hci_stack.substate % 2){ 513 // odd: waiting for event 514 if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){ 515 hci_stack.substate++; 516 } 517 } 518 } 519 520 // help with BT sleep 521 if (hci_stack.state == HCI_STATE_FALLING_ASLEEP 522 && hci_stack.substate == 1 523 && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 524 hci_stack.substate++; 525 } 526 527 hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size); 528 529 // execute main loop 530 hci_run(); 531 } 532 533 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 534 switch (packet_type) { 535 case HCI_EVENT_PACKET: 536 event_handler(packet, size); 537 break; 538 case HCI_ACL_DATA_PACKET: 539 acl_handler(packet, size); 540 break; 541 default: 542 break; 543 } 544 } 545 546 /** Register HCI packet handlers */ 547 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 548 hci_stack.packet_handler = handler; 549 } 550 551 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t * remote_device_db){ 552 553 // reference to use transport layer implementation 554 hci_stack.hci_transport = transport; 555 556 // references to used control implementation 557 hci_stack.control = control; 558 559 // reference to used config 560 hci_stack.config = config; 561 562 // no connections yet 563 hci_stack.connections = NULL; 564 hci_stack.discoverable = 0; 565 566 // empty cmd buffer 567 hci_stack.hci_cmd_buffer = malloc(3+255); 568 569 // higher level handler 570 hci_stack.packet_handler = dummy_handler; 571 572 // store and open remote device db 573 hci_stack.remote_device_db = remote_device_db; 574 if (hci_stack.remote_device_db) { 575 hci_stack.remote_device_db->open(); 576 } 577 578 // register packet handlers with transport 579 transport->register_packet_handler(&packet_handler); 580 } 581 582 void hci_close(){ 583 // close remote device db 584 if (hci_stack.remote_device_db) { 585 hci_stack.remote_device_db->close(); 586 } 587 } 588 589 // State-Module-Driver overview 590 // state module low-level 591 // HCI_STATE_OFF off close 592 // HCI_STATE_INITIALIZING, on open 593 // HCI_STATE_WORKING, on open 594 // HCI_STATE_HALTING, on open 595 // HCI_STATE_SLEEPING, off/sleep close 596 // HCI_STATE_FALLING_ASLEEP on open 597 598 static int hci_power_control_on(void){ 599 600 // power on 601 int err = 0; 602 if (hci_stack.control && hci_stack.control->on){ 603 err = (*hci_stack.control->on)(hci_stack.config); 604 } 605 if (err){ 606 log_err( "POWER_ON failed\n"); 607 hci_emit_hci_open_failed(); 608 return err; 609 } 610 611 // open low-level device 612 err = hci_stack.hci_transport->open(hci_stack.config); 613 if (err){ 614 log_err( "HCI_INIT failed, turning Bluetooth off again\n"); 615 if (hci_stack.control && hci_stack.control->off){ 616 (*hci_stack.control->off)(hci_stack.config); 617 } 618 hci_emit_hci_open_failed(); 619 return err; 620 } 621 return 0; 622 } 623 624 static void hci_power_control_off(void){ 625 626 log_dbg("hci_power_control_off\n"); 627 628 // close low-level device 629 hci_stack.hci_transport->close(hci_stack.config); 630 631 log_dbg("hci_power_control_off - hci_transport closed\n"); 632 633 // power off 634 if (hci_stack.control && hci_stack.control->off){ 635 (*hci_stack.control->off)(hci_stack.config); 636 } 637 638 log_dbg("hci_power_control_off - control closed\n"); 639 640 hci_stack.state = HCI_STATE_OFF; 641 } 642 643 static void hci_power_control_sleep(void){ 644 645 log_dbg("hci_power_control_sleep\n"); 646 647 #if 0 648 // don't close serial port during sleep 649 650 // close low-level device 651 hci_stack.hci_transport->close(hci_stack.config); 652 #endif 653 654 // sleep mode 655 if (hci_stack.control && hci_stack.control->sleep){ 656 (*hci_stack.control->sleep)(hci_stack.config); 657 } 658 659 hci_stack.state = HCI_STATE_SLEEPING; 660 } 661 662 static int hci_power_control_wake(void){ 663 664 log_dbg("hci_power_control_wake\n"); 665 666 // wake on 667 if (hci_stack.control && hci_stack.control->wake){ 668 (*hci_stack.control->wake)(hci_stack.config); 669 } 670 671 #if 0 672 // open low-level device 673 int err = hci_stack.hci_transport->open(hci_stack.config); 674 if (err){ 675 log_err( "HCI_INIT failed, turning Bluetooth off again\n"); 676 if (hci_stack.control && hci_stack.control->off){ 677 (*hci_stack.control->off)(hci_stack.config); 678 } 679 hci_emit_hci_open_failed(); 680 return err; 681 } 682 #endif 683 684 return 0; 685 } 686 687 688 int hci_power_control(HCI_POWER_MODE power_mode){ 689 690 log_dbg("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state); 691 692 int err = 0; 693 switch (hci_stack.state){ 694 695 case HCI_STATE_OFF: 696 switch (power_mode){ 697 case HCI_POWER_ON: 698 err = hci_power_control_on(); 699 if (err) return err; 700 // set up state machine 701 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 702 hci_stack.state = HCI_STATE_INITIALIZING; 703 hci_stack.substate = 0; 704 break; 705 case HCI_POWER_OFF: 706 // do nothing 707 break; 708 case HCI_POWER_SLEEP: 709 // do nothing (with SLEEP == OFF) 710 break; 711 } 712 break; 713 714 case HCI_STATE_INITIALIZING: 715 switch (power_mode){ 716 case HCI_POWER_ON: 717 // do nothing 718 break; 719 case HCI_POWER_OFF: 720 // no connections yet, just turn it off 721 hci_power_control_off(); 722 break; 723 case HCI_POWER_SLEEP: 724 // no connections yet, just turn it off 725 hci_power_control_sleep(); 726 break; 727 } 728 break; 729 730 case HCI_STATE_WORKING: 731 switch (power_mode){ 732 case HCI_POWER_ON: 733 // do nothing 734 break; 735 case HCI_POWER_OFF: 736 // see hci_run 737 hci_stack.state = HCI_STATE_HALTING; 738 break; 739 case HCI_POWER_SLEEP: 740 // see hci_run 741 hci_stack.state = HCI_STATE_FALLING_ASLEEP; 742 hci_stack.substate = 0; 743 break; 744 } 745 break; 746 747 case HCI_STATE_HALTING: 748 switch (power_mode){ 749 case HCI_POWER_ON: 750 // set up state machine 751 hci_stack.state = HCI_STATE_INITIALIZING; 752 hci_stack.substate = 0; 753 break; 754 case HCI_POWER_OFF: 755 // do nothing 756 break; 757 case HCI_POWER_SLEEP: 758 // see hci_run 759 hci_stack.state = HCI_STATE_FALLING_ASLEEP; 760 hci_stack.substate = 0; 761 break; 762 } 763 break; 764 765 case HCI_STATE_FALLING_ASLEEP: 766 switch (power_mode){ 767 case HCI_POWER_ON: 768 // set up state machine 769 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 770 hci_stack.state = HCI_STATE_INITIALIZING; 771 hci_stack.substate = 0; 772 break; 773 case HCI_POWER_OFF: 774 // see hci_run 775 hci_stack.state = HCI_STATE_HALTING; 776 break; 777 case HCI_POWER_SLEEP: 778 // do nothing 779 break; 780 } 781 break; 782 783 case HCI_STATE_SLEEPING: 784 switch (power_mode){ 785 case HCI_POWER_ON: 786 err = hci_power_control_wake(); 787 if (err) return err; 788 // set up state machine 789 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 790 hci_stack.state = HCI_STATE_INITIALIZING; 791 hci_stack.substate = 0; 792 break; 793 case HCI_POWER_OFF: 794 hci_stack.state = HCI_STATE_HALTING; 795 break; 796 case HCI_POWER_SLEEP: 797 // do nothing 798 break; 799 } 800 break; 801 } 802 803 // create internal event 804 hci_emit_state(); 805 806 // trigger next/first action 807 hci_run(); 808 809 return 0; 810 } 811 812 void hci_discoverable_control(uint8_t enable){ 813 if (enable) enable = 1; // normalize argument 814 815 if (hci_stack.discoverable == enable){ 816 hci_emit_discoverable_enabled(hci_stack.discoverable); 817 return; 818 } 819 820 hci_send_cmd(&hci_write_scan_enable, 2 | enable); // 1 = inq scan, 2 = page scan 821 hci_stack.discoverable = enable; 822 } 823 824 void hci_run(){ 825 826 if (hci_stack.num_cmd_packets == 0) { 827 // cannot send command yet 828 return; 829 } 830 831 hci_connection_t * connection; 832 833 switch (hci_stack.state){ 834 case HCI_STATE_INITIALIZING: 835 if (hci_stack.substate % 2) { 836 // odd: waiting for command completion 837 return; 838 } 839 switch (hci_stack.substate >> 1){ 840 case 0: // RESET 841 hci_send_cmd(&hci_reset); 842 if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){ 843 // skip baud change 844 hci_stack.substate = 4; // >> 1 = 2 845 } 846 break; 847 case 1: // SEND BAUD CHANGE 848 hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_cmd_buffer); 849 hci_send_cmd_packet(hci_stack.hci_cmd_buffer, 3 + hci_stack.hci_cmd_buffer[2]); 850 break; 851 case 2: // LOCAL BAUD CHANGE 852 hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main); 853 hci_stack.substate += 2; 854 // break missing here for fall through 855 856 case 3: 857 // custom initialization 858 if (hci_stack.control && hci_stack.control->next_command){ 859 uint8_t * cmd = (*hci_stack.control->next_command)(hci_stack.config); 860 if (cmd) { 861 int size = 3 + cmd[2]; 862 hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, cmd, size); 863 hci_stack.substate = 4; // more init commands 864 break; 865 } 866 printf("hci_run: init script done\n\r"); 867 } 868 // otherwise continue 869 hci_send_cmd(&hci_read_bd_addr); 870 break; 871 case 4: 872 hci_send_cmd(&hci_read_buffer_size); 873 break; 874 case 5: 875 // ca. 15 sec 876 hci_send_cmd(&hci_write_page_timeout, 0x6000); 877 break; 878 case 6: 879 hci_send_cmd(&hci_write_scan_enable, 2 | hci_stack.discoverable); // page scan 880 break; 881 case 7: 882 #ifndef EMBEDDED 883 { 884 char hostname[30]; 885 gethostname(hostname, 30); 886 hostname[29] = '\0'; 887 hci_send_cmd(&hci_write_local_name, hostname); 888 break; 889 } 890 case 8: 891 #ifdef USE_BLUETOOL 892 hci_send_cmd(&hci_write_class_of_device, 0x007a020c); // Smartphone 893 break; 894 895 case 9: 896 #endif 897 #endif 898 // done. 899 hci_stack.state = HCI_STATE_WORKING; 900 hci_emit_state(); 901 break; 902 default: 903 break; 904 } 905 hci_stack.substate++; 906 break; 907 908 case HCI_STATE_HALTING: 909 910 log_dbg("HCI_STATE_HALTING\n"); 911 // close all open connections 912 connection = (hci_connection_t *) hci_stack.connections; 913 if (connection){ 914 log_dbg("HCI_STATE_HALTING, connection %lu, handle %u\n", (uintptr_t) connection, connection->con_handle); 915 // send disconnect 916 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 917 918 // send disconnected event right away - causes higher layer connections to get closed, too. 919 hci_shutdown_connection(connection); 920 return; 921 } 922 log_dbg("HCI_STATE_HALTING, calling off\n"); 923 924 // switch mode 925 hci_power_control_off(); 926 927 log_dbg("HCI_STATE_HALTING, emitting state\n"); 928 hci_emit_state(); 929 log_dbg("HCI_STATE_HALTING, done\n"); 930 break; 931 932 case HCI_STATE_FALLING_ASLEEP: 933 switch(hci_stack.substate) { 934 case 0: 935 log_dbg("HCI_STATE_FALLING_ASLEEP\n"); 936 // close all open connections 937 connection = (hci_connection_t *) hci_stack.connections; 938 if (connection){ 939 log_dbg("HCI_STATE_FALLING_ASLEEP, connection %lu, handle %u\n", (uintptr_t) connection, connection->con_handle); 940 // send disconnect 941 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 942 943 // send disconnected event right away - causes higher layer connections to get closed, too. 944 hci_shutdown_connection(connection); 945 return; 946 } 947 948 log_dbg("HCI_STATE_HALTING, disabling inq & page scans\n"); 949 950 // disable page and inquiry scan 951 hci_send_cmd(&hci_write_scan_enable, 0); // none 952 953 // continue in next sub state 954 hci_stack.substate++; 955 break; 956 case 1: 957 // wait for command complete "hci_write_scan_enable" in event_handler(); 958 break; 959 case 2: 960 log_dbg("HCI_STATE_HALTING, calling sleep\n"); 961 // switch mode 962 hci_power_control_sleep(); // changes hci_stack.state to SLEEP 963 hci_emit_state(); 964 default: 965 break; 966 } 967 break; 968 969 default: 970 break; 971 } 972 } 973 974 int hci_send_cmd_packet(uint8_t *packet, int size){ 975 bd_addr_t addr; 976 hci_connection_t * conn; 977 // house-keeping 978 979 // create_connection? 980 if (IS_COMMAND(packet, hci_create_connection)){ 981 bt_flip_addr(addr, &packet[3]); 982 log_dbg("Create_connection to "); print_bd_addr(addr); log_dbg("\n"); 983 conn = connection_for_address(addr); 984 if (conn) { 985 // if connection exists 986 if (conn->state == OPEN) { 987 // if OPEN, emit connection complete command 988 hci_emit_connection_complete(conn); 989 } 990 // otherwise, just ignore 991 return 0; // don't sent packet to controller 992 993 } else{ 994 conn = create_connection_for_addr(addr); 995 if (conn){ 996 // create connection struct and register, state = SENT_CREATE_CONNECTION 997 conn->state = SENT_CREATE_CONNECTION; 998 } 999 } 1000 } 1001 1002 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 1003 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 1004 } 1005 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 1006 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 1007 } 1008 if (IS_COMMAND(packet, hci_pin_code_request_reply)){ 1009 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY); 1010 } 1011 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){ 1012 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY); 1013 } 1014 1015 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 1016 if (hci_stack.remote_device_db){ 1017 bt_flip_addr(addr, &packet[3]); 1018 hci_stack.remote_device_db->delete_link_key(&addr); 1019 } 1020 } 1021 1022 hci_stack.num_cmd_packets--; 1023 return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 1024 } 1025 1026 /** 1027 * pre: numcmds >= 0 - it's allowed to send a command to the controller 1028 */ 1029 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 1030 va_list argptr; 1031 va_start(argptr, cmd); 1032 uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer; 1033 uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr); 1034 va_end(argptr); 1035 return hci_send_cmd_packet(hci_cmd_buffer, size); 1036 } 1037 1038 // Create various non-HCI events. 1039 // TODO: generalize, use table similar to hci_create_command 1040 1041 void hci_emit_state(){ 1042 uint8_t len = 3; 1043 uint8_t event[len]; 1044 event[0] = BTSTACK_EVENT_STATE; 1045 event[1] = len - 3; 1046 event[2] = hci_stack.state; 1047 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1048 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1049 } 1050 1051 void hci_emit_connection_complete(hci_connection_t *conn){ 1052 uint8_t len = 13; 1053 uint8_t event[len]; 1054 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 1055 event[1] = len - 3; 1056 event[2] = 0; // status = OK 1057 bt_store_16(event, 3, conn->con_handle); 1058 bt_flip_addr(&event[5], conn->address); 1059 event[11] = 1; // ACL connection 1060 event[12] = 0; // encryption disabled 1061 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1062 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1063 } 1064 1065 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 1066 uint8_t len = 6; 1067 uint8_t event[len]; 1068 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 1069 event[1] = len - 3; 1070 event[2] = 0; // status = OK 1071 bt_store_16(event, 3, handle); 1072 event[5] = reason; 1073 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1074 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1075 } 1076 1077 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 1078 uint8_t len = 4; 1079 uint8_t event[len]; 1080 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 1081 event[1] = len - 2; 1082 bt_store_16(event, 2, conn->con_handle); 1083 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1084 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1085 } 1086 1087 void hci_emit_nr_connections_changed(){ 1088 uint8_t len = 3; 1089 uint8_t event[len]; 1090 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 1091 event[1] = len - 2; 1092 event[2] = nr_hci_connections(); 1093 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1094 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1095 } 1096 1097 void hci_emit_hci_open_failed(){ 1098 uint8_t len = 2; 1099 uint8_t event[len]; 1100 event[0] = BTSTACK_EVENT_POWERON_FAILED; 1101 event[1] = len - 2; 1102 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1103 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1104 } 1105 1106 1107 void hci_emit_btstack_version() { 1108 uint8_t len = 6; 1109 uint8_t event[len]; 1110 event[0] = BTSTACK_EVENT_VERSION; 1111 event[1] = len - 2; 1112 event[len++] = BTSTACK_MAJOR; 1113 event[len++] = BTSTACK_MINOR; 1114 bt_store_16(event, len, BTSTACK_REVISION); 1115 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1116 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1117 } 1118 1119 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 1120 uint8_t len = 3; 1121 uint8_t event[len]; 1122 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 1123 event[1] = len - 2; 1124 event[2] = enabled; 1125 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1126 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1127 } 1128 1129 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){ 1130 uint16_t len = 2+1+6+248; 1131 uint8_t event[len]; 1132 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 1133 event[1] = len - 2; 1134 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 1135 bt_flip_addr(&event[3], *addr); 1136 memcpy(&event[9], name, 248); 1137 hci_dump_packet(HCI_EVENT_PACKET, 0, event, len); 1138 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1139 } 1140 1141 void hci_emit_discoverable_enabled(uint8_t enabled){ 1142 uint8_t len = 3; 1143 uint8_t event[len]; 1144 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 1145 event[1] = len - 2; 1146 event[2] = enabled; 1147 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 1148 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 1149 } 1150