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