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 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 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 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 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 usb_transfer_list_release( default_transfer_list, transfer ); 453 #ifdef ENABLE_SCO_OVER_HCI 454 } 455 #endif 456 } else { 457 log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length); 458 // No usable data, just resubmit packet 459 r = libusb_submit_transfer(transfer); 460 if (r) { 461 log_error("Error re-submitting transfer %d", r); 462 } 463 } 464 // log_info("end async_callback"); 465 } 466 467 468 #ifdef ENABLE_SCO_OVER_HCI 469 static int usb_send_sco_packet(uint8_t *packet, int size){ 470 int r; 471 472 if( !sco_activated ) { 473 log_error("sco send without beeing active!"); 474 return -1; 475 } 476 477 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1; 478 479 struct libusb_transfer *transfer = usb_transfer_list_acquire( sco_transfer_list ); 480 uint8_t *data = transfer->buffer; 481 void *user_data = transfer->user_data; 482 483 // log_info("usb_send_acl_packet enter, size %u", size); 484 485 // store packet in free slot 486 memcpy(data, packet, size); 487 488 // setup transfer 489 // 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); 490 libusb_fill_iso_transfer(transfer, handle, sco_out_addr, data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, user_data, 0); 491 libusb_set_iso_packet_lengths(transfer, iso_packet_size); 492 r = libusb_submit_transfer(transfer); 493 if (r < 0) { 494 log_error("Error submitting sco transfer, %d", r); 495 return -1; 496 } 497 498 // log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_out_transfers_active); 499 signal_acknowledge(); 500 501 if( !usb_transfer_list_empty( sco_transfer_list ) ) { 502 signal_sco_can_send_now(); 503 } 504 505 return 0; 506 } 507 508 static void sco_state_machine_init(void){ 509 sco_state = H2_W4_SCO_HEADER; 510 sco_read_pos = 0; 511 sco_bytes_to_read = 3; 512 } 513 514 static void handle_isochronous_data(uint8_t * buffer, uint16_t size){ 515 while (size){ 516 if (size < sco_bytes_to_read){ 517 // just store incomplete data 518 memcpy(&sco_buffer[sco_read_pos], buffer, size); 519 sco_read_pos += size; 520 sco_bytes_to_read -= size; 521 return; 522 } 523 // copy requested data 524 memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read); 525 sco_read_pos += sco_bytes_to_read; 526 buffer += sco_bytes_to_read; 527 size -= sco_bytes_to_read; 528 529 // chunk read successfully, next action 530 switch (sco_state){ 531 case H2_W4_SCO_HEADER: 532 sco_state = H2_W4_PAYLOAD; 533 sco_bytes_to_read = sco_buffer[2]; 534 break; 535 case H2_W4_PAYLOAD: 536 // packet complete 537 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos); 538 sco_state_machine_init(); 539 break; 540 default: 541 btstack_assert(false); 542 break; 543 } 544 } 545 } 546 #endif 547 548 static void handle_completed_transfer(struct libusb_transfer *transfer){ 549 550 int resubmit = 0; 551 assert(transfer->user_data != NULL ); 552 if (transfer->endpoint == event_in_addr) { 553 packet_handler(HCI_EVENT_PACKET, transfer->buffer, transfer->actual_length); 554 resubmit = 1; 555 } else if (transfer->endpoint == acl_in_addr) { 556 // log_info("-> acl"); 557 packet_handler(HCI_ACL_DATA_PACKET, transfer->buffer, transfer->actual_length); 558 resubmit = 1; 559 } else if (transfer->endpoint == 0){ 560 // log_info("command done, size %u", transfer->actual_length); 561 // printf("%s cmd release\n", __FUNCTION__ ); 562 usb_transfer_list_release( default_transfer_list, transfer ); 563 } else if (transfer->endpoint == acl_out_addr){ 564 // log_info("acl out done, size %u", transfer->actual_length); 565 // printf("%s acl release\n", __FUNCTION__ ); 566 usb_transfer_list_release( default_transfer_list, transfer ); 567 #ifdef ENABLE_SCO_OVER_HCI 568 } else if (transfer->endpoint == sco_in_addr) { 569 // log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS); 570 571 // give the transfer back to the pool, without resubmiting 572 if( !sco_activated ) { 573 usb_transfer_list_release( sco_transfer_list, transfer ); 574 return; 575 } 576 577 int i; 578 for (i = 0; i < transfer->num_iso_packets; i++) { 579 struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i]; 580 if (pack->status != LIBUSB_TRANSFER_COMPLETED) { 581 log_error("Error: pack %u status %d\n", i, pack->status); 582 continue; 583 } 584 if (!pack->actual_length) continue; 585 uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i); 586 handle_isochronous_data(data, pack->actual_length); 587 } 588 resubmit = 1; 589 } else if (transfer->endpoint == sco_out_addr){ 590 int i; 591 for (i = 0; i < transfer->num_iso_packets; i++) { 592 struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i]; 593 if (pack->status != LIBUSB_TRANSFER_COMPLETED) { 594 log_error("Error: pack %u status %d\n", i, pack->status); 595 } 596 } 597 usb_transfer_list_release( sco_transfer_list, transfer ); 598 if( !sco_activated ) { 599 return; 600 } 601 // log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}", 602 // transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status, 603 // transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status, 604 // transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status); 605 // notify upper layer if there's space for new SCO packets 606 607 if (!usb_transfer_list_empty(sco_transfer_list)) { 608 signal_sco_can_send_now(); 609 } 610 // log_info("H2: sco out complete, num active num active %u", sco_out_transfers_active); 611 #endif 612 } else { 613 log_info("usb_process_ds endpoint unknown %x", transfer->endpoint); 614 } 615 616 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return; 617 618 if (resubmit){ 619 // Re-submit transfer 620 int r = libusb_submit_transfer(transfer); 621 if (r) { 622 log_error("Error re-submitting transfer %d", r); 623 } 624 } 625 } 626 627 void usb_handle_pending_events(void); 628 void usb_handle_pending_events(void) { 629 struct timeval tv = { 0 }; 630 libusb_handle_events_timeout_completed(NULL, &tv, NULL); 631 } 632 633 static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) { 634 635 UNUSED(ds); 636 UNUSED(callback_type); 637 638 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return; 639 640 // log_info("begin usb_process_ds"); 641 // always handling an event as we're called when data is ready 642 usb_handle_pending_events(); 643 644 // Handle any packet in the order that they were received 645 while (!list_empty(&handle_packet_list)) { 646 // log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status); 647 648 // pop next transfer 649 usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)list_pop_front( &handle_packet_list ); 650 651 // handle transfer 652 handle_completed_transfer(current->t); 653 654 // handle case where libusb_close might be called by hci packet handler 655 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return; 656 } 657 // log_info("end usb_process_ds"); 658 } 659 660 static void usb_process_ts(btstack_timer_source_t *timer) { 661 662 UNUSED(timer); 663 664 // log_info("in usb_process_ts"); 665 666 // timer is deactive, when timer callback gets called 667 usb_timer_active = 0; 668 669 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return; 670 671 // actually handled the packet in the pollfds function 672 usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ); 673 674 // Get the amount of time until next event is due 675 long msec = ASYNC_POLLING_INTERVAL_MS; 676 677 // Activate timer 678 btstack_run_loop_set_timer(&usb_timer, msec); 679 btstack_run_loop_add_timer(&usb_timer); 680 usb_timer_active = 1; 681 682 return; 683 } 684 685 686 static int scan_for_bt_endpoints(libusb_device *dev) { 687 int r; 688 689 event_in_addr = 0; 690 acl_in_addr = 0; 691 acl_out_addr = 0; 692 sco_out_addr = 0; 693 sco_in_addr = 0; 694 695 // get endpoints from interface descriptor 696 struct libusb_config_descriptor *config_descriptor; 697 r = libusb_get_active_config_descriptor(dev, &config_descriptor); 698 if (r < 0) return r; 699 700 int num_interfaces = config_descriptor->bNumInterfaces; 701 log_info("active configuration has %u interfaces", num_interfaces); 702 703 int i; 704 for (i = 0; i < num_interfaces ; i++){ 705 const struct libusb_interface *interface = &config_descriptor->interface[i]; 706 const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting; 707 log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints); 708 709 const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint; 710 711 for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){ 712 log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes); 713 714 switch (endpoint->bmAttributes & 0x3){ 715 case LIBUSB_TRANSFER_TYPE_INTERRUPT: 716 if (event_in_addr) continue; 717 event_in_addr = endpoint->bEndpointAddress; 718 log_info("-> using 0x%2.2X for HCI Events", event_in_addr); 719 break; 720 case LIBUSB_TRANSFER_TYPE_BULK: 721 if (endpoint->bEndpointAddress & 0x80) { 722 if (acl_in_addr) continue; 723 acl_in_addr = endpoint->bEndpointAddress; 724 log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr); 725 } else { 726 if (acl_out_addr) continue; 727 acl_out_addr = endpoint->bEndpointAddress; 728 log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr); 729 } 730 break; 731 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: 732 if (endpoint->bEndpointAddress & 0x80) { 733 if (sco_in_addr) continue; 734 sco_in_addr = endpoint->bEndpointAddress; 735 log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr); 736 } else { 737 if (sco_out_addr) continue; 738 sco_out_addr = endpoint->bEndpointAddress; 739 log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr); 740 } 741 break; 742 default: 743 break; 744 } 745 } 746 } 747 libusb_free_config_descriptor(config_descriptor); 748 return 0; 749 } 750 751 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID 752 753 // list of known devices, using VendorID/ProductID tuples 754 static const uint16_t known_bluetooth_devices[] = { 755 // BCM20702A0 - DeLOCK Bluetooth 4.0 756 0x0a5c, 0x21e8, 757 // BCM20702A0 - Asus BT400 758 0x0b05, 0x17cb, 759 // BCM20702B0 - Generic USB Detuned Class 1 @ 20 MHz 760 0x0a5c, 0x22be, 761 // nRF5x Zephyr USB HCI, e.g nRF52840-PCA10056 762 0x2fe3, 0x0100, 763 0x2fe3, 0x000b, 764 }; 765 766 static int num_known_devices = sizeof(known_bluetooth_devices) / sizeof(uint16_t) / 2; 767 768 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){ 769 int i; 770 for (i=0; i<num_known_devices; i++){ 771 if (known_bluetooth_devices[i*2] == vendor_id && known_bluetooth_devices[i*2+1] == product_id){ 772 return 1; 773 } 774 } 775 btstack_linked_list_iterator_t it; 776 btstack_linked_list_iterator_init(&it, &usb_knwon_devices); 777 while (btstack_linked_list_iterator_has_next(&it)) { 778 usb_known_device_t * device = (usb_known_device_t *) btstack_linked_list_iterator_next(&it); 779 if (device->vendor_id != vendor_id) continue; 780 if (device->product_id != product_id) continue; 781 return 1; 782 } 783 return 0; 784 } 785 786 // returns index of found device or -1 787 static int scan_for_bt_device(libusb_device **devs, int start_index) { 788 int i; 789 for (i = start_index; devs[i] ; i++){ 790 libusb_device * dev = devs[i]; 791 int r = libusb_get_device_descriptor(dev, &desc); 792 if (r < 0) { 793 log_error("failed to get device descriptor"); 794 return 0; 795 } 796 797 log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ", 798 desc.idVendor, desc.idProduct, 799 libusb_get_bus_number(dev), libusb_get_device_address(dev), 800 desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol); 801 802 // Detect USB Dongle based Class, Subclass, and Protocol 803 // The class code (bDeviceClass) is 0xE0 – Wireless Controller. 804 // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller. 805 // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming. 806 if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) { 807 return i; 808 } 809 810 // Detect USB Dongle based on whitelist 811 if (is_known_bt_device(desc.idVendor, desc.idProduct)) { 812 return i; 813 } 814 } 815 return -1; 816 } 817 #endif 818 819 static int prepare_device(libusb_device_handle * aHandle){ 820 821 // get device path 822 libusb_device * device = libusb_get_device(aHandle); 823 usb_path_len = libusb_get_port_numbers(device, usb_path, USB_MAX_PATH_LEN); 824 825 int r; 826 int kernel_driver_detached = 0; 827 828 // Detach OS driver (not possible for OS X, FreeBSD, and Windows) 829 #if !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) && !defined(__FreeBSD__) 830 r = libusb_kernel_driver_active(aHandle, 0); 831 if (r < 0) { 832 log_error("libusb_kernel_driver_active error %d", r); 833 libusb_close(aHandle); 834 return r; 835 } 836 837 if (r == 1) { 838 r = libusb_detach_kernel_driver(aHandle, 0); 839 if (r < 0) { 840 log_error("libusb_detach_kernel_driver error %d", r); 841 libusb_close(aHandle); 842 return r; 843 } 844 kernel_driver_detached = 1; 845 } 846 log_info("libusb_detach_kernel_driver"); 847 #endif 848 849 const int configuration = 1; 850 log_info("setting configuration %d...", configuration); 851 r = libusb_set_configuration(aHandle, configuration); 852 if (r < 0) { 853 log_error("Error libusb_set_configuration: %d", r); 854 if (kernel_driver_detached){ 855 libusb_attach_kernel_driver(aHandle, 0); 856 } 857 libusb_close(aHandle); 858 return r; 859 } 860 861 // reserve access to device 862 log_info("claiming interface 0..."); 863 r = libusb_claim_interface(aHandle, 0); 864 if (r < 0) { 865 log_error("Error %d claiming interface 0", r); 866 if (kernel_driver_detached){ 867 libusb_attach_kernel_driver(aHandle, 0); 868 } 869 libusb_close(aHandle); 870 return r; 871 } 872 873 #ifdef ENABLE_SCO_OVER_HCI 874 // get endpoints from interface descriptor 875 struct libusb_config_descriptor *config_descriptor; 876 r = libusb_get_active_config_descriptor(device, &config_descriptor); 877 if (r >= 0){ 878 int num_interfaces = config_descriptor->bNumInterfaces; 879 if (num_interfaces > 1) { 880 r = libusb_claim_interface(aHandle, 1); 881 if (r < 0) { 882 log_error("Error %d claiming interface 1: - disabling SCO over HCI", r); 883 } else { 884 sco_enabled = 1; 885 } 886 } else { 887 log_info("Device has only on interface, disabling SCO over HCI"); 888 } 889 } 890 #endif 891 892 return 0; 893 } 894 895 static libusb_device_handle * try_open_device(libusb_device * device){ 896 int r; 897 898 r = libusb_get_device_descriptor(device, &desc); 899 if (r < 0) { 900 log_error("libusb_get_device_descriptor failed!"); 901 return NULL; 902 } 903 usb_vendor_id = desc.idVendor; 904 usb_product_id = desc.idProduct; 905 906 libusb_device_handle * dev_handle; 907 r = libusb_open(device, &dev_handle); 908 909 if (r < 0) { 910 log_error("libusb_open failed!"); 911 dev_handle = NULL; 912 return NULL; 913 } 914 915 log_info("libusb open %d, handle %p", r, dev_handle); 916 917 // reset device (Not currently possible under FreeBSD 11.x/12.x due to usb framework) 918 #if !defined(__FreeBSD__) 919 r = libusb_reset_device(dev_handle); 920 if (r < 0) { 921 log_error("libusb_reset_device failed!"); 922 libusb_close(dev_handle); 923 return NULL; 924 } 925 #endif 926 return dev_handle; 927 } 928 929 #ifdef ENABLE_SCO_OVER_HCI 930 static int usb_sco_start(void){ 931 932 log_info("usb_sco_start"); 933 if( sco_activated ) { 934 log_error("double sco start!"); 935 return -1; 936 } 937 sco_activated = true; 938 939 sco_state_machine_init(); 940 941 int alt_setting; 942 if (sco_voice_setting & 0x0020){ 943 // 16-bit PCM 944 alt_setting = alt_setting_16_bit[sco_num_connections-1]; 945 } else { 946 // 8-bit PCM or mSBC 947 alt_setting = alt_setting_8_bit[sco_num_connections-1]; 948 } 949 // derive iso packet size from alt setting 950 iso_packet_size = iso_packet_size_for_alt_setting[alt_setting]; 951 952 log_info("Switching to setting %u on interface 1..", alt_setting); 953 int r = libusb_set_interface_alt_setting(handle, 1, alt_setting); 954 if (r < 0) { 955 log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r)); 956 return r; 957 } 958 959 #ifdef DEBUG 960 int in_flight = usb_transfer_list_in_flight( sco_transfer_list ); 961 // there need to be at least SCO_IN_BUFFER_COUNT packets available to 962 // fill them in below 963 assert( in_flight <= SCO_OUT_BUFFER_COUNT ); 964 #endif 965 966 // incoming 967 int c; 968 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) { 969 970 struct libusb_transfer *transfer = usb_transfer_list_acquire( sco_transfer_list ); 971 uint8_t *data = transfer->buffer; 972 void *user_data = transfer->user_data; 973 974 // configure sco_in handlers 975 libusb_fill_iso_transfer(transfer, handle, sco_in_addr, 976 data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, user_data, 0); 977 libusb_set_iso_packet_lengths(transfer, iso_packet_size); 978 r = libusb_submit_transfer(transfer); 979 if (r) { 980 log_error("Error submitting isochronous in transfer %d", r); 981 usb_close(); 982 return r; 983 } 984 } 985 return 0; 986 } 987 988 static void usb_sco_stop(void){ 989 990 log_info("usb_sco_stop"); 991 sco_activated = false; 992 993 usb_transfer_list_cancel( sco_transfer_list ); 994 995 log_info("Switching to setting %u on interface 1..", 0); 996 int r = libusb_set_interface_alt_setting(handle, 1, 0); 997 if (r < 0) { 998 log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r)); 999 return; 1000 } 1001 1002 log_info("usb_sco_stop done"); 1003 } 1004 #endif 1005 1006 void pollfd_added_cb(int fd, short events, void *user_data); 1007 void pollfd_remove_cb(int fd, void *user_data); 1008 1009 void pollfd_added_cb(int fd, short events, void *user_data) { 1010 UNUSED(events); 1011 UNUSED(user_data); 1012 log_error("add fd: %d", fd); 1013 assert(0); 1014 } 1015 1016 void pollfd_remove_cb(int fd, void *user_data) { 1017 UNUSED(user_data); 1018 log_error("remove fd: %d", fd); 1019 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() { 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() { 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 assert( transfer->user_data != NULL ); 1394 r = libusb_submit_transfer(transfer); 1395 1396 if (r < 0) { 1397 log_error("Error submitting cmd transfer %d", r); 1398 return -1; 1399 } 1400 1401 signal_acknowledge(); 1402 1403 return 0; 1404 } 1405 1406 static int usb_send_acl_packet(uint8_t *packet, int size){ 1407 int r; 1408 1409 if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1; 1410 // printf("%s( %p, %d )\n", __FUNCTION__, packet, size ); 1411 // log_info("usb_send_acl_packet enter, size %u", size); 1412 1413 struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list ); 1414 uint8_t *data = transfer->buffer; 1415 1416 // prepare transfer 1417 memcpy( data, packet, size ); 1418 libusb_fill_bulk_transfer(transfer, handle, acl_out_addr, data, size, 1419 async_callback, transfer->user_data, 0); 1420 1421 assert( transfer->user_data != NULL ); 1422 r = libusb_submit_transfer(transfer); 1423 1424 if (r < 0) { 1425 log_error("Error submitting acl transfer, %d", r); 1426 return -1; 1427 } 1428 1429 signal_acknowledge(); 1430 1431 return 0; 1432 } 1433 1434 static int usb_can_send_packet_now(uint8_t packet_type){ 1435 switch (packet_type){ 1436 case HCI_COMMAND_DATA_PACKET: { 1437 int ret = !usb_transfer_list_empty( default_transfer_list ); 1438 if( !ret ) { 1439 log_error("command transfers shouldn't be empty!"); 1440 } 1441 return ret; 1442 } 1443 case HCI_ACL_DATA_PACKET: { 1444 int ret = !usb_transfer_list_empty( default_transfer_list ); 1445 if( !ret ) { 1446 log_error("acl transfers shouldn't be empty!"); 1447 } 1448 return ret; 1449 } 1450 1451 #ifdef ENABLE_SCO_OVER_HCI 1452 case HCI_SCO_DATA_PACKET: { 1453 if (!sco_enabled || !sco_activated) return 0; 1454 int ret = !usb_transfer_list_empty( sco_transfer_list ); 1455 if( !ret ) { 1456 log_error("sco transfers shouldn't be empty!"); 1457 } 1458 return ret; 1459 } 1460 #endif 1461 default: 1462 return 0; 1463 } 1464 } 1465 1466 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){ 1467 switch (packet_type){ 1468 case HCI_COMMAND_DATA_PACKET: 1469 return usb_send_cmd_packet(packet, size); 1470 case HCI_ACL_DATA_PACKET: 1471 return usb_send_acl_packet(packet, size); 1472 #ifdef ENABLE_SCO_OVER_HCI 1473 case HCI_SCO_DATA_PACKET: 1474 if (!sco_enabled) return -1; 1475 return usb_send_sco_packet(packet, size); 1476 #endif 1477 default: 1478 return -1; 1479 } 1480 } 1481 1482 #ifdef ENABLE_SCO_OVER_HCI 1483 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){ 1484 if (!sco_enabled) return; 1485 1486 log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections); 1487 1488 if (num_connections != sco_num_connections){ 1489 sco_voice_setting = voice_setting; 1490 if (sco_num_connections){ 1491 usb_sco_stop(); 1492 } 1493 sco_num_connections = num_connections; 1494 if (num_connections){ 1495 usb_sco_start(); 1496 } 1497 } 1498 } 1499 #endif 1500 1501 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 1502 log_info("registering packet handler"); 1503 packet_handler = handler; 1504 } 1505 1506 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 1507 UNUSED(packet_type); 1508 UNUSED(packet); 1509 UNUSED(size); 1510 } 1511 1512 // get usb singleton 1513 const hci_transport_t * hci_transport_usb_instance(void) { 1514 if (!hci_transport_usb) { 1515 hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t)); 1516 memset(hci_transport_usb, 0, sizeof(hci_transport_t)); 1517 hci_transport_usb->name = "H2_LIBUSB"; 1518 hci_transport_usb->open = usb_open; 1519 hci_transport_usb->close = usb_close; 1520 hci_transport_usb->register_packet_handler = usb_register_packet_handler; 1521 hci_transport_usb->can_send_packet_now = usb_can_send_packet_now; 1522 hci_transport_usb->send_packet = usb_send_packet; 1523 #ifdef ENABLE_SCO_OVER_HCI 1524 hci_transport_usb->set_sco_config = usb_set_sco_config; 1525 #endif 1526 } 1527 return hci_transport_usb; 1528 } 1529