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