xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision d40c3de009bce6994e726da5a427e08951b353d9)
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 MATTHIAS
24  * RINGWALD 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 <stdio.h>
57 #include <strings.h>
58 #include <string.h>
59 #include <unistd.h>   /* UNIX standard function definitions */
60 #include <sys/types.h>
61 
62 #include <libusb.h>
63 
64 #include "btstack_config.h"
65 
66 #include "btstack_debug.h"
67 #include "hci.h"
68 #include "hci_transport.h"
69 
70 #if (USB_VENDOR_ID != 0) && (USB_PRODUCT_ID != 0)
71 #define HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
72 #endif
73 
74 #define ACL_IN_BUFFER_COUNT    3
75 #define EVENT_IN_BUFFER_COUNT  3
76 #define SCO_IN_BUFFER_COUNT   10
77 
78 #define ASYNC_POLLING_INTERVAL_MS 1
79 
80 //
81 // Bluetooth USB Transport Alternate Settings:
82 //
83 // 0: No active voice channels (for USB compliance)
84 // 1: One 8 kHz voice channel with 8-bit encoding
85 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
86 // 3: Three 8 kHz voice channels with 8-bit encoding
87 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
88 // 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
89 // --> support only a single SCO connection
90 // #define ALT_SETTING (1)
91 
92 #ifdef ENABLE_SCO_OVER_HCI
93 // alt setting for 1-3 connections and 8/16 bit
94 static const int alt_setting_8_bit[]  = {1,2,3};
95 static const int alt_setting_16_bit[] = {2,4,5};
96 
97 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
98 // One complete SCO packet with 24 frames every 3 frames (== 3 ms)
99 #define NUM_ISO_PACKETS (3)
100 
101 static const uint16_t iso_packet_size_for_alt_setting[] = {
102     0,
103     9,
104     17,
105     25,
106     33,
107     49,
108     63,
109 };
110 #endif
111 
112 // 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)
113 // 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
114 #define SCO_PACKET_SIZE  (49 * NUM_ISO_PACKETS)
115 
116 // Outgoing SCO packet queue
117 // simplified ring buffer implementation
118 #define SCO_OUT_BUFFER_COUNT  (8)
119 #define SCO_OUT_BUFFER_SIZE (SCO_OUT_BUFFER_COUNT * SCO_PACKET_SIZE)
120 
121 // seems to be the max depth for USB 3
122 #define USB_MAX_PATH_LEN 7
123 
124 // prototypes
125 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
126 static int usb_close(void);
127 
128 typedef enum {
129     LIB_USB_CLOSED = 0,
130     LIB_USB_OPENED,
131     LIB_USB_DEVICE_OPENDED,
132     LIB_USB_INTERFACE_CLAIMED,
133     LIB_USB_TRANSFERS_ALLOCATED
134 } libusb_state_t;
135 
136 // SCO packet state machine
137 typedef enum {
138     H2_W4_SCO_HEADER = 1,
139     H2_W4_PAYLOAD,
140 } H2_SCO_STATE;
141 
142 static libusb_state_t libusb_state = LIB_USB_CLOSED;
143 
144 // single instance
145 static hci_transport_t * hci_transport_usb = NULL;
146 
147 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = dummy_handler;
148 
149 // libusb
150 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
151 static struct libusb_device_descriptor desc;
152 static libusb_device        * dev;
153 #endif
154 static libusb_device_handle * handle;
155 
156 static struct libusb_transfer *command_out_transfer;
157 static struct libusb_transfer *acl_out_transfer;
158 static struct libusb_transfer *event_in_transfer[EVENT_IN_BUFFER_COUNT];
159 static struct libusb_transfer *acl_in_transfer[ACL_IN_BUFFER_COUNT];
160 
161 #ifdef ENABLE_SCO_OVER_HCI
162 
163 #ifdef _WIN32
164 #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"
165 #endif
166 
167 // incoming SCO
168 static H2_SCO_STATE sco_state;
169 static uint8_t  sco_buffer[255+3 + SCO_PACKET_SIZE];
170 static uint16_t sco_read_pos;
171 static uint16_t sco_bytes_to_read;
172 static struct  libusb_transfer *sco_in_transfer[SCO_IN_BUFFER_COUNT];
173 static uint8_t hci_sco_in_buffer[SCO_IN_BUFFER_COUNT][SCO_PACKET_SIZE];
174 
175 // outgoing SCO
176 static uint8_t  sco_out_ring_buffer[SCO_OUT_BUFFER_SIZE];
177 static int      sco_ring_write;  // packet idx
178 static int      sco_out_transfers_active;
179 static struct libusb_transfer *sco_out_transfers[SCO_OUT_BUFFER_COUNT];
180 static int      sco_out_transfers_in_flight[SCO_OUT_BUFFER_COUNT];
181 
182 // pause/resume
183 static uint16_t sco_voice_setting;
184 static int      sco_num_connections;
185 static int      sco_shutdown;
186 
187 // dynamic SCO configuration
188 static uint16_t iso_packet_size;
189 
190 #endif
191 
192 // outgoing buffer for HCI Command packets
193 static uint8_t hci_cmd_buffer[3 + 256 + LIBUSB_CONTROL_SETUP_SIZE];
194 
195 // incoming buffer for HCI Events and ACL Packets
196 static uint8_t hci_event_in_buffer[EVENT_IN_BUFFER_COUNT][HCI_ACL_BUFFER_SIZE]; // bigger than largest packet
197 static uint8_t hci_acl_in_buffer[ACL_IN_BUFFER_COUNT][HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
198 
199 // For (ab)use as a linked list of received packets
200 static struct libusb_transfer *handle_packet;
201 
202 static int doing_pollfds;
203 static int num_pollfds;
204 static btstack_data_source_t * pollfd_data_sources;
205 static btstack_timer_source_t usb_timer;
206 static int usb_timer_active;
207 
208 static int usb_acl_out_active = 0;
209 static int usb_command_active = 0;
210 
211 // endpoint addresses
212 static int event_in_addr;
213 static int acl_in_addr;
214 static int acl_out_addr;
215 static int sco_in_addr;
216 static int sco_out_addr;
217 
218 // device path
219 static int usb_path_len;
220 static uint8_t usb_path[USB_MAX_PATH_LEN];
221 
222 
223 #ifdef ENABLE_SCO_OVER_HCI
224 static void sco_ring_init(void){
225     sco_ring_write = 0;
226     sco_out_transfers_active = 0;
227 }
228 static int sco_ring_have_space(void){
229     return sco_out_transfers_active < SCO_OUT_BUFFER_COUNT;
230 }
231 #endif
232 
233 void hci_transport_usb_set_path(int len, uint8_t * port_numbers){
234     if (len > USB_MAX_PATH_LEN || !port_numbers){
235         log_error("hci_transport_usb_set_path: len or port numbers invalid");
236         return;
237     }
238     usb_path_len = len;
239     memcpy(usb_path, port_numbers, len);
240 }
241 
242 //
243 static void queue_transfer(struct libusb_transfer *transfer){
244 
245     // log_info("queue_transfer %p, endpoint %x size %u", transfer, transfer->endpoint, transfer->actual_length);
246 
247     transfer->user_data = NULL;
248 
249     // insert first element
250     if (handle_packet == NULL) {
251         handle_packet = transfer;
252         return;
253     }
254 
255     // Walk to end of list and add current packet there
256     struct libusb_transfer *temp = handle_packet;
257     while (temp->user_data) {
258         temp = (struct libusb_transfer*)temp->user_data;
259     }
260     temp->user_data = transfer;
261 }
262 
263 LIBUSB_CALL static void async_callback(struct libusb_transfer *transfer){
264 
265     int c;
266 
267     // identify and free transfers as part of shutdown
268 #ifdef ENABLE_SCO_OVER_HCI
269     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED || sco_shutdown) {
270         for (c=0;c<SCO_IN_BUFFER_COUNT;c++){
271             if (transfer == sco_in_transfer[c]){
272                 libusb_free_transfer(transfer);
273                 sco_in_transfer[c] = 0;
274                 return;
275             }
276         }
277 
278         for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
279             if (transfer == sco_out_transfers[c]){
280                 sco_out_transfers_in_flight[c] = 0;
281                 libusb_free_transfer(transfer);
282                 sco_out_transfers[c] = 0;
283                 return;
284             }
285         }
286     }
287 #endif
288 
289     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) {
290         for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
291             if (transfer == event_in_transfer[c]){
292                 libusb_free_transfer(transfer);
293                 event_in_transfer[c] = 0;
294                 return;
295             }
296         }
297         for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
298             if (transfer == acl_in_transfer[c]){
299                 libusb_free_transfer(transfer);
300                 acl_in_transfer[c] = 0;
301                 return;
302             }
303         }
304         return;
305     }
306 
307 #ifdef ENABLE_SCO_OVER_HCI
308     // mark SCO OUT transfer as done
309     for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
310         if (transfer == sco_out_transfers[c]){
311             sco_out_transfers_in_flight[c] = 0;
312         }
313     }
314 #endif
315 
316     int r;
317     // log_info("begin async_callback endpoint %x, status %x, actual length %u", transfer->endpoint, transfer->status, transfer->actual_length );
318 
319     if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
320         queue_transfer(transfer);
321     } else if (transfer->status == LIBUSB_TRANSFER_STALL){
322         log_info("-> Transfer stalled, trying again");
323         r = libusb_clear_halt(handle, transfer->endpoint);
324         if (r) {
325             log_error("Error rclearing halt %d", r);
326         }
327         r = libusb_submit_transfer(transfer);
328         if (r) {
329             log_error("Error re-submitting transfer %d", r);
330         }
331     } else {
332         log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length);
333         // No usable data, just resubmit packet
334         r = libusb_submit_transfer(transfer);
335         if (r) {
336             log_error("Error re-submitting transfer %d", r);
337         }
338     }
339     // log_info("end async_callback");
340 }
341 
342 
343 #ifdef ENABLE_SCO_OVER_HCI
344 static int usb_send_sco_packet(uint8_t *packet, int size){
345     int r;
346 
347     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
348 
349     // log_info("usb_send_acl_packet enter, size %u", size);
350 
351     // store packet in free slot
352     int tranfer_index = sco_ring_write;
353     uint8_t * data = &sco_out_ring_buffer[tranfer_index * SCO_PACKET_SIZE];
354     memcpy(data, packet, size);
355 
356     // setup transfer
357     // 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);
358     struct libusb_transfer * sco_transfer = sco_out_transfers[tranfer_index];
359     libusb_fill_iso_transfer(sco_transfer, handle, sco_out_addr, data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
360     libusb_set_iso_packet_lengths(sco_transfer, iso_packet_size);
361     r = libusb_submit_transfer(sco_transfer);
362     if (r < 0) {
363         log_error("Error submitting sco transfer, %d", r);
364         return -1;
365     }
366 
367     // mark slot as full
368     sco_ring_write++;
369     if (sco_ring_write == SCO_OUT_BUFFER_COUNT){
370         sco_ring_write = 0;
371     }
372     sco_out_transfers_active++;
373     sco_out_transfers_in_flight[tranfer_index] = 1;
374 
375     // log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_out_transfers_active);
376 
377     // notify upper stack that provided buffer can be used again
378     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
379     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
380 
381     // and if we have more space for SCO packets
382     if (sco_ring_have_space()) {
383         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
384         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
385     }
386     return 0;
387 }
388 
389 static void sco_state_machine_init(void){
390     sco_state = H2_W4_SCO_HEADER;
391     sco_read_pos = 0;
392     sco_bytes_to_read = 3;
393 }
394 
395 static void handle_isochronous_data(uint8_t * buffer, uint16_t size){
396     while (size){
397         if (size < sco_bytes_to_read){
398             // just store incomplete data
399             memcpy(&sco_buffer[sco_read_pos], buffer, size);
400             sco_read_pos      += size;
401             sco_bytes_to_read -= size;
402             return;
403         }
404         // copy requested data
405         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
406         sco_read_pos += sco_bytes_to_read;
407         buffer       += sco_bytes_to_read;
408         size         -= sco_bytes_to_read;
409 
410         // chunk read successfully, next action
411         switch (sco_state){
412             case H2_W4_SCO_HEADER:
413                 sco_state = H2_W4_PAYLOAD;
414                 sco_bytes_to_read = sco_buffer[2];
415                 break;
416             case H2_W4_PAYLOAD:
417                 // packet complete
418                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
419                 sco_state_machine_init();
420                 break;
421         }
422     }
423 }
424 #endif
425 
426 static void handle_completed_transfer(struct libusb_transfer *transfer){
427 
428     int resubmit = 0;
429     int signal_done = 0;
430 
431     if (transfer->endpoint == event_in_addr) {
432         packet_handler(HCI_EVENT_PACKET, transfer-> buffer, transfer->actual_length);
433         resubmit = 1;
434     } else if (transfer->endpoint == acl_in_addr) {
435         // log_info("-> acl");
436         packet_handler(HCI_ACL_DATA_PACKET, transfer-> buffer, transfer->actual_length);
437         resubmit = 1;
438     } else if (transfer->endpoint == 0){
439         // log_info("command done, size %u", transfer->actual_length);
440         usb_command_active = 0;
441         signal_done = 1;
442     } else if (transfer->endpoint == acl_out_addr){
443         // log_info("acl out done, size %u", transfer->actual_length);
444         usb_acl_out_active = 0;
445         signal_done = 1;
446 #ifdef ENABLE_SCO_OVER_HCI
447     } else if (transfer->endpoint == sco_in_addr) {
448         // log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS);
449         int i;
450         for (i = 0; i < transfer->num_iso_packets; i++) {
451             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
452             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
453                 log_error("Error: pack %u status %d\n", i, pack->status);
454                 continue;
455             }
456             if (!pack->actual_length) continue;
457             uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i);
458             // printf_hexdump(data, pack->actual_length);
459             // log_info("handle_isochronous_data,size %u/%u", pack->length, pack->actual_length);
460             handle_isochronous_data(data, pack->actual_length);
461         }
462         resubmit = 1;
463     } else if (transfer->endpoint == sco_out_addr){
464         int i;
465         for (i = 0; i < transfer->num_iso_packets; i++) {
466             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
467             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
468                 log_error("Error: pack %u status %d\n", i, pack->status);
469             }
470         }
471         // log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}",
472         //     transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status,
473         //     transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status,
474         //     transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status);
475         // notify upper layer if there's space for new SCO packets
476 
477         if (sco_ring_have_space()) {
478             uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
479             packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
480         }
481         // decrease tab
482         sco_out_transfers_active--;
483         // log_info("H2: sco out complete, num active num active %u", sco_out_transfers_active);
484 #endif
485     } else {
486         log_info("usb_process_ds endpoint unknown %x", transfer->endpoint);
487     }
488 
489     if (signal_done){
490         // notify upper stack that provided buffer can be used again
491         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
492         packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
493     }
494 
495     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
496 
497     if (resubmit){
498         // Re-submit transfer
499         transfer->user_data = NULL;
500         int r = libusb_submit_transfer(transfer);
501         if (r) {
502             log_error("Error re-submitting transfer %d", r);
503         }
504     }
505 }
506 
507 static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
508 
509     UNUSED(ds);
510     UNUSED(callback_type);
511 
512     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
513 
514     // log_info("begin usb_process_ds");
515     // always handling an event as we're called when data is ready
516     struct timeval tv;
517     memset(&tv, 0, sizeof(struct timeval));
518     libusb_handle_events_timeout(NULL, &tv);
519 
520     // Handle any packet in the order that they were received
521     while (handle_packet) {
522         // log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status);
523         void * next = handle_packet->user_data;
524         handle_completed_transfer(handle_packet);
525         // handle case where libusb_close might be called by hci packet handler
526         if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
527 
528         // Move to next in the list of packets to handle
529         if (next) {
530             handle_packet = (struct libusb_transfer*)next;
531         } else {
532             handle_packet = NULL;
533         }
534     }
535     // log_info("end usb_process_ds");
536 }
537 
538 static void usb_process_ts(btstack_timer_source_t *timer) {
539 
540     UNUSED(timer);
541 
542     // log_info("in usb_process_ts");
543 
544     // timer is deactive, when timer callback gets called
545     usb_timer_active = 0;
546 
547     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
548 
549     // actually handled the packet in the pollfds function
550     usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ);
551 
552     // Get the amount of time until next event is due
553     long msec = ASYNC_POLLING_INTERVAL_MS;
554 
555     // Activate timer
556     btstack_run_loop_set_timer(&usb_timer, msec);
557     btstack_run_loop_add_timer(&usb_timer);
558     usb_timer_active = 1;
559 
560     return;
561 }
562 
563 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
564 
565 // list of known devices, using VendorID/ProductID tuples
566 static const uint16_t known_bt_devices[] = {
567     // DeLOCK Bluetooth 4.0
568     0x0a5c, 0x21e8,
569     // Asus BT400
570     0x0b05, 0x17cb,
571 };
572 
573 static int num_known_devices = sizeof(known_bt_devices) / sizeof(uint16_t) / 2;
574 
575 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
576     int i;
577     for (i=0; i<num_known_devices; i++){
578         if (known_bt_devices[i*2] == vendor_id && known_bt_devices[i*2+1] == product_id){
579             return 1;
580         }
581     }
582     return 0;
583 }
584 
585 static void scan_for_bt_endpoints(void) {
586     int r;
587 
588     event_in_addr = 0;
589     acl_in_addr = 0;
590     acl_out_addr = 0;
591     sco_out_addr = 0;
592     sco_in_addr = 0;
593 
594     // get endpoints from interface descriptor
595     struct libusb_config_descriptor *config_descriptor;
596     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
597 
598     int num_interfaces = config_descriptor->bNumInterfaces;
599     log_info("active configuration has %u interfaces", num_interfaces);
600 
601     int i;
602     for (i = 0; i < num_interfaces ; i++){
603         const struct libusb_interface *interface = &config_descriptor->interface[i];
604         const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
605         log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
606 
607         const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
608 
609         for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
610             log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
611 
612             switch (endpoint->bmAttributes & 0x3){
613                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
614                     if (event_in_addr) continue;
615                     event_in_addr = endpoint->bEndpointAddress;
616                     log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
617                     break;
618                 case LIBUSB_TRANSFER_TYPE_BULK:
619                     if (endpoint->bEndpointAddress & 0x80) {
620                         if (acl_in_addr) continue;
621                         acl_in_addr = endpoint->bEndpointAddress;
622                         log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
623                     } else {
624                         if (acl_out_addr) continue;
625                         acl_out_addr = endpoint->bEndpointAddress;
626                         log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
627                     }
628                     break;
629                 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
630                     if (endpoint->bEndpointAddress & 0x80) {
631                         if (sco_in_addr) continue;
632                         sco_in_addr = endpoint->bEndpointAddress;
633                         log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
634                     } else {
635                         if (sco_out_addr) continue;
636                         sco_out_addr = endpoint->bEndpointAddress;
637                         log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
638                     }
639                     break;
640                 default:
641                     break;
642             }
643         }
644     }
645     libusb_free_config_descriptor(config_descriptor);
646 }
647 
648 // returns index of found device or -1
649 static int scan_for_bt_device(libusb_device **devs, int start_index) {
650     int i;
651     for (i = start_index; devs[i] ; i++){
652         dev = devs[i];
653         int r = libusb_get_device_descriptor(dev, &desc);
654         if (r < 0) {
655             log_error("failed to get device descriptor");
656             return 0;
657         }
658 
659         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
660                desc.idVendor, desc.idProduct,
661                libusb_get_bus_number(dev), libusb_get_device_address(dev),
662                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
663 
664         // Detect USB Dongle based Class, Subclass, and Protocol
665         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
666         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
667         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
668         // if (desc.bDeviceClass == 0xe0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01){
669         if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
670             return i;
671         }
672 
673         // Detect USB Dongle based on whitelist
674         if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
675             return i;
676         }
677     }
678     return -1;
679 }
680 #endif
681 
682 static int prepare_device(libusb_device_handle * aHandle){
683 
684     // print device path
685     uint8_t port_numbers[USB_MAX_PATH_LEN];
686     libusb_device * device = libusb_get_device(aHandle);
687     int path_len = libusb_get_port_numbers(device, port_numbers, USB_MAX_PATH_LEN);
688     printf("USB Path: ");
689     int i;
690     for (i=0;i<path_len;i++){
691         if (i) printf("-");
692         printf("%02x", port_numbers[i]);
693     }
694     printf("\n");
695 
696     int r;
697     int kernel_driver_detached = 0;
698 
699     // Detach OS driver (not possible for OS X and WIN32)
700 #if !defined(__APPLE__) && !defined(_WIN32)
701     r = libusb_kernel_driver_active(aHandle, 0);
702     if (r < 0) {
703         log_error("libusb_kernel_driver_active error %d", r);
704         libusb_close(aHandle);
705         return r;
706     }
707 
708     if (r == 1) {
709         r = libusb_detach_kernel_driver(aHandle, 0);
710         if (r < 0) {
711             log_error("libusb_detach_kernel_driver error %d", r);
712             libusb_close(aHandle);
713             return r;
714         }
715         kernel_driver_detached = 1;
716     }
717     log_info("libusb_detach_kernel_driver");
718 #endif
719 
720     const int configuration = 1;
721     log_info("setting configuration %d...", configuration);
722     r = libusb_set_configuration(aHandle, configuration);
723     if (r < 0) {
724         log_error("Error libusb_set_configuration: %d", r);
725         if (kernel_driver_detached){
726             libusb_attach_kernel_driver(aHandle, 0);
727         }
728         libusb_close(aHandle);
729         return r;
730     }
731 
732     // reserve access to device
733     log_info("claiming interface 0...");
734     r = libusb_claim_interface(aHandle, 0);
735     if (r < 0) {
736         log_error("Error claiming interface %d", r);
737         if (kernel_driver_detached){
738             libusb_attach_kernel_driver(aHandle, 0);
739         }
740         libusb_close(aHandle);
741         return r;
742     }
743 
744 #ifdef ENABLE_SCO_OVER_HCI
745     log_info("claiming interface 1...");
746     r = libusb_claim_interface(aHandle, 1);
747     if (r < 0) {
748         log_error("Error claiming interface %d", r);
749         if (kernel_driver_detached){
750             libusb_attach_kernel_driver(aHandle, 0);
751         }
752         libusb_close(aHandle);
753         return r;
754     }
755 #endif
756 
757     return 0;
758 }
759 
760 static libusb_device_handle * try_open_device(libusb_device * device){
761     int r;
762 
763     libusb_device_handle * dev_handle;
764     r = libusb_open(device, &dev_handle);
765 
766     if (r < 0) {
767         log_error("libusb_open failed!");
768         dev_handle = NULL;
769         return NULL;
770     }
771 
772     log_info("libusb open %d, handle %p", r, dev_handle);
773 
774     // reset device
775     libusb_reset_device(dev_handle);
776     if (r < 0) {
777         log_error("libusb_reset_device failed!");
778         libusb_close(dev_handle);
779         return NULL;
780     }
781     return dev_handle;
782 }
783 
784 #ifdef ENABLE_SCO_OVER_HCI
785 
786 static int usb_sco_start(void){
787 
788     printf("usb_sco_start\n");
789     log_info("usb_sco_start");
790 
791     sco_state_machine_init();
792     sco_ring_init();
793 
794     int alt_setting;
795     if (sco_voice_setting & 0x0020){
796         // 16-bit PCM
797         alt_setting = alt_setting_16_bit[sco_num_connections-1];
798     } else {
799         // 8-bit PCM or mSBC
800         alt_setting = alt_setting_8_bit[sco_num_connections-1];
801     }
802     // derive iso packet size from alt setting
803     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
804 
805     log_info("Switching to setting %u on interface 1..", alt_setting);
806     int r = libusb_set_interface_alt_setting(handle, 1, alt_setting);
807     if (r < 0) {
808         log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r));
809         return r;
810     }
811 
812     // incoming
813     int c;
814     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
815         sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in
816         if (!sco_in_transfer[c]) {
817             usb_close();
818             return LIBUSB_ERROR_NO_MEM;
819         }
820         // configure sco_in handlers
821         libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr,
822             hci_sco_in_buffer[c], NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
823         libusb_set_iso_packet_lengths(sco_in_transfer[c], iso_packet_size);
824         r = libusb_submit_transfer(sco_in_transfer[c]);
825         if (r) {
826             log_error("Error submitting isochronous in transfer %d", r);
827             usb_close();
828             return r;
829         }
830     }
831 
832     // outgoing
833     for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
834         sco_out_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts
835         sco_out_transfers_in_flight[c] = 0;
836     }
837     return 0;
838 }
839 
840 static void usb_sco_stop(void){
841 
842     printf("usb_sco_stop\n");
843 
844     log_info("usb_sco_stop");
845     sco_shutdown = 1;
846 
847     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
848 
849     int c;
850     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
851         libusb_cancel_transfer(sco_in_transfer[c]);
852     }
853 
854     for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
855         if (sco_out_transfers_in_flight[c]) {
856             libusb_cancel_transfer(sco_out_transfers[c]);
857         } else {
858             libusb_free_transfer(sco_out_transfers[c]);
859             sco_out_transfers[c] = 0;
860         }
861     }
862 
863     // wait until all transfers are completed
864     int completed = 0;
865     while (!completed){
866         struct timeval tv;
867         memset(&tv, 0, sizeof(struct timeval));
868         libusb_handle_events_timeout(NULL, &tv);
869         // check if all done
870         completed = 1;
871 
872         // Cancel all synchronous transfer
873         for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
874             if (sco_in_transfer[c]){
875                 completed = 0;
876                 break;
877             }
878         }
879 
880         if (!completed) continue;
881 
882         for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
883             if (sco_out_transfers[c]){
884                 completed = 0;
885                 break;
886             }
887         }
888     }
889     sco_shutdown = 0;
890     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
891 
892     log_info("Switching to setting %u on interface 1..", 0);
893     int r = libusb_set_interface_alt_setting(handle, 1, 0);
894     if (r < 0) {
895         log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
896         return;
897     }
898 
899     printf("usb_sco_stop done\n");
900 }
901 
902 
903 
904 #endif
905 
906 static int usb_open(void){
907     int r;
908 
909     handle_packet = NULL;
910 
911     // default endpoint addresses
912     event_in_addr = 0x81; // EP1, IN interrupt
913     acl_in_addr =   0x82; // EP2, IN bulk
914     acl_out_addr =  0x02; // EP2, OUT bulk
915     sco_in_addr  =  0x83; // EP3, IN isochronous
916     sco_out_addr =  0x03; // EP3, OUT isochronous
917 
918     // USB init
919     r = libusb_init(NULL);
920     if (r < 0) return -1;
921 
922     libusb_state = LIB_USB_OPENED;
923 
924     // configure debug level
925     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
926 
927 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
928 
929     // Use a specified device
930     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
931     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
932 
933     if (!handle){
934         log_error("libusb_open_device_with_vid_pid failed!");
935         usb_close();
936         return -1;
937     }
938     log_info("libusb open %d, handle %p", r, handle);
939 
940     r = prepare_device(handle);
941     if (r < 0){
942         usb_close();
943         return -1;
944     }
945 
946 #else
947     // Scan system for an appropriate devices
948     libusb_device **devs;
949     ssize_t num_devices;
950 
951     log_info("Scanning for USB Bluetooth device");
952     num_devices = libusb_get_device_list(NULL, &devs);
953     if (num_devices < 0) {
954         usb_close();
955         return -1;
956     }
957 
958     dev = NULL;
959 
960     if (usb_path_len){
961         int i;
962         for (i=0;i<num_devices;i++){
963             uint8_t port_numbers[USB_MAX_PATH_LEN];
964             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
965             if (len != usb_path_len) continue;
966             if (memcmp(usb_path, port_numbers, len) == 0){
967                 log_info("USB device found at specified path");
968                 handle = try_open_device(devs[i]);
969                 if (!handle) continue;
970 
971                 r = prepare_device(handle);
972                 if (r < 0) continue;
973 
974                 dev = devs[i];
975                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
976                 break;
977             };
978         }
979         if (!handle){
980             log_error("USB device with given path not found");
981             printf("USB device with given path not found\n");
982             return -1;
983         }
984     } else {
985 
986         int deviceIndex = -1;
987         while (1){
988             // look for next Bluetooth dongle
989             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
990             if (deviceIndex < 0) break;
991 
992             log_info("USB Bluetooth device found, index %u", deviceIndex);
993 
994             handle = try_open_device(devs[deviceIndex]);
995             if (!handle) continue;
996 
997             r = prepare_device(handle);
998             if (r < 0) continue;
999 
1000             dev = devs[deviceIndex];
1001             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1002             break;
1003         }
1004     }
1005 
1006     libusb_free_device_list(devs, 1);
1007 
1008     if (handle == 0){
1009         log_error("No USB Bluetooth device found");
1010         return -1;
1011     }
1012 
1013     scan_for_bt_endpoints();
1014 
1015 #endif
1016 
1017     // allocate transfer handlers
1018     int c;
1019     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1020         event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events
1021         if (!event_in_transfer[c]) {
1022             usb_close();
1023             return LIBUSB_ERROR_NO_MEM;
1024         }
1025     }
1026     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1027         acl_in_transfer[c]  =  libusb_alloc_transfer(0); // 0 isochronous transfers ACL in
1028         if (!acl_in_transfer[c]) {
1029             usb_close();
1030             return LIBUSB_ERROR_NO_MEM;
1031         }
1032     }
1033 
1034     command_out_transfer = libusb_alloc_transfer(0);
1035     acl_out_transfer     = libusb_alloc_transfer(0);
1036 
1037     // TODO check for error
1038 
1039     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
1040 
1041     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1042         // configure event_in handlers
1043         libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr,
1044                 hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1045         r = libusb_submit_transfer(event_in_transfer[c]);
1046         if (r) {
1047             log_error("Error submitting interrupt transfer %d", r);
1048             usb_close();
1049             return r;
1050         }
1051     }
1052 
1053     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1054         // configure acl_in handlers
1055         libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr,
1056                 hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1057         r = libusb_submit_transfer(acl_in_transfer[c]);
1058         if (r) {
1059             log_error("Error submitting bulk in transfer %d", r);
1060             usb_close();
1061             return r;
1062         }
1063 
1064      }
1065 
1066     // Check for pollfds functionality
1067     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
1068 
1069     // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation here
1070     doing_pollfds = 0;
1071 
1072     if (doing_pollfds) {
1073         log_info("Async using pollfds:");
1074 
1075         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
1076         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
1077         pollfd_data_sources = (btstack_data_source_t *)malloc(sizeof(btstack_data_source_t) * num_pollfds);
1078         if (!pollfd_data_sources){
1079             log_error("Cannot allocate data sources for pollfds");
1080             usb_close();
1081             return 1;
1082         }
1083         for (r = 0 ; r < num_pollfds ; r++) {
1084             btstack_data_source_t *ds = &pollfd_data_sources[r];
1085             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
1086             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
1087             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
1088             btstack_run_loop_add_data_source(ds);
1089             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
1090         }
1091         free(pollfd);
1092     } else {
1093         log_info("Async using timers:");
1094 
1095         usb_timer.process = usb_process_ts;
1096         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
1097         btstack_run_loop_add_timer(&usb_timer);
1098         usb_timer_active = 1;
1099     }
1100 
1101     return 0;
1102 }
1103 
1104 static int usb_close(void){
1105     int c;
1106     int completed = 0;
1107 
1108     switch (libusb_state){
1109         case LIB_USB_CLOSED:
1110             break;
1111 
1112         case LIB_USB_TRANSFERS_ALLOCATED:
1113             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1114 
1115             if(usb_timer_active) {
1116                 btstack_run_loop_remove_timer(&usb_timer);
1117                 usb_timer_active = 0;
1118             }
1119 
1120             if (doing_pollfds){
1121                 int r;
1122                 for (r = 0 ; r < num_pollfds ; r++) {
1123                     btstack_data_source_t *ds = &pollfd_data_sources[r];
1124                     btstack_run_loop_remove_data_source(ds);
1125                 }
1126                 free(pollfd_data_sources);
1127                 pollfd_data_sources = NULL;
1128                 num_pollfds = 0;
1129                 doing_pollfds = 0;
1130             }
1131 
1132         case LIB_USB_INTERFACE_CLAIMED:
1133             // Cancel all transfers, ignore warnings for this
1134             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
1135             for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1136                 libusb_cancel_transfer(event_in_transfer[c]);
1137             }
1138             for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1139                 libusb_cancel_transfer(acl_in_transfer[c]);
1140             }
1141 #ifdef ENABLE_SCO_OVER_HCI
1142             for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1143                 libusb_cancel_transfer(sco_in_transfer[c]);
1144             }
1145             for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
1146                 if (sco_out_transfers_in_flight[c]) {
1147                     libusb_cancel_transfer(sco_out_transfers[c]);
1148                 } else {
1149                     libusb_free_transfer(sco_out_transfers[c]);
1150                     sco_out_transfers[c] = 0;
1151                 }
1152             }
1153 #endif
1154             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1155 
1156             // wait until all transfers are completed
1157             while (!completed){
1158                 struct timeval tv;
1159                 memset(&tv, 0, sizeof(struct timeval));
1160                 libusb_handle_events_timeout(NULL, &tv);
1161                 // check if all done
1162                 completed = 1;
1163                 for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
1164                     if (event_in_transfer[c]) {
1165                         completed = 0;
1166                         break;
1167                     }
1168                 }
1169 
1170                 if (!completed) continue;
1171 
1172                 for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
1173                     if (acl_in_transfer[c]) {
1174                         completed = 0;
1175                         break;
1176                     }
1177                 }
1178 
1179 #ifdef ENABLE_SCO_OVER_HCI
1180                 if (!completed) continue;
1181 
1182                 // Cancel all synchronous transfer
1183                 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1184                     if (sco_in_transfer[c]){
1185                         completed = 0;
1186                         break;
1187                     }
1188                 }
1189 
1190                 if (!completed) continue;
1191 
1192                 for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
1193                     if (sco_out_transfers[c]){
1194                         completed = 0;
1195                         break;
1196                     }
1197                 }
1198 #endif
1199             }
1200 
1201             // finally release interface
1202             libusb_release_interface(handle, 0);
1203 #ifdef ENABLE_SCO_OVER_HCI
1204             libusb_release_interface(handle, 1);
1205 #endif
1206             log_info("Libusb shutdown complete");
1207 
1208         case LIB_USB_DEVICE_OPENDED:
1209             libusb_close(handle);
1210 
1211         case LIB_USB_OPENED:
1212             libusb_exit(NULL);
1213     }
1214 
1215     libusb_state = LIB_USB_CLOSED;
1216     handle = NULL;
1217 
1218     return 0;
1219 }
1220 
1221 static int usb_send_cmd_packet(uint8_t *packet, int size){
1222     int r;
1223 
1224     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1225 
1226     // async
1227     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1228     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1229 
1230     // prepare transfer
1231     int completed = 0;
1232     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1233     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1234 
1235     // update stata before submitting transfer
1236     usb_command_active = 1;
1237 
1238     // submit transfer
1239     r = libusb_submit_transfer(command_out_transfer);
1240 
1241     if (r < 0) {
1242         usb_command_active = 0;
1243         log_error("Error submitting cmd transfer %d", r);
1244         return -1;
1245     }
1246 
1247     return 0;
1248 }
1249 
1250 static int usb_send_acl_packet(uint8_t *packet, int size){
1251     int r;
1252 
1253     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1254 
1255     // log_info("usb_send_acl_packet enter, size %u", size);
1256 
1257     // prepare transfer
1258     int completed = 0;
1259     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1260         async_callback, &completed, 0);
1261     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1262 
1263     // update stata before submitting transfer
1264     usb_acl_out_active = 1;
1265 
1266     r = libusb_submit_transfer(acl_out_transfer);
1267     if (r < 0) {
1268         usb_acl_out_active = 0;
1269         log_error("Error submitting acl transfer, %d", r);
1270         return -1;
1271     }
1272 
1273     return 0;
1274 }
1275 
1276 static int usb_can_send_packet_now(uint8_t packet_type){
1277     switch (packet_type){
1278         case HCI_COMMAND_DATA_PACKET:
1279             return !usb_command_active;
1280         case HCI_ACL_DATA_PACKET:
1281             return !usb_acl_out_active;
1282 #ifdef ENABLE_SCO_OVER_HCI
1283         case HCI_SCO_DATA_PACKET:
1284             return sco_ring_have_space();
1285 #endif
1286         default:
1287             return 0;
1288     }
1289 }
1290 
1291 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1292     switch (packet_type){
1293         case HCI_COMMAND_DATA_PACKET:
1294             return usb_send_cmd_packet(packet, size);
1295         case HCI_ACL_DATA_PACKET:
1296             return usb_send_acl_packet(packet, size);
1297 #ifdef ENABLE_SCO_OVER_HCI
1298         case HCI_SCO_DATA_PACKET:
1299             return usb_send_sco_packet(packet, size);
1300 #endif
1301         default:
1302             return -1;
1303     }
1304 }
1305 
1306 #ifdef ENABLE_SCO_OVER_HCI
1307 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1308     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1309 
1310     if (num_connections != sco_num_connections){
1311         sco_voice_setting = voice_setting;
1312         if (sco_num_connections){
1313             usb_sco_stop();
1314         }
1315         sco_num_connections = num_connections;
1316         if (num_connections){
1317             usb_sco_start();
1318         }
1319     }
1320 }
1321 #endif
1322 
1323 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1324     log_info("registering packet handler");
1325     packet_handler = handler;
1326 }
1327 
1328 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1329     UNUSED(packet_type);
1330     UNUSED(packet);
1331     UNUSED(size);
1332 }
1333 
1334 // get usb singleton
1335 const hci_transport_t * hci_transport_usb_instance(void) {
1336     if (!hci_transport_usb) {
1337         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1338         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1339         hci_transport_usb->name                          = "H2_LIBUSB";
1340         hci_transport_usb->open                          = usb_open;
1341         hci_transport_usb->close                         = usb_close;
1342         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1343         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1344         hci_transport_usb->send_packet                   = usb_send_packet;
1345 #ifdef ENABLE_SCO_OVER_HCI
1346         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1347 #endif
1348     }
1349     return hci_transport_usb;
1350 }
1351