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