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 <unistd.h> 42 #include <stdarg.h> 43 #include <string.h> 44 #include <stdio.h> 45 46 #include "debug.h" 47 #include "hci_dump.h" 48 49 #include "../include/btstack/hci_cmds.h" 50 #include "../include/btstack/version.h" 51 52 // temp 53 #include "l2cap.h" 54 55 #define HCI_CONNECTION_TIMEOUT_MS 10000 56 57 // the STACK is here 58 static hci_stack_t hci_stack; 59 60 /** 61 * get connection for a given handle 62 * 63 * @return connection OR NULL, if not found 64 */ 65 hci_connection_t * connection_for_handle(hci_con_handle_t con_handle){ 66 linked_item_t *it; 67 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 68 if ( ((hci_connection_t *) it)->con_handle == con_handle){ 69 return (hci_connection_t *) it; 70 } 71 } 72 return NULL; 73 } 74 75 static void hci_connection_timeout_handler(timer_source_t *timer){ 76 hci_connection_t * connection = linked_item_get_user(&timer->item); 77 struct timeval tv; 78 gettimeofday(&tv, NULL); 79 if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) { 80 // connections might be timed out 81 hci_emit_l2cap_check_timeout(connection); 82 run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS); 83 } else { 84 // next timeout check at 85 timer->timeout.tv_sec = connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000; 86 } 87 run_loop_add_timer(timer); 88 } 89 90 static void hci_connection_timestamp(hci_connection_t *connection){ 91 gettimeofday(&connection->timestamp, NULL); 92 } 93 94 /** 95 * create connection for given address 96 * 97 * @return connection OR NULL, if not found 98 */ 99 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){ 100 hci_connection_t * conn = malloc( sizeof(hci_connection_t) ); 101 if (!conn) return NULL; 102 BD_ADDR_COPY(conn->address, addr); 103 conn->con_handle = 0xffff; 104 conn->flags = 0; 105 linked_item_set_user(&conn->timeout.item, conn); 106 conn->timeout.process = hci_connection_timeout_handler; 107 hci_connection_timestamp(conn); 108 conn->acl_recombination_length = 0; 109 conn->acl_recombination_pos = 0; 110 linked_list_add(&hci_stack.connections, (linked_item_t *) conn); 111 return conn; 112 } 113 114 /** 115 * get connection for given address 116 * 117 * @return connection OR NULL, if not found 118 */ 119 static hci_connection_t * connection_for_address(bd_addr_t address){ 120 linked_item_t *it; 121 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){ 122 if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){ 123 return (hci_connection_t *) it; 124 } 125 } 126 return NULL; 127 } 128 129 /** 130 * count connections 131 */ 132 static int nr_hci_connections(){ 133 int count = 0; 134 linked_item_t *it; 135 for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++); 136 return count; 137 } 138 139 /** 140 * Dummy handler called by HCI 141 */ 142 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 143 } 144 145 /** 146 * Dummy control handler 147 */ 148 static int null_control_function(void *config){ 149 return 0; 150 } 151 static const char * null_control_name(void *config){ 152 return "Hardware unknown"; 153 } 154 static bt_control_t null_control = { 155 null_control_function, 156 null_control_function, 157 null_control_function, 158 null_control_name 159 }; 160 161 162 int hci_send_acl_packet(uint8_t *packet, int size){ 163 164 // update idle timestamp 165 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 166 hci_connection_t *connection = connection_for_handle( con_handle); 167 if (connection) hci_connection_timestamp(connection); 168 169 // send packet 170 return hci_stack.hci_transport->send_acl_packet(packet, size); 171 } 172 173 static void acl_handler(uint8_t *packet, int size){ 174 175 // get info 176 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 177 hci_connection_t *conn = connection_for_handle(con_handle); 178 uint8_t acl_flags = READ_ACL_FLAGS(packet); 179 uint16_t acl_length = READ_ACL_LENGTH(packet); 180 181 // ignore non-registered handle 182 if (!conn){ 183 log_err( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle); 184 return; 185 } 186 187 // update idle timestamp 188 hci_connection_timestamp(conn); 189 190 // handle different packet types 191 switch (acl_flags & 0x03) { 192 193 case 0x01: // continuation fragment 194 195 // sanity check 196 if (conn->acl_recombination_pos == 0) { 197 log_err( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle); 198 return; 199 } 200 201 // append fragment payload (header already stored) 202 memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length ); 203 conn->acl_recombination_pos += acl_length; 204 205 // log_err( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", 206 // acl_length, connection->acl_recombination_pos, connection->acl_recombination_length); 207 208 // forward complete L2CAP packet if complete. 209 if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header 210 211 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos); 212 // reset recombination buffer 213 conn->acl_recombination_length = 0; 214 conn->acl_recombination_pos = 0; 215 } 216 break; 217 218 case 0x02: { // first fragment 219 220 // sanity check 221 if (conn->acl_recombination_pos) { 222 log_err( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle); 223 return; 224 } 225 226 // peek into L2CAP packet! 227 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 228 229 // compare fragment size to L2CAP packet size 230 if (acl_length >= l2cap_length + 4){ 231 232 // forward fragment as L2CAP packet 233 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4); 234 235 } else { 236 // store first fragment and tweak acl length for complete package 237 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4); 238 conn->acl_recombination_pos = acl_length + 4; 239 conn->acl_recombination_length = l2cap_length; 240 bt_store_16(conn->acl_recombination_buffer, 2, acl_length +4); 241 // log_err( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length); 242 } 243 break; 244 245 } 246 default: 247 log_err( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03); 248 return; 249 } 250 251 // execute main loop 252 hci_run(); 253 } 254 255 static void event_handler(uint8_t *packet, int size){ 256 bd_addr_t addr; 257 hci_con_handle_t handle; 258 hci_connection_t * conn; 259 260 switch (packet[0]) { 261 262 case HCI_EVENT_COMMAND_COMPLETE: 263 case HCI_EVENT_COMMAND_STATUS: 264 // Get Num_HCI_Command_Packets 265 hci_stack.num_cmd_packets = packet[2]; 266 break; 267 268 case HCI_EVENT_CONNECTION_REQUEST: 269 bt_flip_addr(addr, &packet[2]); 270 // TODO: eval COD 8-10 271 uint8_t link_type = packet[11]; 272 log_dbg("Connection_incoming: "); print_bd_addr(addr); log_dbg(", type %u\n", link_type); 273 if (link_type == 1) { // ACL 274 conn = connection_for_address(addr); 275 if (!conn) { 276 conn = create_connection_for_addr(addr); 277 } 278 // TODO: check for malloc failure 279 conn->state = ACCEPTED_CONNECTION_REQUEST; 280 hci_send_cmd(&hci_accept_connection_request, addr, 1); 281 } else { 282 // TODO: decline request 283 } 284 break; 285 286 case HCI_EVENT_CONNECTION_COMPLETE: 287 // Connection management 288 bt_flip_addr(addr, &packet[5]); 289 log_dbg("Connection_complete (status=%u)", packet[2]); print_bd_addr(addr); log_dbg("\n"); 290 conn = connection_for_address(addr); 291 if (conn) { 292 if (!packet[2]){ 293 conn->state = OPEN; 294 conn->con_handle = READ_BT_16(packet, 3); 295 conn->flags = 0; 296 297 gettimeofday(&conn->timestamp, NULL); 298 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 299 run_loop_add_timer(&conn->timeout); 300 301 log_dbg("New connection: handle %u, ", conn->con_handle); 302 print_bd_addr( conn->address ); 303 log_dbg("\n"); 304 305 hci_emit_nr_connections_changed(); 306 } else { 307 // connection failed, remove entry 308 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); 309 free( conn ); 310 } 311 } 312 break; 313 314 case HCI_EVENT_DISCONNECTION_COMPLETE: 315 if (!packet[2]){ 316 handle = READ_BT_16(packet, 3); 317 hci_connection_t * conn = connection_for_handle(handle); 318 if (conn) { 319 log_dbg("Connection closed: handle %u, ", conn->con_handle); 320 print_bd_addr( conn->address ); 321 log_dbg("\n"); 322 run_loop_remove_timer(&conn->timeout); 323 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); 324 free( conn ); 325 hci_emit_nr_connections_changed(); 326 } 327 } 328 break; 329 330 default: 331 break; 332 } 333 334 // handle BT initialization 335 if (hci_stack.state == HCI_STATE_INITIALIZING){ 336 // handle H4 synchronization loss on restart 337 // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){ 338 // hci_stack.substate = 0; 339 // } 340 // handle normal init sequence 341 if (hci_stack.substate % 2){ 342 // odd: waiting for event 343 if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){ 344 hci_stack.substate++; 345 } 346 } 347 } 348 349 hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size); 350 351 // execute main loop 352 hci_run(); 353 } 354 355 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 356 switch (packet_type) { 357 case HCI_EVENT_PACKET: 358 event_handler(packet, size); 359 break; 360 case HCI_ACL_DATA_PACKET: 361 acl_handler(packet, size); 362 break; 363 default: 364 break; 365 } 366 } 367 368 /** Register HCI packet handlers */ 369 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 370 hci_stack.packet_handler = handler; 371 } 372 373 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control){ 374 375 // reference to use transport layer implementation 376 hci_stack.hci_transport = transport; 377 378 // references to used control implementation 379 if (control) { 380 hci_stack.control = control; 381 } else { 382 hci_stack.control = &null_control; 383 } 384 385 // reference to used config 386 hci_stack.config = config; 387 388 // no connections yet 389 hci_stack.connections = NULL; 390 391 // empty cmd buffer 392 hci_stack.hci_cmd_buffer = malloc(3+255); 393 394 // higher level handler 395 hci_stack.packet_handler = dummy_handler; 396 397 // register packet handlers with transport 398 transport->register_packet_handler(&packet_handler); 399 } 400 401 int hci_power_control(HCI_POWER_MODE power_mode){ 402 if (power_mode == HCI_POWER_ON && hci_stack.state == HCI_STATE_OFF) { 403 404 // power on 405 int err = hci_stack.control->on(hci_stack.config); 406 if (err){ 407 log_err( "POWER_ON failed\n"); 408 hci_emit_hci_open_failed(); 409 return err; 410 } 411 412 // open low-level device 413 err = hci_stack.hci_transport->open(hci_stack.config); 414 if (err){ 415 log_err( "HCI_INIT failed, turning Bluetooth off again\n"); 416 hci_stack.control->off(hci_stack.config); 417 hci_emit_hci_open_failed(); 418 return err; 419 } 420 421 // set up state machine 422 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 423 hci_stack.state = HCI_STATE_INITIALIZING; 424 hci_stack.substate = 0; 425 426 } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){ 427 428 // close low-level device 429 hci_stack.hci_transport->close(hci_stack.config); 430 431 // power off 432 hci_stack.control->off(hci_stack.config); 433 434 // we're off now 435 hci_stack.state = HCI_STATE_OFF; 436 } 437 438 // create internal event 439 hci_emit_state(); 440 441 // trigger next/first action 442 hci_run(); 443 444 return 0; 445 } 446 447 void hci_run(){ 448 switch (hci_stack.state){ 449 case HCI_STATE_INITIALIZING: 450 if (hci_stack.substate % 2) { 451 // odd: waiting for command completion 452 return; 453 } 454 if (hci_stack.num_cmd_packets == 0) { 455 // cannot send command yet 456 return; 457 } 458 switch (hci_stack.substate/2){ 459 case 0: 460 hci_send_cmd(&hci_reset); 461 break; 462 case 1: 463 hci_send_cmd(&hci_read_bd_addr); 464 break; 465 case 2: 466 // ca. 15 sec 467 hci_send_cmd(&hci_write_page_timeout, 0x6000); 468 break; 469 case 3: 470 hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan 471 break; 472 case 4: 473 // done. 474 hci_stack.state = HCI_STATE_WORKING; 475 hci_emit_state(); 476 break; 477 default: 478 break; 479 } 480 hci_stack.substate++; 481 break; 482 default: 483 break; 484 } 485 } 486 487 int hci_send_cmd_packet(uint8_t *packet, int size){ 488 bd_addr_t addr; 489 hci_connection_t * conn; 490 // house-keeping 491 492 // create_connection? 493 if (IS_COMMAND(packet, hci_create_connection)){ 494 bt_flip_addr(addr, &packet[3]); 495 log_dbg("Create_connection to "); print_bd_addr(addr); log_dbg("\n"); 496 conn = connection_for_address(addr); 497 if (conn) { 498 // if connection exists 499 if (conn->state == OPEN) { 500 // if OPEN, emit connection complete command 501 hci_emit_connection_complete(conn); 502 } 503 // otherwise, just ignore 504 return 0; // don't sent packet to controller 505 506 } else{ 507 conn = create_connection_for_addr(addr); 508 if (conn){ 509 // create connection struct and register, state = SENT_CREATE_CONNECTION 510 conn->state = SENT_CREATE_CONNECTION; 511 } 512 } 513 } 514 515 // accept connection 516 517 // reject connection 518 519 // close_connection? 520 // set state = SENT_DISCONNECT 521 522 hci_stack.num_cmd_packets--; 523 return hci_stack.hci_transport->send_cmd_packet(packet, size); 524 } 525 526 /** 527 * pre: numcmds >= 0 - it's allowed to send a command to the controller 528 */ 529 int hci_send_cmd(hci_cmd_t *cmd, ...){ 530 va_list argptr; 531 va_start(argptr, cmd); 532 uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer; 533 uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr); 534 va_end(argptr); 535 return hci_send_cmd_packet(hci_cmd_buffer, size); 536 } 537 538 // Create various non-HCI events. 539 // TODO: generalize, use table similar to hci_create_command 540 541 void hci_emit_state(){ 542 uint8_t len = 3; 543 uint8_t event[len]; 544 event[0] = BTSTACK_EVENT_STATE; 545 event[1] = len - 3; 546 event[2] = hci_stack.state; 547 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 548 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 549 } 550 551 void hci_emit_connection_complete(hci_connection_t *conn){ 552 uint8_t len = 13; 553 uint8_t event[len]; 554 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 555 event[1] = len - 3; 556 event[2] = 0; // status = OK 557 bt_store_16(event, 3, conn->con_handle); 558 bt_flip_addr(&event[5], conn->address); 559 event[11] = 1; // ACL connection 560 event[12] = 0; // encryption disabled 561 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 562 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 563 } 564 565 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 566 uint8_t len = 4; 567 uint8_t event[len]; 568 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 569 event[1] = len - 2; 570 bt_store_16(event, 2, conn->con_handle); 571 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 572 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 573 } 574 575 void hci_emit_nr_connections_changed(){ 576 uint8_t len = 3; 577 uint8_t event[len]; 578 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 579 event[1] = len - 2; 580 event[2] = nr_hci_connections(); 581 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 582 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 583 } 584 585 void hci_emit_hci_open_failed(){ 586 uint8_t len = 2; 587 uint8_t event[len]; 588 event[0] = BTSTACK_EVENT_POWERON_FAILED; 589 event[1] = len - 2; 590 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 591 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 592 } 593 594 595 void hci_emit_btstack_version() { 596 uint8_t len = 6; 597 uint8_t event[len]; 598 event[0] = BTSTACK_EVENT_VERSION; 599 event[1] = len - 2; 600 event[len++] = BTSTACK_MAJOR; 601 event[len++] = BTSTACK_MINOR; 602 bt_store_16(event, len, BTSTACK_REVISION); 603 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 604 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 605 } 606 607 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 608 uint8_t len = 3; 609 uint8_t event[len]; 610 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 611 event[1] = len - 2; 612 event[2] = enabled; 613 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 614 hci_stack.packet_handler(HCI_EVENT_PACKET, event, len); 615 } 616