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