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, 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.acl_packet_handler(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.acl_packet_handler(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.event_packet_handler(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_event_packet_handler(void (*handler)(uint8_t *packet, uint16_t size)){ 370 hci_stack.event_packet_handler = handler; 371 } 372 void hci_register_acl_packet_handler (void (*handler)(uint8_t *packet, uint16_t size)){ 373 hci_stack.acl_packet_handler = handler; 374 } 375 376 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control){ 377 378 // reference to use transport layer implementation 379 hci_stack.hci_transport = transport; 380 381 // references to used control implementation 382 if (control) { 383 hci_stack.control = control; 384 } else { 385 hci_stack.control = &null_control; 386 } 387 388 // reference to used config 389 hci_stack.config = config; 390 391 // no connections yet 392 hci_stack.connections = NULL; 393 394 // empty cmd buffer 395 hci_stack.hci_cmd_buffer = malloc(3+255); 396 397 // higher level handler 398 hci_stack.event_packet_handler = dummy_handler; 399 hci_stack.acl_packet_handler = dummy_handler; 400 401 // register packet handlers with transport 402 transport->register_packet_handler(&packet_handler); 403 } 404 405 int hci_power_control(HCI_POWER_MODE power_mode){ 406 if (power_mode == HCI_POWER_ON && hci_stack.state == HCI_STATE_OFF) { 407 408 // power on 409 int err = hci_stack.control->on(hci_stack.config); 410 if (err){ 411 log_err( "POWER_ON failed\n"); 412 hci_emit_hci_open_failed(); 413 return err; 414 } 415 416 // open low-level device 417 err = hci_stack.hci_transport->open(hci_stack.config); 418 if (err){ 419 log_err( "HCI_INIT failed, turning Bluetooth off again\n"); 420 hci_stack.control->off(hci_stack.config); 421 hci_emit_hci_open_failed(); 422 return err; 423 } 424 425 // set up state machine 426 hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent 427 hci_stack.state = HCI_STATE_INITIALIZING; 428 hci_stack.substate = 0; 429 430 } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){ 431 432 // close low-level device 433 hci_stack.hci_transport->close(hci_stack.config); 434 435 // power off 436 hci_stack.control->off(hci_stack.config); 437 438 // we're off now 439 hci_stack.state = HCI_STATE_OFF; 440 } 441 442 // create internal event 443 hci_emit_state(); 444 445 // trigger next/first action 446 hci_run(); 447 448 return 0; 449 } 450 451 void hci_run(){ 452 switch (hci_stack.state){ 453 case HCI_STATE_INITIALIZING: 454 if (hci_stack.substate % 2) { 455 // odd: waiting for command completion 456 return; 457 } 458 if (hci_stack.num_cmd_packets == 0) { 459 // cannot send command yet 460 return; 461 } 462 switch (hci_stack.substate/2){ 463 case 0: 464 hci_send_cmd(&hci_reset); 465 break; 466 case 1: 467 hci_send_cmd(&hci_read_bd_addr); 468 break; 469 case 2: 470 // ca. 15 sec 471 hci_send_cmd(&hci_write_page_timeout, 0x6000); 472 break; 473 case 3: 474 hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan 475 break; 476 case 4: 477 // done. 478 hci_stack.state = HCI_STATE_WORKING; 479 hci_emit_state(); 480 break; 481 default: 482 break; 483 } 484 hci_stack.substate++; 485 break; 486 default: 487 break; 488 } 489 } 490 491 int hci_send_cmd_packet(uint8_t *packet, int size){ 492 bd_addr_t addr; 493 hci_connection_t * conn; 494 // house-keeping 495 496 // create_connection? 497 if (IS_COMMAND(packet, hci_create_connection)){ 498 bt_flip_addr(addr, &packet[3]); 499 log_dbg("Create_connection to "); print_bd_addr(addr); log_dbg("\n"); 500 conn = connection_for_address(addr); 501 if (conn) { 502 // if connection exists 503 if (conn->state == OPEN) { 504 // if OPEN, emit connection complete command 505 hci_emit_connection_complete(conn); 506 } 507 // otherwise, just ignore 508 return 0; // don't sent packet to controller 509 510 } else{ 511 conn = create_connection_for_addr(addr); 512 if (conn){ 513 // create connection struct and register, state = SENT_CREATE_CONNECTION 514 conn->state = SENT_CREATE_CONNECTION; 515 } 516 } 517 } 518 519 // accept connection 520 521 // reject connection 522 523 // close_connection? 524 // set state = SENT_DISCONNECT 525 526 hci_stack.num_cmd_packets--; 527 return hci_stack.hci_transport->send_cmd_packet(packet, size); 528 } 529 530 /** 531 * pre: numcmds >= 0 - it's allowed to send a command to the controller 532 */ 533 int hci_send_cmd(hci_cmd_t *cmd, ...){ 534 va_list argptr; 535 va_start(argptr, cmd); 536 uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer; 537 uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr); 538 va_end(argptr); 539 return hci_send_cmd_packet(hci_cmd_buffer, size); 540 } 541 542 // Create various non-HCI events. 543 // TODO: generalize, use table similar to hci_create_command 544 545 void hci_emit_state(){ 546 uint8_t len = 3; 547 uint8_t event[len]; 548 event[0] = BTSTACK_EVENT_STATE; 549 event[1] = len - 3; 550 event[2] = hci_stack.state; 551 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 552 hci_stack.event_packet_handler(event, len); 553 } 554 555 void hci_emit_connection_complete(hci_connection_t *conn){ 556 uint8_t len = 13; 557 uint8_t event[len]; 558 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 559 event[1] = len - 3; 560 event[2] = 0; // status = OK 561 bt_store_16(event, 3, conn->con_handle); 562 bt_flip_addr(&event[5], conn->address); 563 event[11] = 1; // ACL connection 564 event[12] = 0; // encryption disabled 565 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 566 hci_stack.event_packet_handler(event, len); 567 } 568 569 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 570 uint8_t len = 4; 571 uint8_t event[len]; 572 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 573 event[1] = len - 2; 574 bt_store_16(event, 2, conn->con_handle); 575 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 576 hci_stack.event_packet_handler(event, len); 577 } 578 579 void hci_emit_nr_connections_changed(){ 580 uint8_t len = 3; 581 uint8_t event[len]; 582 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 583 event[1] = len - 2; 584 event[2] = nr_hci_connections(); 585 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 586 hci_stack.event_packet_handler(event, len); 587 } 588 589 void hci_emit_hci_open_failed(){ 590 uint8_t len = 2; 591 uint8_t event[len]; 592 event[0] = BTSTACK_EVENT_POWERON_FAILED; 593 event[1] = len - 2; 594 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 595 hci_stack.event_packet_handler(event, len); 596 } 597 598 599 void hci_emit_btstack_version() { 600 uint8_t len = 6; 601 uint8_t event[len]; 602 event[0] = BTSTACK_EVENT_VERSION; 603 event[1] = len - 2; 604 event[len++] = BTSTACK_MAJOR; 605 event[len++] = BTSTACK_MINOR; 606 bt_store_16(event, len, BTSTACK_REVISION); 607 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 608 hci_stack.event_packet_handler(event, len); 609 } 610 611 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 612 uint8_t len = 3; 613 uint8_t event[len]; 614 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 615 event[1] = len - 2; 616 event[2] = enabled; 617 hci_dump_packet( HCI_EVENT_PACKET, 0, event, len); 618 hci_stack.event_packet_handler(event, len); 619 } 620