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