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 HAVE_TICK 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 HAVE_TICK 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 247 int err = hci_stack.hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 248 249 return err; 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 const 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_PAYLOAD_SIZE < hci_stack.acl_data_packet_length){ 413 hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_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: used 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 memset(&device_name, 0, 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 // no pending cmds 637 hci_stack.decline_reason = 0; 638 hci_stack.new_scan_enable_value = 0xff; 639 640 // higher level handler 641 hci_stack.packet_handler = dummy_handler; 642 643 // store and open remote device db 644 hci_stack.remote_device_db = remote_device_db; 645 if (hci_stack.remote_device_db) { 646 hci_stack.remote_device_db->open(); 647 } 648 649 // max acl payload size defined in config.h 650 hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 651 652 // register packet handlers with transport 653 transport->register_packet_handler(&packet_handler); 654 } 655 656 void hci_close(){ 657 // close remote device db 658 if (hci_stack.remote_device_db) { 659 hci_stack.remote_device_db->close(); 660 } 661 } 662 663 // State-Module-Driver overview 664 // state module low-level 665 // HCI_STATE_OFF off close 666 // HCI_STATE_INITIALIZING, on open 667 // HCI_STATE_WORKING, on open 668 // HCI_STATE_HALTING, on open 669 // HCI_STATE_SLEEPING, off/sleep close 670 // HCI_STATE_FALLING_ASLEEP on open 671 672 static int hci_power_control_on(void){ 673 674 // power on 675 int err = 0; 676 if (hci_stack.control && hci_stack.control->on){ 677 err = (*hci_stack.control->on)(hci_stack.config); 678 } 679 if (err){ 680 log_error( "POWER_ON failed\n"); 681 hci_emit_hci_open_failed(); 682 return err; 683 } 684 685 // open low-level device 686 err = hci_stack.hci_transport->open(hci_stack.config); 687 if (err){ 688 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 689 if (hci_stack.control && hci_stack.control->off){ 690 (*hci_stack.control->off)(hci_stack.config); 691 } 692 hci_emit_hci_open_failed(); 693 return err; 694 } 695 return 0; 696 } 697 698 static void hci_power_control_off(void){ 699 700 log_info("hci_power_control_off\n"); 701 702 // close low-level device 703 hci_stack.hci_transport->close(hci_stack.config); 704 705 log_info("hci_power_control_off - hci_transport closed\n"); 706 707 // power off 708 if (hci_stack.control && hci_stack.control->off){ 709 (*hci_stack.control->off)(hci_stack.config); 710 } 711 712 log_info("hci_power_control_off - control closed\n"); 713 714 hci_stack.state = HCI_STATE_OFF; 715 } 716 717 static void hci_power_control_sleep(void){ 718 719 log_info("hci_power_control_sleep\n"); 720 721 #if 0 722 // don't close serial port during sleep 723 724 // close low-level device 725 hci_stack.hci_transport->close(hci_stack.config); 726 #endif 727 728 // sleep mode 729 if (hci_stack.control && hci_stack.control->sleep){ 730 (*hci_stack.control->sleep)(hci_stack.config); 731 } 732 733 hci_stack.state = HCI_STATE_SLEEPING; 734 } 735 736 static int hci_power_control_wake(void){ 737 738 log_info("hci_power_control_wake\n"); 739 740 // wake on 741 if (hci_stack.control && hci_stack.control->wake){ 742 (*hci_stack.control->wake)(hci_stack.config); 743 } 744 745 #if 0 746 // open low-level device 747 int err = hci_stack.hci_transport->open(hci_stack.config); 748 if (err){ 749 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 750 if (hci_stack.control && hci_stack.control->off){ 751 (*hci_stack.control->off)(hci_stack.config); 752 } 753 hci_emit_hci_open_failed(); 754 return err; 755 } 756 #endif 757 758 return 0; 759 } 760 761 762 int hci_power_control(HCI_POWER_MODE power_mode){ 763 764 log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state); 765 766 int err = 0; 767 switch (hci_stack.state){ 768 769 case HCI_STATE_OFF: 770 switch (power_mode){ 771 case HCI_POWER_ON: 772 err = hci_power_control_on(); 773 if (err) return err; 774 // set up state machine 775 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 776 hci_stack.state = HCI_STATE_INITIALIZING; 777 hci_stack.substate = 0; 778 break; 779 case HCI_POWER_OFF: 780 // do nothing 781 break; 782 case HCI_POWER_SLEEP: 783 // do nothing (with SLEEP == OFF) 784 break; 785 } 786 break; 787 788 case HCI_STATE_INITIALIZING: 789 switch (power_mode){ 790 case HCI_POWER_ON: 791 // do nothing 792 break; 793 case HCI_POWER_OFF: 794 // no connections yet, just turn it off 795 hci_power_control_off(); 796 break; 797 case HCI_POWER_SLEEP: 798 // no connections yet, just turn it off 799 hci_power_control_sleep(); 800 break; 801 } 802 break; 803 804 case HCI_STATE_WORKING: 805 switch (power_mode){ 806 case HCI_POWER_ON: 807 // do nothing 808 break; 809 case HCI_POWER_OFF: 810 // see hci_run 811 hci_stack.state = HCI_STATE_HALTING; 812 break; 813 case HCI_POWER_SLEEP: 814 // see hci_run 815 hci_stack.state = HCI_STATE_FALLING_ASLEEP; 816 hci_stack.substate = 0; 817 break; 818 } 819 break; 820 821 case HCI_STATE_HALTING: 822 switch (power_mode){ 823 case HCI_POWER_ON: 824 // set up state machine 825 hci_stack.state = HCI_STATE_INITIALIZING; 826 hci_stack.substate = 0; 827 break; 828 case HCI_POWER_OFF: 829 // do nothing 830 break; 831 case HCI_POWER_SLEEP: 832 // see hci_run 833 hci_stack.state = HCI_STATE_FALLING_ASLEEP; 834 hci_stack.substate = 0; 835 break; 836 } 837 break; 838 839 case HCI_STATE_FALLING_ASLEEP: 840 switch (power_mode){ 841 case HCI_POWER_ON: 842 // set up state machine 843 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 844 hci_stack.state = HCI_STATE_INITIALIZING; 845 hci_stack.substate = 0; 846 break; 847 case HCI_POWER_OFF: 848 // see hci_run 849 hci_stack.state = HCI_STATE_HALTING; 850 break; 851 case HCI_POWER_SLEEP: 852 // do nothing 853 break; 854 } 855 break; 856 857 case HCI_STATE_SLEEPING: 858 switch (power_mode){ 859 case HCI_POWER_ON: 860 err = hci_power_control_wake(); 861 if (err) return err; 862 // set up state machine 863 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 864 hci_stack.state = HCI_STATE_INITIALIZING; 865 hci_stack.substate = 0; 866 break; 867 case HCI_POWER_OFF: 868 hci_stack.state = HCI_STATE_HALTING; 869 break; 870 case HCI_POWER_SLEEP: 871 // do nothing 872 break; 873 } 874 break; 875 } 876 877 // create internal event 878 hci_emit_state(); 879 880 // trigger next/first action 881 hci_run(); 882 883 return 0; 884 } 885 886 void hci_discoverable_control(uint8_t enable){ 887 if (enable) enable = 1; // normalize argument 888 889 if (hci_stack.discoverable == enable){ 890 hci_emit_discoverable_enabled(hci_stack.discoverable); 891 return; 892 } 893 894 // store request to send command but accept in higher layer view 895 hci_stack.new_scan_enable_value = 2 | enable; // 1 = inq scan, 2 = page scan 896 hci_stack.discoverable = enable; 897 898 hci_run(); 899 } 900 901 void hci_run(){ 902 903 hci_connection_t * connection; 904 linked_item_t * it; 905 906 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 907 908 // global/non-connection oriented commands 909 910 // decline incoming connections 911 if (hci_stack.decline_reason){ 912 uint8_t reason = hci_stack.decline_reason; 913 hci_stack.decline_reason = 0; 914 hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason); 915 } 916 917 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 918 919 // send scan enable 920 if (hci_stack.new_scan_enable_value != 0xff){ 921 hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value); 922 hci_stack.new_scan_enable_value = 0xff; 923 } 924 925 // send pending HCI commands 926 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 927 928 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 929 930 connection = (hci_connection_t *) it; 931 932 if (connection->state == RECEIVED_CONNECTION_REQUEST){ 933 log_info("sending hci_accept_connection_request\n"); 934 hci_send_cmd(&hci_accept_connection_request, connection->address, 1); 935 connection->state = ACCEPTED_CONNECTION_REQUEST; 936 } 937 938 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 939 940 if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){ 941 link_key_t link_key; 942 log_info("responding to link key request\n"); 943 if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){ 944 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key); 945 } else { 946 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 947 } 948 connection->authentication_flags &= ~HANDLE_LINK_KEY_REQUEST; 949 } 950 } 951 952 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 953 954 switch (hci_stack.state){ 955 case HCI_STATE_INITIALIZING: 956 // log_info("hci_init: substate %u\n", hci_stack.substate); 957 if (hci_stack.substate % 2) { 958 // odd: waiting for command completion 959 return; 960 } 961 switch (hci_stack.substate >> 1){ 962 case 0: // RESET 963 hci_send_cmd(&hci_reset); 964 if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){ 965 // skip baud change 966 hci_stack.substate = 4; // >> 1 = 2 967 } 968 break; 969 case 1: // SEND BAUD CHANGE 970 hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer); 971 hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]); 972 break; 973 case 2: // LOCAL BAUD CHANGE 974 hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main); 975 hci_stack.substate += 2; 976 // break missing here for fall through 977 978 case 3: 979 // custom initialization 980 if (hci_stack.control && hci_stack.control->next_cmd){ 981 int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer); 982 if (valid_cmd){ 983 int size = 3 + hci_stack.hci_packet_buffer[2]; 984 hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size); 985 hci_stack.substate = 4; // more init commands 986 break; 987 } 988 log_info("hci_run: init script done\n\r"); 989 } 990 // otherwise continue 991 hci_send_cmd(&hci_read_bd_addr); 992 break; 993 case 4: 994 hci_send_cmd(&hci_read_buffer_size); 995 break; 996 case 5: 997 // ca. 15 sec 998 hci_send_cmd(&hci_write_page_timeout, 0x6000); 999 break; 1000 case 6: 1001 hci_send_cmd(&hci_write_scan_enable, 2 | hci_stack.discoverable); // page scan 1002 break; 1003 case 7: 1004 #ifndef EMBEDDED 1005 { 1006 char hostname[30]; 1007 gethostname(hostname, 30); 1008 hostname[29] = '\0'; 1009 hci_send_cmd(&hci_write_local_name, hostname); 1010 break; 1011 } 1012 case 8: 1013 #ifdef USE_BLUETOOL 1014 hci_send_cmd(&hci_write_class_of_device, 0x007a020c); // Smartphone 1015 break; 1016 1017 case 9: 1018 #endif 1019 #endif 1020 // done. 1021 hci_stack.state = HCI_STATE_WORKING; 1022 hci_emit_state(); 1023 break; 1024 default: 1025 break; 1026 } 1027 hci_stack.substate++; 1028 break; 1029 1030 case HCI_STATE_HALTING: 1031 1032 log_info("HCI_STATE_HALTING\n"); 1033 // close all open connections 1034 connection = (hci_connection_t *) hci_stack.connections; 1035 if (connection){ 1036 1037 // send disconnect 1038 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1039 1040 log_info("HCI_STATE_HALTING, connection %lu, handle %u\n", (uintptr_t) connection, (uint16_t)connection->con_handle); 1041 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1042 1043 // send disconnected event right away - causes higher layer connections to get closed, too. 1044 hci_shutdown_connection(connection); 1045 return; 1046 } 1047 log_info("HCI_STATE_HALTING, calling off\n"); 1048 1049 // switch mode 1050 hci_power_control_off(); 1051 1052 log_info("HCI_STATE_HALTING, emitting state\n"); 1053 hci_emit_state(); 1054 log_info("HCI_STATE_HALTING, done\n"); 1055 break; 1056 1057 case HCI_STATE_FALLING_ASLEEP: 1058 switch(hci_stack.substate) { 1059 case 0: 1060 log_info("HCI_STATE_FALLING_ASLEEP\n"); 1061 // close all open connections 1062 connection = (hci_connection_t *) hci_stack.connections; 1063 if (connection){ 1064 1065 // send disconnect 1066 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1067 1068 log_info("HCI_STATE_FALLING_ASLEEP, connection %lu, handle %u\n", (uintptr_t) connection, (uint16_t)connection->con_handle); 1069 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1070 1071 // send disconnected event right away - causes higher layer connections to get closed, too. 1072 hci_shutdown_connection(connection); 1073 return; 1074 } 1075 1076 // disable page and inquiry scan 1077 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1078 1079 log_info("HCI_STATE_HALTING, disabling inq & page scans\n"); 1080 hci_send_cmd(&hci_write_scan_enable, 0); // none 1081 1082 // continue in next sub state 1083 hci_stack.substate++; 1084 break; 1085 case 1: 1086 // wait for command complete "hci_write_scan_enable" in event_handler(); 1087 break; 1088 case 2: 1089 log_info("HCI_STATE_HALTING, calling sleep\n"); 1090 // switch mode 1091 hci_power_control_sleep(); // changes hci_stack.state to SLEEP 1092 hci_emit_state(); 1093 default: 1094 break; 1095 } 1096 break; 1097 1098 default: 1099 break; 1100 } 1101 } 1102 1103 int hci_send_cmd_packet(uint8_t *packet, int size){ 1104 bd_addr_t addr; 1105 hci_connection_t * conn; 1106 // house-keeping 1107 1108 // create_connection? 1109 if (IS_COMMAND(packet, hci_create_connection)){ 1110 bt_flip_addr(addr, &packet[3]); 1111 log_info("Create_connection to %s\n", bd_addr_to_str(addr)); 1112 conn = connection_for_address(addr); 1113 if (conn) { 1114 // if connection exists 1115 if (conn->state == OPEN) { 1116 // and OPEN, emit connection complete command 1117 hci_emit_connection_complete(conn, 0); 1118 } 1119 // otherwise, just ignore as it is already in the open process 1120 return 0; // don't sent packet to controller 1121 1122 } 1123 // create connection struct and register, state = SENT_CREATE_CONNECTION 1124 conn = create_connection_for_addr(addr); 1125 if (!conn){ 1126 // notify client that alloc failed 1127 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 1128 return 0; // don't sent packet to controller 1129 } 1130 conn->state = SENT_CREATE_CONNECTION; 1131 } 1132 1133 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 1134 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 1135 } 1136 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 1137 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 1138 } 1139 if (IS_COMMAND(packet, hci_pin_code_request_reply)){ 1140 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY); 1141 } 1142 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){ 1143 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY); 1144 } 1145 1146 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 1147 if (hci_stack.remote_device_db){ 1148 bt_flip_addr(addr, &packet[3]); 1149 hci_stack.remote_device_db->delete_link_key(&addr); 1150 } 1151 } 1152 1153 hci_stack.num_cmd_packets--; 1154 return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 1155 } 1156 1157 /** 1158 * pre: numcmds >= 0 - it's allowed to send a command to the controller 1159 */ 1160 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 1161 va_list argptr; 1162 va_start(argptr, cmd); 1163 uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr); 1164 va_end(argptr); 1165 return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size); 1166 } 1167 1168 // Create various non-HCI events. 1169 // TODO: generalize, use table similar to hci_create_command 1170 1171 void hci_emit_state(){ 1172 uint8_t event[3]; 1173 event[0] = BTSTACK_EVENT_STATE; 1174 event[1] = sizeof(event) - 2; 1175 event[2] = hci_stack.state; 1176 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1177 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1178 } 1179 1180 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){ 1181 uint8_t event[13]; 1182 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 1183 event[1] = sizeof(event) - 2; 1184 event[2] = status; 1185 bt_store_16(event, 3, conn->con_handle); 1186 bt_flip_addr(&event[5], conn->address); 1187 event[11] = 1; // ACL connection 1188 event[12] = 0; // encryption disabled 1189 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1190 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1191 } 1192 1193 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 1194 uint8_t event[6]; 1195 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 1196 event[1] = sizeof(event) - 2; 1197 event[2] = 0; // status = OK 1198 bt_store_16(event, 3, handle); 1199 event[5] = reason; 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 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 1205 uint8_t event[4]; 1206 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 1207 event[1] = sizeof(event) - 2; 1208 bt_store_16(event, 2, conn->con_handle); 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 void hci_emit_nr_connections_changed(){ 1214 uint8_t event[3]; 1215 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 1216 event[1] = sizeof(event) - 2; 1217 event[2] = nr_hci_connections(); 1218 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1219 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1220 } 1221 1222 void hci_emit_hci_open_failed(){ 1223 uint8_t event[2]; 1224 event[0] = BTSTACK_EVENT_POWERON_FAILED; 1225 event[1] = sizeof(event) - 2; 1226 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1227 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1228 } 1229 1230 1231 void hci_emit_btstack_version() { 1232 uint8_t event[6]; 1233 event[0] = BTSTACK_EVENT_VERSION; 1234 event[1] = sizeof(event) - 2; 1235 event[2] = BTSTACK_MAJOR; 1236 event[3] = BTSTACK_MINOR; 1237 bt_store_16(event, 4, BTSTACK_REVISION); 1238 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1239 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1240 } 1241 1242 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 1243 uint8_t event[3]; 1244 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 1245 event[1] = sizeof(event) - 2; 1246 event[2] = enabled; 1247 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1248 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1249 } 1250 1251 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){ 1252 uint8_t event[2+1+6+248]; 1253 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 1254 event[1] = sizeof(event) - 2; 1255 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 1256 bt_flip_addr(&event[3], *addr); 1257 memcpy(&event[9], name, 248); 1258 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1259 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1260 } 1261 1262 void hci_emit_discoverable_enabled(uint8_t enabled){ 1263 uint8_t event[3]; 1264 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 1265 event[1] = sizeof(event) - 2; 1266 event[2] = enabled; 1267 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1268 hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1269 } 1270