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