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