/
hci_transport_h2_libusb.c
1388 lines (1161 loc) · 45.1 KB
/
hci_transport_h2_libusb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014 BlueKitchen GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* 4. Any redistribution, use, or modification is done solely for
* personal benefit and not for any commercial purpose or for
* monetary gain.
*
* THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
* RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Please inquire about commercial licensing options at
* contact@bluekitchen-gmbh.com
*
*/
#define __BTSTACK_FILE__ "hci_transport_h2_libusb.c"
/*
* hci_transport_usb.c
*
* HCI Transport API implementation for USB
*
* Created by Matthias Ringwald on 7/5/09.
*/
// Interface Number - Alternate Setting - suggested Endpoint Address - Endpoint Type - Suggested Max Packet Size
// HCI Commands 0 0 0x00 Control 8/16/32/64
// HCI Events 0 0 0x81 Interrupt (IN) 16
// ACL Data 0 0 0x82 Bulk (IN) 32/64
// ACL Data 0 0 0x02 Bulk (OUT) 32/64
// SCO Data 0 0 0x83 Isochronous (IN)
// SCO Data 0 0 0x03 Isochronous (Out)
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <unistd.h> /* UNIX standard function definitions */
#include <sys/types.h>
#include <libusb.h>
#include "btstack_config.h"
#include "btstack_debug.h"
#include "hci.h"
#include "hci_transport.h"
// deal with changes in libusb API:
#ifdef LIBUSB_API_VERSION
#if LIBUSB_API_VERSION >= 0x01000106
// since 1.0.22, libusb_set_option replaces libusb_set_debug
#define libusb_set_debug(context,level) libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, level)
#endif
#endif
#if (USB_VENDOR_ID != 0) && (USB_PRODUCT_ID != 0)
#define HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
#endif
#define ACL_IN_BUFFER_COUNT 3
#define EVENT_IN_BUFFER_COUNT 3
#define SCO_IN_BUFFER_COUNT 10
#define ASYNC_POLLING_INTERVAL_MS 1
//
// Bluetooth USB Transport Alternate Settings:
//
// 0: No active voice channels (for USB compliance)
// 1: One 8 kHz voice channel with 8-bit encoding
// 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
// 3: Three 8 kHz voice channels with 8-bit encoding
// 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
// 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
// --> support only a single SCO connection
// #define ALT_SETTING (1)
#ifdef ENABLE_SCO_OVER_HCI
// alt setting for 1-3 connections and 8/16 bit
static const int alt_setting_8_bit[] = {1,2,3};
static const int alt_setting_16_bit[] = {2,4,5};
// for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
// One complete SCO packet with 24 frames every 3 frames (== 3 ms)
#define NUM_ISO_PACKETS (3)
static const uint16_t iso_packet_size_for_alt_setting[] = {
0,
9,
17,
25,
33,
49,
63,
};
#endif
// 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)
// 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
#define SCO_PACKET_SIZE (49 * NUM_ISO_PACKETS)
// Outgoing SCO packet queue
// simplified ring buffer implementation
#define SCO_OUT_BUFFER_COUNT (8)
#define SCO_OUT_BUFFER_SIZE (SCO_OUT_BUFFER_COUNT * SCO_PACKET_SIZE)
// seems to be the max depth for USB 3
#define USB_MAX_PATH_LEN 7
// prototypes
static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
static int usb_close(void);
typedef enum {
LIB_USB_CLOSED = 0,
LIB_USB_OPENED,
LIB_USB_DEVICE_OPENDED,
LIB_USB_INTERFACE_CLAIMED,
LIB_USB_TRANSFERS_ALLOCATED
} libusb_state_t;
// SCO packet state machine
typedef enum {
H2_W4_SCO_HEADER = 1,
H2_W4_PAYLOAD,
} H2_SCO_STATE;
static libusb_state_t libusb_state = LIB_USB_CLOSED;
// single instance
static hci_transport_t * hci_transport_usb = NULL;
static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = dummy_handler;
// libusb
#ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
static struct libusb_device_descriptor desc;
static libusb_device * dev;
#endif
static libusb_device_handle * handle;
static struct libusb_transfer *command_out_transfer;
static struct libusb_transfer *acl_out_transfer;
static struct libusb_transfer *event_in_transfer[EVENT_IN_BUFFER_COUNT];
static struct libusb_transfer *acl_in_transfer[ACL_IN_BUFFER_COUNT];
#ifdef ENABLE_SCO_OVER_HCI
#ifdef _WIN32
#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"
#endif
// incoming SCO
static H2_SCO_STATE sco_state;
static uint8_t sco_buffer[255+3 + SCO_PACKET_SIZE];
static uint16_t sco_read_pos;
static uint16_t sco_bytes_to_read;
static struct libusb_transfer *sco_in_transfer[SCO_IN_BUFFER_COUNT];
static uint8_t hci_sco_in_buffer[SCO_IN_BUFFER_COUNT][SCO_PACKET_SIZE];
// outgoing SCO
static uint8_t sco_out_ring_buffer[SCO_OUT_BUFFER_SIZE];
static int sco_ring_write; // packet idx
static int sco_out_transfers_active;
static struct libusb_transfer *sco_out_transfers[SCO_OUT_BUFFER_COUNT];
static int sco_out_transfers_in_flight[SCO_OUT_BUFFER_COUNT];
// pause/resume
static uint16_t sco_voice_setting;
static int sco_num_connections;
static int sco_shutdown;
// dynamic SCO configuration
static uint16_t iso_packet_size;
#endif
// outgoing buffer for HCI Command packets
static uint8_t hci_cmd_buffer[3 + 256 + LIBUSB_CONTROL_SETUP_SIZE];
// incoming buffer for HCI Events and ACL Packets
static uint8_t hci_event_in_buffer[EVENT_IN_BUFFER_COUNT][HCI_ACL_BUFFER_SIZE]; // bigger than largest packet
static uint8_t hci_acl_in_buffer[ACL_IN_BUFFER_COUNT][HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
// For (ab)use as a linked list of received packets
static struct libusb_transfer *handle_packet;
static int doing_pollfds;
static int num_pollfds;
static btstack_data_source_t * pollfd_data_sources;
static btstack_timer_source_t usb_timer;
static int usb_timer_active;
static int usb_acl_out_active = 0;
static int usb_command_active = 0;
// endpoint addresses
static int event_in_addr;
static int acl_in_addr;
static int acl_out_addr;
static int sco_in_addr;
static int sco_out_addr;
// device path
static int usb_path_len;
static uint8_t usb_path[USB_MAX_PATH_LEN];
#ifdef ENABLE_SCO_OVER_HCI
static void sco_ring_init(void){
sco_ring_write = 0;
sco_out_transfers_active = 0;
}
static int sco_ring_have_space(void){
return sco_out_transfers_active < SCO_OUT_BUFFER_COUNT;
}
#endif
void hci_transport_usb_set_path(int len, uint8_t * port_numbers){
if (len > USB_MAX_PATH_LEN || !port_numbers){
log_error("hci_transport_usb_set_path: len or port numbers invalid");
return;
}
usb_path_len = len;
memcpy(usb_path, port_numbers, len);
}
//
static void queue_transfer(struct libusb_transfer *transfer){
// log_info("queue_transfer %p, endpoint %x size %u", transfer, transfer->endpoint, transfer->actual_length);
transfer->user_data = NULL;
// insert first element
if (handle_packet == NULL) {
handle_packet = transfer;
return;
}
// Walk to end of list and add current packet there
struct libusb_transfer *temp = handle_packet;
while (temp->user_data) {
temp = (struct libusb_transfer*)temp->user_data;
}
temp->user_data = transfer;
}
LIBUSB_CALL static void async_callback(struct libusb_transfer *transfer){
int c;
if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED){
log_info("shutdown, transfer %p", transfer);
}
// identify and free transfers as part of shutdown
#ifdef ENABLE_SCO_OVER_HCI
if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED || sco_shutdown) {
for (c=0;c<SCO_IN_BUFFER_COUNT;c++){
if (transfer == sco_in_transfer[c]){
libusb_free_transfer(transfer);
sco_in_transfer[c] = 0;
return;
}
}
for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
if (transfer == sco_out_transfers[c]){
sco_out_transfers_in_flight[c] = 0;
libusb_free_transfer(transfer);
sco_out_transfers[c] = 0;
return;
}
}
}
#endif
if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) {
for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
if (transfer == event_in_transfer[c]){
libusb_free_transfer(transfer);
event_in_transfer[c] = 0;
return;
}
}
for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
if (transfer == acl_in_transfer[c]){
libusb_free_transfer(transfer);
acl_in_transfer[c] = 0;
return;
}
}
return;
}
#ifdef ENABLE_SCO_OVER_HCI
// mark SCO OUT transfer as done
for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
if (transfer == sco_out_transfers[c]){
sco_out_transfers_in_flight[c] = 0;
}
}
#endif
int r;
// log_info("begin async_callback endpoint %x, status %x, actual length %u", transfer->endpoint, transfer->status, transfer->actual_length );
if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
queue_transfer(transfer);
} else if (transfer->status == LIBUSB_TRANSFER_STALL){
log_info("-> Transfer stalled, trying again");
r = libusb_clear_halt(handle, transfer->endpoint);
if (r) {
log_error("Error rclearing halt %d", r);
}
r = libusb_submit_transfer(transfer);
if (r) {
log_error("Error re-submitting transfer %d", r);
}
} else {
log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length);
// No usable data, just resubmit packet
r = libusb_submit_transfer(transfer);
if (r) {
log_error("Error re-submitting transfer %d", r);
}
}
// log_info("end async_callback");
}
#ifdef ENABLE_SCO_OVER_HCI
static int usb_send_sco_packet(uint8_t *packet, int size){
int r;
if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
// log_info("usb_send_acl_packet enter, size %u", size);
// store packet in free slot
int tranfer_index = sco_ring_write;
uint8_t * data = &sco_out_ring_buffer[tranfer_index * SCO_PACKET_SIZE];
memcpy(data, packet, size);
// setup transfer
// 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);
struct libusb_transfer * sco_transfer = sco_out_transfers[tranfer_index];
libusb_fill_iso_transfer(sco_transfer, handle, sco_out_addr, data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
libusb_set_iso_packet_lengths(sco_transfer, iso_packet_size);
r = libusb_submit_transfer(sco_transfer);
if (r < 0) {
log_error("Error submitting sco transfer, %d", r);
return -1;
}
// mark slot as full
sco_ring_write++;
if (sco_ring_write == SCO_OUT_BUFFER_COUNT){
sco_ring_write = 0;
}
sco_out_transfers_active++;
sco_out_transfers_in_flight[tranfer_index] = 1;
// log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_out_transfers_active);
// notify upper stack that provided buffer can be used again
uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
// and if we have more space for SCO packets
if (sco_ring_have_space()) {
uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
}
return 0;
}
static void sco_state_machine_init(void){
sco_state = H2_W4_SCO_HEADER;
sco_read_pos = 0;
sco_bytes_to_read = 3;
}
static void handle_isochronous_data(uint8_t * buffer, uint16_t size){
while (size){
if (size < sco_bytes_to_read){
// just store incomplete data
memcpy(&sco_buffer[sco_read_pos], buffer, size);
sco_read_pos += size;
sco_bytes_to_read -= size;
return;
}
// copy requested data
memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
sco_read_pos += sco_bytes_to_read;
buffer += sco_bytes_to_read;
size -= sco_bytes_to_read;
// chunk read successfully, next action
switch (sco_state){
case H2_W4_SCO_HEADER:
sco_state = H2_W4_PAYLOAD;
sco_bytes_to_read = sco_buffer[2];
break;
case H2_W4_PAYLOAD:
// packet complete
packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
sco_state_machine_init();
break;
}
}
}
#endif
static void handle_completed_transfer(struct libusb_transfer *transfer){
int resubmit = 0;
int signal_done = 0;
if (transfer->endpoint == event_in_addr) {
packet_handler(HCI_EVENT_PACKET, transfer-> buffer, transfer->actual_length);
resubmit = 1;
} else if (transfer->endpoint == acl_in_addr) {
// log_info("-> acl");
packet_handler(HCI_ACL_DATA_PACKET, transfer-> buffer, transfer->actual_length);
resubmit = 1;
} else if (transfer->endpoint == 0){
// log_info("command done, size %u", transfer->actual_length);
usb_command_active = 0;
signal_done = 1;
} else if (transfer->endpoint == acl_out_addr){
// log_info("acl out done, size %u", transfer->actual_length);
usb_acl_out_active = 0;
signal_done = 1;
#ifdef ENABLE_SCO_OVER_HCI
} else if (transfer->endpoint == sco_in_addr) {
// log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS);
int i;
for (i = 0; i < transfer->num_iso_packets; i++) {
struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
log_error("Error: pack %u status %d\n", i, pack->status);
continue;
}
if (!pack->actual_length) continue;
uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i);
// printf_hexdump(data, pack->actual_length);
// log_info("handle_isochronous_data,size %u/%u", pack->length, pack->actual_length);
handle_isochronous_data(data, pack->actual_length);
}
resubmit = 1;
} else if (transfer->endpoint == sco_out_addr){
int i;
for (i = 0; i < transfer->num_iso_packets; i++) {
struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
log_error("Error: pack %u status %d\n", i, pack->status);
}
}
// log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}",
// transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status,
// transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status,
// transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status);
// notify upper layer if there's space for new SCO packets
if (sco_ring_have_space()) {
uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
}
// decrease tab
sco_out_transfers_active--;
// log_info("H2: sco out complete, num active num active %u", sco_out_transfers_active);
#endif
} else {
log_info("usb_process_ds endpoint unknown %x", transfer->endpoint);
}
if (signal_done){
// notify upper stack that provided buffer can be used again
uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
}
if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
if (resubmit){
// Re-submit transfer
transfer->user_data = NULL;
int r = libusb_submit_transfer(transfer);
if (r) {
log_error("Error re-submitting transfer %d", r);
}
}
}
static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
UNUSED(ds);
UNUSED(callback_type);
if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
// log_info("begin usb_process_ds");
// always handling an event as we're called when data is ready
struct timeval tv;
memset(&tv, 0, sizeof(struct timeval));
libusb_handle_events_timeout(NULL, &tv);
// Handle any packet in the order that they were received
while (handle_packet) {
// log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status);
void * next = handle_packet->user_data;
handle_completed_transfer(handle_packet);
// handle case where libusb_close might be called by hci packet handler
if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
// Move to next in the list of packets to handle
if (next) {
handle_packet = (struct libusb_transfer*)next;
} else {
handle_packet = NULL;
}
}
// log_info("end usb_process_ds");
}
static void usb_process_ts(btstack_timer_source_t *timer) {
UNUSED(timer);
// log_info("in usb_process_ts");
// timer is deactive, when timer callback gets called
usb_timer_active = 0;
if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
// actually handled the packet in the pollfds function
usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ);
// Get the amount of time until next event is due
long msec = ASYNC_POLLING_INTERVAL_MS;
// Activate timer
btstack_run_loop_set_timer(&usb_timer, msec);
btstack_run_loop_add_timer(&usb_timer);
usb_timer_active = 1;
return;
}
#ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
// list of known devices, using VendorID/ProductID tuples
static const uint16_t known_bt_devices[] = {
// DeLOCK Bluetooth 4.0
0x0a5c, 0x21e8,
// Asus BT400
0x0b05, 0x17cb,
// BCM20702B0 (Generic USB Detuned Class 1 @ 20 MHz)
0x0a5c, 0x22be
};
static int num_known_devices = sizeof(known_bt_devices) / sizeof(uint16_t) / 2;
static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
int i;
for (i=0; i<num_known_devices; i++){
if (known_bt_devices[i*2] == vendor_id && known_bt_devices[i*2+1] == product_id){
return 1;
}
}
return 0;
}
static void scan_for_bt_endpoints(void) {
int r;
event_in_addr = 0;
acl_in_addr = 0;
acl_out_addr = 0;
sco_out_addr = 0;
sco_in_addr = 0;
// get endpoints from interface descriptor
struct libusb_config_descriptor *config_descriptor;
r = libusb_get_active_config_descriptor(dev, &config_descriptor);
int num_interfaces = config_descriptor->bNumInterfaces;
log_info("active configuration has %u interfaces", num_interfaces);
int i;
for (i = 0; i < num_interfaces ; i++){
const struct libusb_interface *interface = &config_descriptor->interface[i];
const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
switch (endpoint->bmAttributes & 0x3){
case LIBUSB_TRANSFER_TYPE_INTERRUPT:
if (event_in_addr) continue;
event_in_addr = endpoint->bEndpointAddress;
log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
break;
case LIBUSB_TRANSFER_TYPE_BULK:
if (endpoint->bEndpointAddress & 0x80) {
if (acl_in_addr) continue;
acl_in_addr = endpoint->bEndpointAddress;
log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
} else {
if (acl_out_addr) continue;
acl_out_addr = endpoint->bEndpointAddress;
log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
}
break;
case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
if (endpoint->bEndpointAddress & 0x80) {
if (sco_in_addr) continue;
sco_in_addr = endpoint->bEndpointAddress;
log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
} else {
if (sco_out_addr) continue;
sco_out_addr = endpoint->bEndpointAddress;
log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
}
break;
default:
break;
}
}
}
libusb_free_config_descriptor(config_descriptor);
}
// returns index of found device or -1
static int scan_for_bt_device(libusb_device **devs, int start_index) {
int i;
for (i = start_index; devs[i] ; i++){
dev = devs[i];
int r = libusb_get_device_descriptor(dev, &desc);
if (r < 0) {
log_error("failed to get device descriptor");
return 0;
}
log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
desc.idVendor, desc.idProduct,
libusb_get_bus_number(dev), libusb_get_device_address(dev),
desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
// Detect USB Dongle based Class, Subclass, and Protocol
// The class code (bDeviceClass) is 0xE0 – Wireless Controller.
// The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
// The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
// if (desc.bDeviceClass == 0xe0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01){
if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
return i;
}
// Detect USB Dongle based on whitelist
if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
return i;
}
}
return -1;
}
#endif
static int prepare_device(libusb_device_handle * aHandle){
// print device path
uint8_t port_numbers[USB_MAX_PATH_LEN];
libusb_device * device = libusb_get_device(aHandle);
int path_len = libusb_get_port_numbers(device, port_numbers, USB_MAX_PATH_LEN);
printf("USB Path: ");
int i;
for (i=0;i<path_len;i++){
if (i) printf("-");
printf("%02x", port_numbers[i]);
}
printf("\n");
int r;
int kernel_driver_detached = 0;
// Detach OS driver (not possible for OS X and WIN32)
#if !defined(__APPLE__) && !defined(_WIN32)
r = libusb_kernel_driver_active(aHandle, 0);
if (r < 0) {
log_error("libusb_kernel_driver_active error %d", r);
libusb_close(aHandle);
return r;
}
if (r == 1) {
r = libusb_detach_kernel_driver(aHandle, 0);
if (r < 0) {
log_error("libusb_detach_kernel_driver error %d", r);
libusb_close(aHandle);
return r;
}
kernel_driver_detached = 1;
}
log_info("libusb_detach_kernel_driver");
#endif
const int configuration = 1;
log_info("setting configuration %d...", configuration);
r = libusb_set_configuration(aHandle, configuration);
if (r < 0) {
log_error("Error libusb_set_configuration: %d", r);
if (kernel_driver_detached){
libusb_attach_kernel_driver(aHandle, 0);
}
libusb_close(aHandle);
return r;
}
// reserve access to device
log_info("claiming interface 0...");
r = libusb_claim_interface(aHandle, 0);
if (r < 0) {
log_error("Error claiming interface %d", r);
if (kernel_driver_detached){
libusb_attach_kernel_driver(aHandle, 0);
}
libusb_close(aHandle);
return r;
}
#ifdef ENABLE_SCO_OVER_HCI
log_info("claiming interface 1...");
r = libusb_claim_interface(aHandle, 1);
if (r < 0) {
log_error("Error claiming interface %d", r);
if (kernel_driver_detached){
libusb_attach_kernel_driver(aHandle, 0);
}
libusb_close(aHandle);
return r;
}
#endif
return 0;
}
static libusb_device_handle * try_open_device(libusb_device * device){
int r;
libusb_device_handle * dev_handle;
r = libusb_open(device, &dev_handle);
if (r < 0) {
log_error("libusb_open failed!");
dev_handle = NULL;
return NULL;
}
log_info("libusb open %d, handle %p", r, dev_handle);
// reset device
libusb_reset_device(dev_handle);
if (r < 0) {
log_error("libusb_reset_device failed!");
libusb_close(dev_handle);
return NULL;
}
return dev_handle;
}
#ifdef ENABLE_SCO_OVER_HCI
static int usb_sco_start(void){
printf("usb_sco_start\n");
log_info("usb_sco_start");
sco_state_machine_init();
sco_ring_init();
int alt_setting;
if (sco_voice_setting & 0x0020){
// 16-bit PCM
alt_setting = alt_setting_16_bit[sco_num_connections-1];
} else {
// 8-bit PCM or mSBC
alt_setting = alt_setting_8_bit[sco_num_connections-1];
}
// derive iso packet size from alt setting
iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
log_info("Switching to setting %u on interface 1..", alt_setting);
int r = libusb_set_interface_alt_setting(handle, 1, alt_setting);
if (r < 0) {
log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r));
return r;
}
// incoming
int c;
for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in
if (!sco_in_transfer[c]) {
usb_close();
return LIBUSB_ERROR_NO_MEM;
}
// configure sco_in handlers
libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr,
hci_sco_in_buffer[c], NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
libusb_set_iso_packet_lengths(sco_in_transfer[c], iso_packet_size);
r = libusb_submit_transfer(sco_in_transfer[c]);
if (r) {
log_error("Error submitting isochronous in transfer %d", r);
usb_close();
return r;
}
}
// outgoing
for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
sco_out_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts
sco_out_transfers_in_flight[c] = 0;
}
return 0;
}
static void usb_sco_stop(void){
printf("usb_sco_stop\n");
log_info("usb_sco_stop");
sco_shutdown = 1;
libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
int c;
for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
libusb_cancel_transfer(sco_in_transfer[c]);
}
for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
if (sco_out_transfers_in_flight[c]) {
libusb_cancel_transfer(sco_out_transfers[c]);
} else {
libusb_free_transfer(sco_out_transfers[c]);
sco_out_transfers[c] = 0;
}
}
// wait until all transfers are completed
int completed = 0;
while (!completed){
struct timeval tv;
memset(&tv, 0, sizeof(struct timeval));
libusb_handle_events_timeout(NULL, &tv);
// check if all done
completed = 1;
// Cancel all synchronous transfer
for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
if (sco_in_transfer[c]){
completed = 0;
break;
}
}
if (!completed) continue;
for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
if (sco_out_transfers[c]){
completed = 0;
break;
}
}
}
sco_shutdown = 0;
libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
log_info("Switching to setting %u on interface 1..", 0);
int r = libusb_set_interface_alt_setting(handle, 1, 0);
if (r < 0) {
log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
return;
}
printf("usb_sco_stop done\n");
}
#endif
static int usb_open(void){
int r;
handle_packet = NULL;
// default endpoint addresses
event_in_addr = 0x81; // EP1, IN interrupt
acl_in_addr = 0x82; // EP2, IN bulk
acl_out_addr = 0x02; // EP2, OUT bulk
sco_in_addr = 0x83; // EP3, IN isochronous
sco_out_addr = 0x03; // EP3, OUT isochronous
// USB init
r = libusb_init(NULL);
if (r < 0) return -1;
libusb_state = LIB_USB_OPENED;
// configure debug level
libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
#ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
// Use a specified device
log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
if (!handle){
log_error("libusb_open_device_with_vid_pid failed!");
usb_close();
return -1;
}
log_info("libusb open %d, handle %p", r, handle);
r = prepare_device(handle);
if (r < 0){
usb_close();
return -1;
}
#else
// Scan system for an appropriate devices
libusb_device **devs;
ssize_t num_devices;
log_info("Scanning for USB Bluetooth device");
num_devices = libusb_get_device_list(NULL, &devs);
if (num_devices < 0) {
usb_close();
return -1;
}
dev = NULL;
if (usb_path_len){
int i;
for (i=0;i<num_devices;i++){
uint8_t port_numbers[USB_MAX_PATH_LEN];
int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
if (len != usb_path_len) continue;
if (memcmp(usb_path, port_numbers, len) == 0){
log_info("USB device found at specified path");
handle = try_open_device(devs[i]);
if (!handle) continue;
r = prepare_device(handle);
if (r < 0) continue;
dev = devs[i];
libusb_state = LIB_USB_INTERFACE_CLAIMED;
break;
};
}
if (!handle){
log_error("USB device with given path not found");
printf("USB device with given path not found\n");
return -1;
}
} else {