1 /* 2 * Copyright (C) 2014 BlueKitchen GmbH 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 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN 24 * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define BTSTACK_FILE__ "hci_transport_h2_libusb.c" 39 40 /* 41 * hci_transport_usb.c 42 * 43 * HCI Transport API implementation for USB 44 * 45 * Created by Matthias Ringwald on 7/5/09. 46 */ 47 48 // Interface Number - Alternate Setting - suggested Endpoint Address - Endpoint Type - Suggested Max Packet Size 49 // HCI Commands 0 0 0x00 Control 8/16/32/64 50 // HCI Events 0 0 0x81 Interrupt (IN) 16 51 // ACL Data 0 0 0x82 Bulk (IN) 32/64 52 // ACL Data 0 0 0x02 Bulk (OUT) 32/64 53 // SCO Data 0 0 0x83 Isochronous (IN) 54 // SCO Data 0 0 0x03 Isochronous (Out) 55 56 #include <strings.h> 57 #include <string.h> 58 #include <unistd.h> /* UNIX standard function definitions */ 59 #include <sys/types.h> 60 61 #include <libusb.h> 62 63 // bail out if seen libusb is apperently to old 64 #if !defined(LIBUSB_API_VERSION) || (LIBUSB_API_VERSION < 0x01000104) 65 #error libusb api version to old! 66 #endif 67 68 #include <poll.h> 69 70 #include "btstack_config.h" 71 72 #include "btstack_debug.h" 73 #include "hci.h" 74 #include "hci_transport.h" 75 #include "hci_transport_usb.h" 76 77 #define DEBUG 78 79 // deal with changes in libusb API: 80 #ifdef LIBUSB_API_VERSION 81 #if LIBUSB_API_VERSION >= 0x01000106 82 // since 1.0.22, libusb_set_option replaces libusb_set_debug 83 #define libusb_set_debug(context,level) libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, level) 84 #endif 85 #endif 86 87 #if (USB_VENDOR_ID != 0) && (USB_PRODUCT_ID != 0) 88 #define HAVE_USB_VENDOR_ID_AND_PRODUCT_ID 89 #endif 90 91 #define ACL_IN_BUFFER_COUNT 3 92 #define EVENT_IN_BUFFER_COUNT 3 93 #define EVENT_OUT_BUFFER_COUNT 4 94 #define SCO_IN_BUFFER_COUNT 10 95 96 #define ASYNC_POLLING_INTERVAL_MS 1 97 98 // 99 // Bluetooth USB Transport Alternate Settings: 100 // 101 // 0: No active voice channels (for USB compliance) 102 // 1: One 8 kHz voice channel with 8-bit encoding 103 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding 104 // 3: Three 8 kHz voice channels with 8-bit encoding 105 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding 106 // 5: Three 8 kHz voice channels with 16-bit encoding or one 8 kHz voice channel with 16-bit encoding and one 16 kHz voice channel with 16-bit encoding 107 // --> support only a single SCO connection 108 // #define ALT_SETTING (1) 109 110 #ifdef ENABLE_SCO_OVER_HCI 111 // alt setting for 1-3 connections and 8/16 bit 112 static const int alt_setting_8_bit[] = {1,2,3}; 113 static const int alt_setting_16_bit[] = {2,4,5}; 114 115 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets 116 // One complete SCO packet with 24 frames every 3 frames (== 3 ms) 117 #define NUM_ISO_PACKETS (3) 118 119 static const uint16_t iso_packet_size_for_alt_setting[] = { 120 0, 121 9, 122 17, 123 25, 124 33, 125 49, 126 63, 127 }; 128 #endif 129 130 // 49 bytes is the max usb packet size for alternate setting 5 (Three 8 kHz 16-bit channels or one 8 kHz 16-bit channel and one 16 kHz 16-bit channel) 131 // note: alt setting 6 has max packet size of 63 every 7.5 ms = 472.5 bytes / HCI packet, while max SCO packet has 255 byte payload 132 #define SCO_PACKET_SIZE (49 * NUM_ISO_PACKETS) 133 134 // Outgoing SCO packet queue 135 // simplified ring buffer implementation 136 #define SCO_OUT_BUFFER_COUNT (20) 137 #define SCO_OUT_BUFFER_SIZE (SCO_OUT_BUFFER_COUNT * SCO_PACKET_SIZE) 138 139 // seems to be the max depth for USB 3 140 #define USB_MAX_PATH_LEN 7 141 142 // prototypes 143 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size); 144 static int usb_close(void); 145 146 typedef enum { 147 LIB_USB_CLOSED = 0, 148 LIB_USB_OPENED, 149 LIB_USB_DEVICE_OPENDED, 150 LIB_USB_INTERFACE_CLAIMED, 151 LIB_USB_TRANSFERS_ALLOCATED 152 } libusb_state_t; 153 154 // SCO packet state machine 155 typedef enum { 156 H2_W4_SCO_HEADER = 1, 157 H2_W4_PAYLOAD, 158 } H2_SCO_STATE; 159 160 static libusb_state_t libusb_state = LIB_USB_CLOSED; 161 162 // single instance 163 static hci_transport_t * hci_transport_usb = NULL; 164 165 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = dummy_handler; 166 167 // libusb 168 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID 169 static struct libusb_device_descriptor desc; 170 #endif 171 static libusb_device_handle * handle; 172 173 // known devices 174 typedef struct { 175 btstack_linked_item_t next; 176 uint16_t vendor_id; 177 uint16_t product_id; 178 } usb_known_device_t; 179 180 static btstack_linked_list_t usb_knwon_devices; 181 182 typedef struct list_head { 183 struct list_head *next, *prev; 184 } list_head_t; 185 186 static inline void __list_add( list_head_t *new, list_head_t *prev, list_head_t *next ) { 187 next->prev = new; 188 new->next = next; 189 new->prev = prev; 190 prev->next = new; 191 } 192 193 #define LIST_HEAD_INIT(name) { &(name), &(name) } 194 195 static inline void init_list_head( list_head_t *list ) { 196 list->next = list; 197 list->prev = list; 198 } 199 200 static inline void list_add( list_head_t *new, list_head_t *head ) { 201 __list_add( new, head, head->next ); 202 } 203 204 static inline void list_add_tail( list_head_t *new, list_head_t *head ) { 205 __list_add( new, head->prev, head ); 206 } 207 208 static inline void list_del( list_head_t *entry ) { 209 entry->next->prev = entry->prev; 210 entry->prev->next = entry->next; 211 212 entry->prev = NULL; 213 entry->next = NULL; 214 } 215 216 static inline bool list_empty( list_head_t *head ) { 217 return head->next == head; 218 } 219 220 static inline list_head_t *list_pop_front( list_head_t *head ) { 221 list_head_t *front = head->next; 222 list_del( front ); 223 return front; 224 } 225 226 227 typedef struct { 228 list_head_t list; 229 struct libusb_transfer *t; 230 uint8_t *data; 231 bool in_flight; 232 } usb_transfer_list_entry_t; 233 234 typedef struct { 235 list_head_t transfers; 236 int nbr; 237 usb_transfer_list_entry_t entries[0]; 238 } usb_transfer_list_t; 239 240 static struct libusb_transfer *usb_transfer_list_acquire( usb_transfer_list_t *list ) { 241 usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)list_pop_front( &list->transfers ); 242 struct libusb_transfer *transfer = current->t; 243 current->in_flight = true; 244 return transfer; 245 } 246 void usb_transfer_list_free( usb_transfer_list_t *list ); 247 248 static void usb_transfer_list_release( usb_transfer_list_t *list, struct libusb_transfer *transfer ) { 249 usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)transfer->user_data; 250 btstack_assert( current != NULL ); 251 current->in_flight = false; 252 list_add( ¤t->list, &list->transfers ); 253 } 254 255 static bool usb_transfer_list_empty( usb_transfer_list_t *list ) { 256 return list_empty( &list->transfers ); 257 } 258 259 static usb_transfer_list_t *usb_transfer_list_alloc( int nbr, int iso_packets, int length ) { 260 usb_transfer_list_t *list = malloc( sizeof(usb_transfer_list_t) + nbr*sizeof(usb_transfer_list_entry_t) ); 261 init_list_head( &list->transfers ); 262 list->nbr = nbr; 263 for( int i=0; i<nbr; ++i ) 264 { 265 usb_transfer_list_entry_t *entry = &list->entries[i]; 266 struct libusb_transfer *transfer = libusb_alloc_transfer(iso_packets); 267 entry->data = malloc( length ); 268 transfer->buffer = entry->data; 269 transfer->user_data = entry; 270 entry->t = transfer; 271 usb_transfer_list_release( list, transfer ); 272 btstack_assert( entry->t->user_data != NULL ); 273 } 274 return list; 275 } 276 277 static void usb_transfer_list_cancel( usb_transfer_list_t *list ) { 278 #ifdef __APPLE__ 279 // for darwin ignore all warnings 280 libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR); 281 #endif 282 for( int i=0; i<list->nbr; ++i ) { 283 usb_transfer_list_entry_t *current = &list->entries[i]; 284 if( current->in_flight ) { 285 libusb_cancel_transfer( current->t ); 286 } 287 } 288 #ifdef __APPLE__ 289 libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING); 290 #endif 291 } 292 293 static int usb_transfer_list_in_flight( usb_transfer_list_t *list ) { 294 int cnt = 0; 295 for(int i=0; i<list->nbr; ++i) { 296 usb_transfer_list_entry_t *entry = &list->entries[i]; 297 if( entry->in_flight ) { 298 ++cnt; 299 } 300 } 301 return cnt; 302 } 303 304 305 static void usb_transfer_list_free_entry( struct libusb_transfer *transfer ) { 306 usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)transfer->user_data; 307 free( current->data ); 308 libusb_free_transfer( transfer ); 309 current->in_flight = false; 310 current->t = NULL; 311 current->data = NULL; 312 } 313 314 void usb_transfer_list_free( usb_transfer_list_t *list ) { 315 for( int i=0; i<list->nbr; ++i ) { 316 usb_transfer_list_entry_t *entry = &list->entries[i]; 317 btstack_assert( entry->in_flight == false ); 318 if( entry->t ) { 319 usb_transfer_list_free_entry( entry->t ); 320 } 321 } 322 free( list ); 323 } 324 325 static usb_transfer_list_t *default_transfer_list = NULL; 326 327 // For (ab)use as a linked list of received packets 328 static list_head_t handle_packet_list = LIST_HEAD_INIT(handle_packet_list); 329 330 static void enqueue_transfer(struct libusb_transfer *transfer) { 331 usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)transfer->user_data; 332 btstack_assert( current != NULL ); 333 list_add_tail( ¤t->list, &handle_packet_list ); 334 } 335 336 static void signal_acknowledge(void); 337 static void signal_sco_can_send_now(void); 338 339 #ifdef ENABLE_SCO_OVER_HCI 340 341 #ifdef _WIN32 342 #error "SCO not working on Win32 (Windows 8, libusb 1.0.19, Zadic WinUSB), please uncomment ENABLE_SCO_OVER_HCI in btstack-config.h for now" 343 #endif 344 345 // incoming SCO 346 static H2_SCO_STATE sco_state; 347 static uint8_t sco_buffer[255+3 + SCO_PACKET_SIZE]; 348 static uint16_t sco_read_pos; 349 static uint16_t sco_bytes_to_read; 350 351 // pause/resume 352 static uint16_t sco_voice_setting; 353 static int sco_num_connections; 354 static bool sco_activated; 355 356 // dynamic SCO configuration 357 static uint16_t iso_packet_size; 358 static int sco_enabled; 359 360 usb_transfer_list_t *sco_transfer_list = NULL; 361 362 #endif 363 364 365 static int doing_pollfds; 366 static int num_pollfds; 367 static btstack_data_source_t * pollfd_data_sources; 368 369 static void usb_transport_response_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type); 370 static btstack_data_source_t transport_response; 371 372 static btstack_timer_source_t usb_timer; 373 static int usb_timer_active; 374 375 // endpoint addresses 376 static int event_in_addr; 377 static int acl_in_addr; 378 static int acl_out_addr; 379 static int sco_in_addr; 380 static int sco_out_addr; 381 382 // device info 383 static int usb_path_len; 384 static uint8_t usb_path[USB_MAX_PATH_LEN]; 385 static uint16_t usb_vendor_id; 386 static uint16_t usb_product_id; 387 388 // transport interface state 389 static int usb_transport_open; 390 391 static void hci_transport_h2_libusb_emit_usb_info(void) { 392 uint8_t event[7 + USB_MAX_PATH_LEN]; 393 uint16_t pos = 0; 394 event[pos++] = HCI_EVENT_TRANSPORT_USB_INFO; 395 event[pos++] = 5 + usb_path_len; 396 little_endian_store_16(event, pos, usb_vendor_id); 397 pos+=2; 398 little_endian_store_16(event, pos, usb_product_id); 399 pos+=2; 400 event[pos++] = usb_path_len; 401 memcpy(&event[pos], usb_path, usb_path_len); 402 pos += usb_path_len; 403 (*packet_handler)(HCI_EVENT_PACKET, event, pos); 404 } 405 406 void hci_transport_usb_add_device(uint16_t vendor_id, uint16_t product_id) { 407 usb_known_device_t * device = malloc(sizeof(usb_known_device_t)); 408 if (device != NULL) { 409 device->vendor_id = vendor_id; 410 device->product_id = product_id; 411 btstack_linked_list_add(&usb_knwon_devices, (btstack_linked_item_t *) device); 412 } 413 } 414 415 void hci_transport_usb_set_path(int len, uint8_t * port_numbers){ 416 if (len > USB_MAX_PATH_LEN || !port_numbers){ 417 log_error("hci_transport_usb_set_path: len or port numbers invalid"); 418 return; 419 } 420 usb_path_len = len; 421 memcpy(usb_path, port_numbers, len); 422 } 423 424 LIBUSB_CALL static void async_callback(struct libusb_transfer *transfer) { 425 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) { 426 log_info("shutdown, transfer %p", transfer); 427 usb_transfer_list_free_entry( transfer ); 428 return; 429 } 430 431 int r; 432 // log_info("begin async_callback endpoint %x, status %x, actual length %u", transfer->endpoint, transfer->status, transfer->actual_length ); 433 434 if (transfer->status == LIBUSB_TRANSFER_COMPLETED) { 435 enqueue_transfer(transfer); 436 } else if (transfer->status == LIBUSB_TRANSFER_STALL){ 437 log_info("-> Transfer stalled, trying again"); 438 r = libusb_clear_halt(handle, transfer->endpoint); 439 if (r) { 440 log_error("Error rclearing halt %d", r); 441 } 442 r = libusb_submit_transfer(transfer); 443 if (r) { 444 log_error("Error re-submitting transfer %d", r); 445 } 446 } else if ( transfer->status == LIBUSB_TRANSFER_CANCELLED ) { 447 #ifdef ENABLE_SCO_OVER_HCI 448 if(( transfer->endpoint == sco_in_addr) || (transfer->endpoint == sco_out_addr)) { 449 usb_transfer_list_release( sco_transfer_list, transfer ); 450 } else 451 #endif 452 { 453 usb_transfer_list_release( default_transfer_list, transfer ); 454 } 455 } else { 456 log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length); 457 // No usable data, just resubmit packet 458 r = libusb_submit_transfer(transfer); 459 if (r) { 460 log_error("Error re-submitting transfer %d", r); 461 } 462 } 463 // log_info("end async_callback"); 464 } 465 466 467 #ifdef ENABLE_SCO_OVER_HCI 468 static int usb_send_sco_packet(uint8_t *packet, int size){ 469 int r; 470 471 if( !sco_activated ) { 472 log_error("sco send without beeing active!"); 473 return -1; 474 } 475 476 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1; 477 478 struct libusb_transfer *transfer = usb_transfer_list_acquire( sco_transfer_list ); 479 uint8_t *data = transfer->buffer; 480 void *user_data = transfer->user_data; 481 482 // log_info("usb_send_acl_packet enter, size %u", size); 483 484 // store packet in free slot 485 memcpy(data, packet, size); 486 487 // setup transfer 488 // log_info("usb_send_sco_packet: size %u, max size %u, iso packet size %u", size, NUM_ISO_PACKETS * iso_packet_size, iso_packet_size); 489 libusb_fill_iso_transfer(transfer, handle, sco_out_addr, data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, user_data, 0); 490 libusb_set_iso_packet_lengths(transfer, iso_packet_size); 491 r = libusb_submit_transfer(transfer); 492 if (r < 0) { 493 log_error("Error submitting sco transfer, %d", r); 494 return -1; 495 } 496 497 // log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_out_transfers_active); 498 signal_acknowledge(); 499 500 if( !usb_transfer_list_empty( sco_transfer_list ) ) { 501 signal_sco_can_send_now(); 502 } 503 504 return 0; 505 } 506 507 static void sco_state_machine_init(void){ 508 sco_state = H2_W4_SCO_HEADER; 509 sco_read_pos = 0; 510 sco_bytes_to_read = 3; 511 } 512 513 static void handle_isochronous_data(uint8_t * buffer, uint16_t size){ 514 while (size){ 515 if (size < sco_bytes_to_read){ 516 // just store incomplete data 517 memcpy(&sco_buffer[sco_read_pos], buffer, size); 518 sco_read_pos += size; 519 sco_bytes_to_read -= size; 520 return; 521 } 522 // copy requested data 523 memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read); 524 sco_read_pos += sco_bytes_to_read; 525 buffer += sco_bytes_to_read; 526 size -= sco_bytes_to_read; 527 528 // chunk read successfully, next action 529 switch (sco_state){ 530 case H2_W4_SCO_HEADER: 531 sco_state = H2_W4_PAYLOAD; 532 sco_bytes_to_read = sco_buffer[2]; 533 break; 534 case H2_W4_PAYLOAD: 535 // packet complete 536 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos); 537 sco_state_machine_init(); 538 break; 539 default: 540 btstack_assert(false); 541 break; 542 } 543 } 544 } 545 #endif 546 547 static void handle_completed_transfer(struct libusb_transfer *transfer){ 548 549 int resubmit = 0; 550 if (transfer->endpoint == event_in_addr) { 551 packet_handler(HCI_EVENT_PACKET, transfer->buffer, transfer->actual_length); 552 resubmit = 1; 553 } else if (transfer->endpoint == acl_in_addr) { 554 // log_info("-> acl"); 555 packet_handler(HCI_ACL_DATA_PACKET, transfer->buffer, transfer->actual_length); 556 resubmit = 1; 557 } else if (transfer->endpoint == 0){ 558 // log_info("command done, size %u", transfer->actual_length); 559 // printf("%s cmd release\n", __FUNCTION__ ); 560 usb_transfer_list_release( default_transfer_list, transfer ); 561 } else if (transfer->endpoint == acl_out_addr){ 562 // log_info("acl out done, size %u", transfer->actual_length); 563 // printf("%s acl release\n", __FUNCTION__ ); 564 usb_transfer_list_release( default_transfer_list, transfer ); 565 #ifdef ENABLE_SCO_OVER_HCI 566 } else if (transfer->endpoint == sco_in_addr) { 567 // log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS); 568 569 // give the transfer back to the pool, without resubmiting 570 if( !sco_activated ) { 571 usb_transfer_list_release( sco_transfer_list, transfer ); 572 return; 573 } 574 575 int i; 576 for (i = 0; i < transfer->num_iso_packets; i++) { 577 struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i]; 578 if (pack->status != LIBUSB_TRANSFER_COMPLETED) { 579 log_error("Error: pack %u status %d\n", i, pack->status); 580 continue; 581 } 582 if (!pack->actual_length) continue; 583 uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i); 584 handle_isochronous_data(data, pack->actual_length); 585 } 586 resubmit = 1; 587 } else if (transfer->endpoint == sco_out_addr){ 588 int i; 589 for (i = 0; i < transfer->num_iso_packets; i++) { 590 struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i]; 591 if (pack->status != LIBUSB_TRANSFER_COMPLETED) { 592 log_error("Error: pack %u status %d\n", i, pack->status); 593 } 594 } 595 usb_transfer_list_release( sco_transfer_list, transfer ); 596 if( !sco_activated ) { 597 return; 598 } 599 // log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}", 600 // transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status, 601 // transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status, 602 // transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status); 603 // notify upper layer if there's space for new SCO packets 604 605 if (!usb_transfer_list_empty(sco_transfer_list)) { 606 signal_sco_can_send_now(); 607 } 608 // log_info("H2: sco out complete, num active num active %u", sco_out_transfers_active); 609 #endif 610 } else { 611 log_info("usb_process_ds endpoint unknown %x", transfer->endpoint); 612 } 613 614 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return; 615 616 if (resubmit){ 617 // Re-submit transfer 618 int r = libusb_submit_transfer(transfer); 619 if (r) { 620 log_error("Error re-submitting transfer %d", r); 621 } 622 } 623 } 624 625 void usb_handle_pending_events(void); 626 void usb_handle_pending_events(void) { 627 struct timeval tv = { 0 }; 628 libusb_handle_events_timeout_completed(NULL, &tv, NULL); 629 } 630 631 static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) { 632 633 UNUSED(ds); 634 UNUSED(callback_type); 635 636 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return; 637 638 // log_info("begin usb_process_ds"); 639 // always handling an event as we're called when data is ready 640 usb_handle_pending_events(); 641 642 // Handle any packet in the order that they were received 643 while (!list_empty(&handle_packet_list)) { 644 // log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status); 645 646 // pop next transfer 647 usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)list_pop_front( &handle_packet_list ); 648 649 // handle transfer 650 handle_completed_transfer(current->t); 651 652 // handle case where libusb_close might be called by hci packet handler 653 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return; 654 } 655 // log_info("end usb_process_ds"); 656 } 657 658 static void usb_process_ts(btstack_timer_source_t *timer) { 659 660 UNUSED(timer); 661 662 // log_info("in usb_process_ts"); 663 664 // timer is deactive, when timer callback gets called 665 usb_timer_active = 0; 666 667 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return; 668 669 // actually handled the packet in the pollfds function 670 usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ); 671 672 // Get the amount of time until next event is due 673 long msec = ASYNC_POLLING_INTERVAL_MS; 674 675 // Activate timer 676 btstack_run_loop_set_timer(&usb_timer, msec); 677 btstack_run_loop_add_timer(&usb_timer); 678 usb_timer_active = 1; 679 680 return; 681 } 682 683 684 static int scan_for_bt_endpoints(libusb_device *dev) { 685 int r; 686 687 event_in_addr = 0; 688 acl_in_addr = 0; 689 acl_out_addr = 0; 690 sco_out_addr = 0; 691 sco_in_addr = 0; 692 693 // get endpoints from interface descriptor 694 struct libusb_config_descriptor *config_descriptor; 695 r = libusb_get_active_config_descriptor(dev, &config_descriptor); 696 if (r < 0) return r; 697 698 int num_interfaces = config_descriptor->bNumInterfaces; 699 log_info("active configuration has %u interfaces", num_interfaces); 700 701 int i; 702 for (i = 0; i < num_interfaces ; i++){ 703 const struct libusb_interface *interface = &config_descriptor->interface[i]; 704 const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting; 705 log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints); 706 707 const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint; 708 709 for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){ 710 log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes); 711 712 switch (endpoint->bmAttributes & 0x3){ 713 case LIBUSB_TRANSFER_TYPE_INTERRUPT: 714 if (event_in_addr) continue; 715 event_in_addr = endpoint->bEndpointAddress; 716 log_info("-> using 0x%2.2X for HCI Events", event_in_addr); 717 break; 718 case LIBUSB_TRANSFER_TYPE_BULK: 719 if (endpoint->bEndpointAddress & 0x80) { 720 if (acl_in_addr) continue; 721 acl_in_addr = endpoint->bEndpointAddress; 722 log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr); 723 } else { 724 if (acl_out_addr) continue; 725 acl_out_addr = endpoint->bEndpointAddress; 726 log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr); 727 } 728 break; 729 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: 730 if (endpoint->bEndpointAddress & 0x80) { 731 if (sco_in_addr) continue; 732 sco_in_addr = endpoint->bEndpointAddress; 733 log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr); 734 } else { 735 if (sco_out_addr) continue; 736 sco_out_addr = endpoint->bEndpointAddress; 737 log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr); 738 } 739 break; 740 default: 741 break; 742 } 743 } 744 } 745 libusb_free_config_descriptor(config_descriptor); 746 return 0; 747 } 748 749 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID 750 751 // list of known devices, using VendorID/ProductID tuples 752 static const uint16_t known_bluetooth_devices[] = { 753 // BCM20702A0 - DeLOCK Bluetooth 4.0 754 0x0a5c, 0x21e8, 755 // BCM20702A0 - Asus BT400 756 0x0b05, 0x17cb, 757 // BCM20702B0 - Generic USB Detuned Class 1 @ 20 MHz 758 0x0a5c, 0x22be, 759 // nRF5x Zephyr USB HCI, e.g nRF52840-PCA10056 760 0x2fe3, 0x0100, 761 0x2fe3, 0x000b, 762 }; 763 764 static int num_known_devices = sizeof(known_bluetooth_devices) / sizeof(uint16_t) / 2; 765 766 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){ 767 int i; 768 for (i=0; i<num_known_devices; i++){ 769 if (known_bluetooth_devices[i*2] == vendor_id && known_bluetooth_devices[i*2+1] == product_id){ 770 return 1; 771 } 772 } 773 btstack_linked_list_iterator_t it; 774 btstack_linked_list_iterator_init(&it, &usb_knwon_devices); 775 while (btstack_linked_list_iterator_has_next(&it)) { 776 usb_known_device_t * device = (usb_known_device_t *) btstack_linked_list_iterator_next(&it); 777 if (device->vendor_id != vendor_id) continue; 778 if (device->product_id != product_id) continue; 779 return 1; 780 } 781 return 0; 782 } 783 784 // returns index of found device or -1 785 static int scan_for_bt_device(libusb_device **devs, int start_index) { 786 int i; 787 for (i = start_index; devs[i] ; i++){ 788 libusb_device * dev = devs[i]; 789 int r = libusb_get_device_descriptor(dev, &desc); 790 if (r < 0) { 791 log_error("failed to get device descriptor"); 792 return 0; 793 } 794 795 log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ", 796 desc.idVendor, desc.idProduct, 797 libusb_get_bus_number(dev), libusb_get_device_address(dev), 798 desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol); 799 800 // Detect USB Dongle based Class, Subclass, and Protocol 801 // The class code (bDeviceClass) is 0xE0 – Wireless Controller. 802 // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller. 803 // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming. 804 if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) { 805 return i; 806 } 807 808 // Detect USB Dongle based on whitelist 809 if (is_known_bt_device(desc.idVendor, desc.idProduct)) { 810 return i; 811 } 812 } 813 return -1; 814 } 815 #endif 816 817 static int prepare_device(libusb_device_handle * aHandle){ 818 819 // get device path 820 libusb_device * device = libusb_get_device(aHandle); 821 usb_path_len = libusb_get_port_numbers(device, usb_path, USB_MAX_PATH_LEN); 822 823 int r; 824 int kernel_driver_detached = 0; 825 826 // Detach OS driver (not possible for OS X, FreeBSD, and Windows) 827 #if !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) && !defined(__FreeBSD__) 828 r = libusb_kernel_driver_active(aHandle, 0); 829 if (r < 0) { 830 log_error("libusb_kernel_driver_active error %d", r); 831 libusb_close(aHandle); 832 return r; 833 } 834 835 if (r == 1) { 836 r = libusb_detach_kernel_driver(aHandle, 0); 837 if (r < 0) { 838 log_error("libusb_detach_kernel_driver error %d", r); 839 libusb_close(aHandle); 840 return r; 841 } 842 kernel_driver_detached = 1; 843 } 844 log_info("libusb_detach_kernel_driver"); 845 #endif 846 847 const int configuration = 1; 848 log_info("setting configuration %d...", configuration); 849 r = libusb_set_configuration(aHandle, configuration); 850 if (r < 0) { 851 log_error("Error libusb_set_configuration: %d", r); 852 if (kernel_driver_detached){ 853 libusb_attach_kernel_driver(aHandle, 0); 854 } 855 libusb_close(aHandle); 856 return r; 857 } 858 859 // reserve access to device 860 log_info("claiming interface 0..."); 861 r = libusb_claim_interface(aHandle, 0); 862 if (r < 0) { 863 log_error("Error %d claiming interface 0", r); 864 if (kernel_driver_detached){ 865 libusb_attach_kernel_driver(aHandle, 0); 866 } 867 libusb_close(aHandle); 868 return r; 869 } 870 871 #ifdef ENABLE_SCO_OVER_HCI 872 // get endpoints from interface descriptor 873 struct libusb_config_descriptor *config_descriptor; 874 r = libusb_get_active_config_descriptor(device, &config_descriptor); 875 if (r >= 0){ 876 int num_interfaces = config_descriptor->bNumInterfaces; 877 if (num_interfaces > 1) { 878 r = libusb_claim_interface(aHandle, 1); 879 if (r < 0) { 880 log_error("Error %d claiming interface 1: - disabling SCO over HCI", r); 881 } else { 882 sco_enabled = 1; 883 } 884 } else { 885 log_info("Device has only on interface, disabling SCO over HCI"); 886 } 887 } 888 #endif 889 890 return 0; 891 } 892 893 static libusb_device_handle * try_open_device(libusb_device * device){ 894 int r; 895 896 r = libusb_get_device_descriptor(device, &desc); 897 if (r < 0) { 898 log_error("libusb_get_device_descriptor failed!"); 899 return NULL; 900 } 901 usb_vendor_id = desc.idVendor; 902 usb_product_id = desc.idProduct; 903 904 libusb_device_handle * dev_handle; 905 r = libusb_open(device, &dev_handle); 906 907 if (r < 0) { 908 log_error("libusb_open failed!"); 909 dev_handle = NULL; 910 return NULL; 911 } 912 913 log_info("libusb open %d, handle %p", r, dev_handle); 914 915 // reset device (Not currently possible under FreeBSD 11.x/12.x due to usb framework) 916 #if !defined(__FreeBSD__) 917 r = libusb_reset_device(dev_handle); 918 if (r < 0) { 919 log_error("libusb_reset_device failed!"); 920 libusb_close(dev_handle); 921 return NULL; 922 } 923 #endif 924 return dev_handle; 925 } 926 927 #ifdef ENABLE_SCO_OVER_HCI 928 static int usb_sco_start(void){ 929 930 log_info("usb_sco_start"); 931 if( sco_activated ) { 932 log_error("double sco start!"); 933 return -1; 934 } 935 sco_activated = true; 936 937 sco_state_machine_init(); 938 939 int alt_setting; 940 if (sco_voice_setting & 0x0020){ 941 // 16-bit PCM 942 alt_setting = alt_setting_16_bit[sco_num_connections-1]; 943 } else { 944 // 8-bit PCM or mSBC 945 alt_setting = alt_setting_8_bit[sco_num_connections-1]; 946 } 947 // derive iso packet size from alt setting 948 iso_packet_size = iso_packet_size_for_alt_setting[alt_setting]; 949 950 log_info("Switching to setting %u on interface 1..", alt_setting); 951 int r = libusb_set_interface_alt_setting(handle, 1, alt_setting); 952 if (r < 0) { 953 log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r)); 954 return r; 955 } 956 957 #ifdef DEBUG 958 int in_flight = usb_transfer_list_in_flight( sco_transfer_list ); 959 // there need to be at least SCO_IN_BUFFER_COUNT packets available to 960 // fill them in below 961 btstack_assert( in_flight <= SCO_OUT_BUFFER_COUNT ); 962 #endif 963 964 // incoming 965 int c; 966 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) { 967 968 struct libusb_transfer *transfer = usb_transfer_list_acquire( sco_transfer_list ); 969 uint8_t *data = transfer->buffer; 970 void *user_data = transfer->user_data; 971 972 // configure sco_in handlers 973 libusb_fill_iso_transfer(transfer, handle, sco_in_addr, 974 data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, user_data, 0); 975 libusb_set_iso_packet_lengths(transfer, iso_packet_size); 976 r = libusb_submit_transfer(transfer); 977 if (r) { 978 log_error("Error submitting isochronous in transfer %d", r); 979 usb_close(); 980 return r; 981 } 982 } 983 return 0; 984 } 985 986 static void usb_sco_stop(void){ 987 988 log_info("usb_sco_stop"); 989 sco_activated = false; 990 991 usb_transfer_list_cancel( sco_transfer_list ); 992 993 log_info("Switching to setting %u on interface 1..", 0); 994 int r = libusb_set_interface_alt_setting(handle, 1, 0); 995 if (r < 0) { 996 log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r)); 997 return; 998 } 999 1000 log_info("usb_sco_stop done"); 1001 } 1002 #endif 1003 1004 void pollfd_added_cb(int fd, short events, void *user_data); 1005 void pollfd_remove_cb(int fd, void *user_data); 1006 1007 void pollfd_added_cb(int fd, short events, void *user_data) { 1008 UNUSED(fd); 1009 UNUSED(events); 1010 UNUSED(user_data); 1011 log_error("add fd: %d", fd); 1012 btstack_assert(0); 1013 } 1014 1015 void pollfd_remove_cb(int fd, void *user_data) { 1016 UNUSED(fd); 1017 UNUSED(user_data); 1018 log_error("remove fd: %d", fd); 1019 btstack_assert(0); 1020 } 1021 1022 static int usb_open(void){ 1023 int r; 1024 1025 if (usb_transport_open) return 0; 1026 1027 // default endpoint addresses 1028 event_in_addr = 0x81; // EP1, IN interrupt 1029 acl_in_addr = 0x82; // EP2, IN bulk 1030 acl_out_addr = 0x02; // EP2, OUT bulk 1031 sco_in_addr = 0x83; // EP3, IN isochronous 1032 sco_out_addr = 0x03; // EP3, OUT isochronous 1033 1034 // USB init 1035 r = libusb_init(NULL); 1036 if (r < 0) return -1; 1037 1038 libusb_state = LIB_USB_OPENED; 1039 1040 // configure debug level 1041 libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING); 1042 1043 libusb_device * dev = NULL; 1044 1045 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID 1046 1047 // Use a specified device 1048 log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID); 1049 handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID); 1050 1051 if (!handle){ 1052 log_error("libusb_open_device_with_vid_pid failed!"); 1053 usb_close(); 1054 return -1; 1055 } 1056 log_info("libusb open %d, handle %p", r, handle); 1057 1058 r = prepare_device(handle); 1059 if (r < 0){ 1060 usb_close(); 1061 return -1; 1062 } 1063 1064 dev = libusb_get_device(handle); 1065 r = scan_for_bt_endpoints(dev); 1066 if (r < 0){ 1067 usb_close(); 1068 return -1; 1069 } 1070 1071 usb_vendor_id = USB_VENDOR_ID; 1072 usb_product_id = USB_PRODUCT_ID; 1073 1074 #else 1075 // Scan system for an appropriate devices 1076 libusb_device **devs; 1077 ssize_t num_devices; 1078 1079 log_info("Scanning for USB Bluetooth device"); 1080 num_devices = libusb_get_device_list(NULL, &devs); 1081 if (num_devices < 0) { 1082 usb_close(); 1083 return -1; 1084 } 1085 1086 if (usb_path_len){ 1087 int i; 1088 for (i=0;i<num_devices;i++){ 1089 uint8_t port_numbers[USB_MAX_PATH_LEN]; 1090 int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN); 1091 if (len != usb_path_len) continue; 1092 if (memcmp(usb_path, port_numbers, len) == 0){ 1093 log_info("USB device found at specified path"); 1094 handle = try_open_device(devs[i]); 1095 if (!handle) continue; 1096 1097 r = prepare_device(handle); 1098 if (r < 0) { 1099 handle = NULL; 1100 continue; 1101 } 1102 1103 dev = devs[i]; 1104 r = scan_for_bt_endpoints(dev); 1105 if (r < 0) { 1106 handle = NULL; 1107 continue; 1108 } 1109 1110 libusb_state = LIB_USB_INTERFACE_CLAIMED; 1111 break; 1112 }; 1113 } 1114 if (!handle){ 1115 log_error("USB device with given path not found"); 1116 return -1; 1117 } 1118 } else { 1119 1120 int deviceIndex = -1; 1121 while (true){ 1122 // look for next Bluetooth dongle 1123 deviceIndex = scan_for_bt_device(devs, deviceIndex+1); 1124 if (deviceIndex < 0) break; 1125 1126 log_info("USB Bluetooth device found, index %u", deviceIndex); 1127 1128 handle = try_open_device(devs[deviceIndex]); 1129 if (!handle) continue; 1130 1131 r = prepare_device(handle); 1132 if (r < 0) { 1133 handle = NULL; 1134 continue; 1135 } 1136 1137 dev = devs[deviceIndex]; 1138 r = scan_for_bt_endpoints(dev); 1139 if (r < 0) { 1140 handle = NULL; 1141 continue; 1142 } 1143 1144 libusb_state = LIB_USB_INTERFACE_CLAIMED; 1145 break; 1146 } 1147 } 1148 1149 libusb_free_device_list(devs, 1); 1150 1151 if (handle == 0){ 1152 log_error("No USB Bluetooth device found"); 1153 return -1; 1154 } 1155 1156 #endif 1157 1158 // allocate transfer handlers 1159 int c; 1160 1161 default_transfer_list = usb_transfer_list_alloc( 1162 EVENT_OUT_BUFFER_COUNT+EVENT_IN_BUFFER_COUNT+ACL_IN_BUFFER_COUNT, 1163 0, 1164 LIBUSB_CONTROL_SETUP_SIZE + HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE ); // biggest packet ever to expect 1165 1166 #ifdef ENABLE_SCO_OVER_HCI 1167 sco_transfer_list = usb_transfer_list_alloc( 1168 SCO_OUT_BUFFER_COUNT+SCO_IN_BUFFER_COUNT, 1169 NUM_ISO_PACKETS, 1170 SCO_PACKET_SIZE 1171 ); 1172 #endif 1173 1174 // TODO check for error 1175 1176 libusb_state = LIB_USB_TRANSFERS_ALLOCATED; 1177 1178 for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) { 1179 struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list ); 1180 uint8_t *data = transfer->buffer; 1181 void *user_data = transfer->user_data; 1182 // configure event_in handlers 1183 libusb_fill_interrupt_transfer(transfer, handle, event_in_addr, 1184 data, HCI_ACL_BUFFER_SIZE, async_callback, user_data, 0); 1185 r = libusb_submit_transfer(transfer); 1186 if (r) { 1187 log_error("Error submitting interrupt transfer %d", r); 1188 usb_close(); 1189 return r; 1190 } 1191 } 1192 1193 for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) { 1194 struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list ); 1195 usb_transfer_list_entry_t *transfer_meta_data = (usb_transfer_list_entry_t*)transfer->user_data; 1196 uint8_t *data = transfer_meta_data->data; 1197 void *user_data = transfer->user_data; 1198 // configure acl_in handlers 1199 libusb_fill_bulk_transfer(transfer, handle, acl_in_addr, 1200 data + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, user_data, 0) ; 1201 r = libusb_submit_transfer(transfer); 1202 if (r) { 1203 log_error("Error submitting bulk in transfer %d", r); 1204 usb_close(); 1205 return r; 1206 } 1207 1208 } 1209 1210 // Check for pollfds functionality 1211 doing_pollfds = libusb_pollfds_handle_timeouts(NULL); 1212 1213 libusb_set_pollfd_notifiers( NULL, pollfd_added_cb, pollfd_remove_cb, NULL ); 1214 1215 if (doing_pollfds) { 1216 log_info("Async using pollfds:"); 1217 1218 const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL); 1219 for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++); 1220 pollfd_data_sources = (btstack_data_source_t *)malloc(sizeof(btstack_data_source_t) * num_pollfds); 1221 if (!pollfd_data_sources){ 1222 log_error("Cannot allocate data sources for pollfds"); 1223 usb_close(); 1224 return 1; 1225 } 1226 memset(pollfd_data_sources, 0, sizeof(btstack_data_source_t) * num_pollfds); 1227 for (r = 0 ; r < num_pollfds ; r++) { 1228 btstack_data_source_t *ds = &pollfd_data_sources[r]; 1229 btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd); 1230 btstack_run_loop_set_data_source_handler(ds, &usb_process_ds); 1231 if( pollfd[r]->events & POLLIN ) 1232 btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ); 1233 else 1234 btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE); 1235 btstack_run_loop_add_data_source(ds); 1236 log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events); 1237 } 1238 libusb_free_pollfds(pollfd); 1239 } else { 1240 log_info("Async using timers:"); 1241 1242 usb_timer.process = usb_process_ts; 1243 btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS); 1244 btstack_run_loop_add_timer(&usb_timer); 1245 usb_timer_active = 1; 1246 } 1247 1248 usb_transport_open = 1; 1249 1250 hci_transport_h2_libusb_emit_usb_info(); 1251 1252 btstack_data_source_t *ds = &transport_response; 1253 btstack_run_loop_set_data_source_handler(ds, &usb_transport_response_ds); 1254 btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_POLL); 1255 btstack_run_loop_add_data_source(ds); 1256 return 0; 1257 } 1258 1259 static int usb_close(void) { 1260 if (!usb_transport_open) return 0; 1261 1262 log_info("usb_close"); 1263 1264 switch (libusb_state){ 1265 case LIB_USB_CLOSED: 1266 break; 1267 1268 case LIB_USB_TRANSFERS_ALLOCATED: 1269 libusb_state = LIB_USB_INTERFACE_CLAIMED; 1270 1271 if(usb_timer_active) { 1272 btstack_run_loop_remove_timer(&usb_timer); 1273 usb_timer_active = 0; 1274 } 1275 1276 if (doing_pollfds){ 1277 int r; 1278 for (r = 0 ; r < num_pollfds ; r++) { 1279 btstack_data_source_t *ds = &pollfd_data_sources[r]; 1280 btstack_run_loop_remove_data_source(ds); 1281 } 1282 free(pollfd_data_sources); 1283 pollfd_data_sources = NULL; 1284 num_pollfds = 0; 1285 doing_pollfds = 0; 1286 } 1287 1288 /* fall through */ 1289 1290 case LIB_USB_INTERFACE_CLAIMED: 1291 libusb_set_pollfd_notifiers( NULL, NULL, NULL, NULL ); 1292 usb_transfer_list_cancel( default_transfer_list ); 1293 #ifdef ENABLE_SCO_OVER_HCI 1294 usb_transfer_list_cancel( sco_transfer_list ); 1295 #endif 1296 1297 int in_flight_transfers = usb_transfer_list_in_flight( default_transfer_list ); 1298 #ifdef ENABLE_SCO_OVER_HCI 1299 in_flight_transfers += usb_transfer_list_in_flight( sco_transfer_list ); 1300 #endif 1301 while( in_flight_transfers > 0 ) { 1302 struct timeval tv = { 0 }; 1303 libusb_handle_events_timeout(NULL, &tv); 1304 1305 in_flight_transfers = usb_transfer_list_in_flight( default_transfer_list ); 1306 #ifdef ENABLE_SCO_OVER_HCI 1307 in_flight_transfers += usb_transfer_list_in_flight( sco_transfer_list ); 1308 #endif 1309 } 1310 1311 usb_transfer_list_free( default_transfer_list ); 1312 #ifdef ENABLE_SCO_OVER_HCI 1313 usb_transfer_list_free( sco_transfer_list ); 1314 sco_enabled = 0; 1315 #endif 1316 1317 // finally release interface 1318 libusb_release_interface(handle, 0); 1319 #ifdef ENABLE_SCO_OVER_HCI 1320 libusb_release_interface(handle, 1); 1321 #endif 1322 log_info("Libusb shutdown complete"); 1323 1324 /* fall through */ 1325 1326 case LIB_USB_DEVICE_OPENDED: 1327 libusb_close(handle); 1328 1329 /* fall through */ 1330 1331 case LIB_USB_OPENED: 1332 libusb_exit(NULL); 1333 break; 1334 1335 default: 1336 btstack_assert(false); 1337 break; 1338 } 1339 1340 libusb_state = LIB_USB_CLOSED; 1341 handle = NULL; 1342 usb_transport_open = 0; 1343 1344 return 0; 1345 } 1346 1347 static int acknowledge_count = 0; 1348 static void signal_acknowledge(void) { 1349 ++acknowledge_count; 1350 btstack_run_loop_poll_data_sources_from_irq(); 1351 } 1352 1353 static int sco_can_send_now_count = 0; 1354 static void signal_sco_can_send_now(void) { 1355 ++sco_can_send_now_count; 1356 btstack_run_loop_poll_data_sources_from_irq(); 1357 } 1358 1359 static void usb_transport_response_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) { 1360 UNUSED(ds); 1361 UNUSED(callback_type); 1362 // printf("%s packet sent: %d sco can send now: %d\n", __FUNCTION__, acknowledge_count, sco_can_send_now_count); 1363 for(; acknowledge_count>0; --acknowledge_count) { 1364 static const uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0 }; 1365 packet_handler(HCI_EVENT_PACKET, (uint8_t*)&event[0], sizeof(event)); 1366 } 1367 1368 for(; sco_can_send_now_count>0; --sco_can_send_now_count) { 1369 static const uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 }; 1370 packet_handler(HCI_EVENT_PACKET, (uint8_t*)&event[0], sizeof(event)); 1371 } 1372 1373 } 1374 1375 static int usb_send_cmd_packet(uint8_t *packet, int size){ 1376 int r; 1377 1378 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1; 1379 // printf("%s( %p, %d )\n", __FUNCTION__, packet, size ); 1380 1381 struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list ); 1382 uint8_t *data = transfer->buffer; 1383 void *user_data = transfer->user_data; 1384 1385 // async 1386 libusb_fill_control_setup(data, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size); 1387 memcpy(data + LIBUSB_CONTROL_SETUP_SIZE, packet, size); 1388 1389 // prepare transfer 1390 libusb_fill_control_transfer(transfer, handle, data, async_callback, user_data, 0); 1391 1392 // submit transfer 1393 r = libusb_submit_transfer(transfer); 1394 1395 if (r < 0) { 1396 log_error("Error submitting cmd transfer %d", r); 1397 return -1; 1398 } 1399 1400 signal_acknowledge(); 1401 1402 return 0; 1403 } 1404 1405 static int usb_send_acl_packet(uint8_t *packet, int size){ 1406 int r; 1407 1408 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1; 1409 // printf("%s( %p, %d )\n", __FUNCTION__, packet, size ); 1410 // log_info("usb_send_acl_packet enter, size %u", size); 1411 1412 struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list ); 1413 uint8_t *data = transfer->buffer; 1414 1415 // prepare transfer 1416 memcpy( data, packet, size ); 1417 libusb_fill_bulk_transfer(transfer, handle, acl_out_addr, data, size, 1418 async_callback, transfer->user_data, 0); 1419 1420 r = libusb_submit_transfer(transfer); 1421 1422 if (r < 0) { 1423 log_error("Error submitting acl transfer, %d", r); 1424 return -1; 1425 } 1426 1427 signal_acknowledge(); 1428 1429 return 0; 1430 } 1431 1432 static int usb_can_send_packet_now(uint8_t packet_type){ 1433 switch (packet_type){ 1434 case HCI_COMMAND_DATA_PACKET: { 1435 int ret = !usb_transfer_list_empty( default_transfer_list ); 1436 if( !ret ) { 1437 log_error("command transfers shouldn't be empty!"); 1438 } 1439 return ret; 1440 } 1441 case HCI_ACL_DATA_PACKET: { 1442 int ret = !usb_transfer_list_empty( default_transfer_list ); 1443 if( !ret ) { 1444 log_error("acl transfers shouldn't be empty!"); 1445 } 1446 return ret; 1447 } 1448 1449 #ifdef ENABLE_SCO_OVER_HCI 1450 case HCI_SCO_DATA_PACKET: { 1451 if (!sco_enabled || !sco_activated) return 0; 1452 int ret = !usb_transfer_list_empty( sco_transfer_list ); 1453 if( !ret ) { 1454 log_error("sco transfers shouldn't be empty!"); 1455 } 1456 return ret; 1457 } 1458 #endif 1459 default: 1460 return 0; 1461 } 1462 } 1463 1464 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){ 1465 switch (packet_type){ 1466 case HCI_COMMAND_DATA_PACKET: 1467 return usb_send_cmd_packet(packet, size); 1468 case HCI_ACL_DATA_PACKET: 1469 return usb_send_acl_packet(packet, size); 1470 #ifdef ENABLE_SCO_OVER_HCI 1471 case HCI_SCO_DATA_PACKET: 1472 if (!sco_enabled) return -1; 1473 return usb_send_sco_packet(packet, size); 1474 #endif 1475 default: 1476 return -1; 1477 } 1478 } 1479 1480 #ifdef ENABLE_SCO_OVER_HCI 1481 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){ 1482 if (!sco_enabled) return; 1483 1484 log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections); 1485 1486 if (num_connections != sco_num_connections){ 1487 sco_voice_setting = voice_setting; 1488 if (sco_num_connections){ 1489 usb_sco_stop(); 1490 } 1491 sco_num_connections = num_connections; 1492 if (num_connections){ 1493 usb_sco_start(); 1494 } 1495 } 1496 } 1497 #endif 1498 1499 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 1500 log_info("registering packet handler"); 1501 packet_handler = handler; 1502 } 1503 1504 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 1505 UNUSED(packet_type); 1506 UNUSED(packet); 1507 UNUSED(size); 1508 } 1509 1510 // get usb singleton 1511 const hci_transport_t * hci_transport_usb_instance(void) { 1512 if (!hci_transport_usb) { 1513 hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t)); 1514 memset(hci_transport_usb, 0, sizeof(hci_transport_t)); 1515 hci_transport_usb->name = "H2_LIBUSB"; 1516 hci_transport_usb->open = usb_open; 1517 hci_transport_usb->close = usb_close; 1518 hci_transport_usb->register_packet_handler = usb_register_packet_handler; 1519 hci_transport_usb->can_send_packet_now = usb_can_send_packet_now; 1520 hci_transport_usb->send_packet = usb_send_packet; 1521 #ifdef ENABLE_SCO_OVER_HCI 1522 hci_transport_usb->set_sco_config = usb_set_sco_config; 1523 #endif 1524 } 1525 return hci_transport_usb; 1526 } 1527