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