forked from OpenPrinting/ipp-usb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
usbio_libusb.go
725 lines (602 loc) · 19.1 KB
/
usbio_libusb.go
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
/* ipp-usb - HTTP reverse proxy, backed by IPP-over-USB connection to device
*
* Copyright (C) 2020 and up by Alexander Pevzner ([email protected])
* See LICENSE for license terms and conditions
*
* USB low-level I/O. Cgo implementation on a top of libusb
*/
package main
import (
"encoding/binary"
"errors"
"sync"
"sync/atomic"
"time"
"unsafe"
)
// #cgo pkg-config: libusb-1.0
// #include <libusb.h>
//
// int libusbHotplugCallback (libusb_context *ctx, libusb_device *device,
// libusb_hotplug_event event, void *user_data);
//
// typedef struct libusb_device_descriptor libusb_device_descriptor_struct;
// typedef struct libusb_config_descriptor libusb_config_descriptor_struct;
// typedef struct libusb_interface libusb_interface_struct;
// typedef struct libusb_interface_descriptor libusb_interface_descriptor_struct;
// typedef struct libusb_endpoint_descriptor libusb_endpoint_descriptor_struct;
//
// // Note, libusb_strerror accepts enum libusb_error argument, which
// // unfortunately behaves differently depending on target OS and compiler
// // version (sometimes as C.int, sometimes as int32). Looks like cgo
// // bug. Wrapping this function into this simple wrapper should
// // fix the problem. See #18 for details
// static inline const char*
// libusb_strerror_wrapper (int code) {
// return libusb_strerror(code);
// }
import "C"
// UsbError represents USB error
type UsbError struct {
Func string
Code UsbErrCode
}
// Error describes a libusb error. It implements error interface
func (err UsbError) Error() string {
return err.Func + ": " + err.Code.String()
}
// UsbErrCode represents USB I/O error code
type UsbErrCode int
const (
UsbIO UsbErrCode = C.LIBUSB_ERROR_IO
UsbEInval = C.LIBUSB_ERROR_INVALID_PARAM
UsbEAccess = C.LIBUSB_ERROR_ACCESS
UsbENoDev = C.LIBUSB_ERROR_NO_DEVICE
UsbENotFound = C.LIBUSB_ERROR_NOT_FOUND
UsbEBusy = C.LIBUSB_ERROR_BUSY
UsbETimeout = C.LIBUSB_ERROR_TIMEOUT
UsbEOverflow = C.LIBUSB_ERROR_OVERFLOW
UsbEPipe = C.LIBUSB_ERROR_PIPE
UsbEIntr = C.LIBUSB_ERROR_INTERRUPTED
UsbENomem = C.LIBUSB_ERROR_NO_MEM
UsbENotSupported = C.LIBUSB_ERROR_NOT_SUPPORTED
UsbEOther = C.LIBUSB_ERROR_OTHER
)
// String returns string representation of error code
func (err UsbErrCode) String() string {
return C.GoString(C.libusb_strerror_wrapper(C.int(err)))
}
var (
// libusbContextPtr keeps a pointer to libusb_context.
// It is initialized on demand
libusbContextPtr *C.libusb_context
// libusbContextLock protects libusbContextPtr initialization
// in multithreaded context
libusbContextLock sync.Mutex
// Nonzero, if libusbContextPtr initialized
libusbContextOk int32
// UsbHotPlugChan receives USB hotplug event notifications
UsbHotPlugChan = make(chan struct{})
)
// Initialize low-level USB I/O
func UsbInit() error {
_, err := libusbContext()
return err
}
// libusbContext returns libusb_context. It
// initializes context on demand.
func libusbContext() (*C.libusb_context, error) {
if atomic.LoadInt32(&libusbContextOk) != 0 {
return libusbContextPtr, nil
}
libusbContextLock.Lock()
defer libusbContextLock.Unlock()
// Obtain libusb_context
rc := C.libusb_init(&libusbContextPtr)
if rc != 0 {
return nil, UsbError{"libusb_init", UsbErrCode(rc)}
}
// Subscribe to hotplug events
C.libusb_hotplug_register_callback(
libusbContextPtr, // libusb_context
C.LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED| // events mask
C.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
C.LIBUSB_HOTPLUG_NO_FLAGS, // flags
C.LIBUSB_HOTPLUG_MATCH_ANY, // vendor_id
C.LIBUSB_HOTPLUG_MATCH_ANY, // product_id
C.LIBUSB_HOTPLUG_MATCH_ANY, // dev_class
C.libusb_hotplug_callback_fn(unsafe.Pointer(C.libusbHotplugCallback)),
nil, // callback's data
nil, // deregister handle
)
// Start libusb thread (required for hotplug)
go func() {
for {
C.libusb_handle_events(libusbContextPtr)
}
}()
atomic.StoreInt32(&libusbContextOk, 1)
return libusbContextPtr, nil
}
// Called by libusb on hotplug event
//
//export libusbHotplugCallback
func libusbHotplugCallback(ctx *C.libusb_context, dev *C.libusb_device,
event C.libusb_hotplug_event, p unsafe.Pointer) C.int {
usbaddr := UsbAddr{
Bus: int(C.libusb_get_bus_number(dev)),
Address: int(C.libusb_get_device_address(dev)),
}
switch event {
case C.LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED:
Log.Debug('+', "HOTPLUG: added %s", usbaddr)
case C.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT:
Log.Debug('-', "HOTPLUG: removed %s", usbaddr)
}
select {
case UsbHotPlugChan <- struct{}{}:
default:
}
return 0
}
// UsbCheckIppOverUsbDevices returns true if there are some IPP-over-USB devices
func UsbCheckIppOverUsbDevices() bool {
descs, _ := UsbGetIppOverUsbDeviceDescs()
return len(descs) != 0
}
// UsbGetIppOverUsbDeviceDescs return list of IPP-over-USB
// device descriptors
func UsbGetIppOverUsbDeviceDescs() (map[UsbAddr]UsbDeviceDesc, error) {
// Obtain libusb context
ctx, err := libusbContext()
if err != nil {
return nil, err
}
// Obtain list of devices
var devlist **C.libusb_device
cnt := C.libusb_get_device_list(ctx, &devlist)
if cnt < 0 {
return nil, UsbError{"libusb_get_device_list", UsbErrCode(cnt)}
}
defer C.libusb_free_device_list(devlist, 1)
// Convert devlist to slice.
// See https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
devs := (*[1 << 28]*C.libusb_device)(unsafe.Pointer(devlist))[:cnt:cnt]
// Now build list of addresses
descs := make(map[UsbAddr]UsbDeviceDesc)
for _, dev := range devs {
desc, err := libusbBuildUsbDeviceDesc(dev)
if err == nil && len(desc.IfAddrs) >= 2 {
descs[desc.UsbAddr] = desc
}
}
return descs, nil
}
// libusbBuildUsbDeviceDesc builds device descriptor
func libusbBuildUsbDeviceDesc(dev *C.libusb_device) (UsbDeviceDesc, error) {
var c_desc C.libusb_device_descriptor_struct
var desc UsbDeviceDesc
// Obtain device descriptor
rc := C.libusb_get_device_descriptor(dev, &c_desc)
if rc < 0 {
return desc, UsbError{"libusb_get_device_descriptor", UsbErrCode(rc)}
}
// Decode device descriptor
desc.Bus = int(C.libusb_get_bus_number(dev))
desc.Address = int(C.libusb_get_device_address(dev))
desc.Config = -1
// Roll over configs/interfaces/alt settings/endpoins
for cfgNum := 0; cfgNum < int(c_desc.bNumConfigurations); cfgNum++ {
var conf *C.libusb_config_descriptor_struct
rc = C.libusb_get_config_descriptor(dev, C.uint8_t(cfgNum), &conf)
if rc == 0 {
// Make sure we use the same configuration for all interfaces
if desc.Config >= 0 && desc.Config != int(conf.bConfigurationValue) {
continue
}
ifcnt := conf.bNumInterfaces
ifaces := (*[256]C.libusb_interface_struct)(
unsafe.Pointer(conf._interface))[:ifcnt:ifcnt]
for ifnum, iface := range ifaces {
altcnt := iface.num_altsetting
alts := (*[256]C.libusb_interface_descriptor_struct)(
unsafe.Pointer(iface.altsetting))[:altcnt:altcnt]
for altnum, alt := range alts {
// Build and append UsbIfDesc
ifdesc := UsbIfDesc{
Config: int(conf.bConfigurationValue),
IfNum: int(alt.bInterfaceNumber),
Alt: int(alt.bAlternateSetting),
Class: int(alt.bInterfaceClass),
SubClass: int(alt.bInterfaceSubClass),
Proto: int(alt.bInterfaceProtocol),
}
desc.IfDescs = append(desc.IfDescs, ifdesc)
// We are only interested in IPP-over-USB
// interfaces, i.e., LIBUSB_CLASS_PRINTER,
// SubClass 1, Protocol 4
if ifdesc.IsIppOverUsb() {
epnum := alt.bNumEndpoints
endpoints := (*[256]C.libusb_endpoint_descriptor_struct)(
unsafe.Pointer(alt.endpoint))[:epnum:epnum]
in, out := -1, -1
for _, ep := range endpoints {
num := int(ep.bEndpointAddress & 0xf)
dir := int(ep.bEndpointAddress & 0x80)
switch dir {
case C.LIBUSB_ENDPOINT_IN:
if in == -1 {
in = num
}
case C.LIBUSB_ENDPOINT_OUT:
if out == -1 {
out = num
}
}
}
// Build and append UsbIfAddr
if in >= 0 && out >= 0 {
desc.Config = int(conf.bConfigurationValue)
addr := UsbIfAddr{
UsbAddr: desc.UsbAddr,
Num: ifnum,
Alt: altnum,
In: in,
Out: out,
}
desc.IfAddrs.Add(addr)
}
}
}
}
C.libusb_free_config_descriptor(conf)
}
}
return desc, nil
}
// UsbDevHandle represents libusb_device_handle
type UsbDevHandle C.libusb_device_handle
// UsbOpenDevice opens device by device descriptor
func UsbOpenDevice(desc UsbDeviceDesc) (*UsbDevHandle, error) {
// Obtain libusb context
ctx, err := libusbContext()
if err != nil {
return nil, err
}
// Obtain list of devices
var devlist **C.libusb_device
cnt := C.libusb_get_device_list(ctx, &devlist)
if cnt < 0 {
return nil, UsbError{"libusb_get_device_list", UsbErrCode(cnt)}
}
defer C.libusb_free_device_list(devlist, 1)
// Convert devlist to slice.
devs := (*[1 << 28]*C.libusb_device)(unsafe.Pointer(devlist))[:cnt:cnt]
// Find and open a device
for _, dev := range devs {
bus := int(C.libusb_get_bus_number(dev))
address := int(C.libusb_get_device_address(dev))
if desc.Bus == bus && desc.Address == address {
// Open device
var devhandle *C.libusb_device_handle
rc := C.libusb_open(dev, &devhandle)
if rc < 0 {
return nil, UsbError{"libusb_open", UsbErrCode(rc)}
}
return (*UsbDevHandle)(devhandle), nil
}
}
return nil, UsbError{"libusb_get_device_list", UsbENotFound}
}
// Configure prepares the device for further work:
// - set proper USB configuration
// - detach kernel driver
func (devhandle *UsbDevHandle) Configure(desc UsbDeviceDesc) error {
// Detach kernel driver
err := (*UsbDevHandle)(devhandle).detachKernelDriver()
if err != nil {
return err
}
// Set configuration
rc := C.libusb_set_configuration(
(*C.libusb_device_handle)(devhandle), C.int(desc.Config))
if rc < 0 {
return UsbError{"libusb_set_configuration", UsbErrCode(rc)}
}
// Printer may require some time to switch configuration
time.Sleep(time.Second / 4)
return nil
}
// detachKernelDriver detaches kernel driver from all interfaces
// of current configuration
func (devhandle *UsbDevHandle) detachKernelDriver() error {
C.libusb_set_auto_detach_kernel_driver(
(*C.libusb_device_handle)(devhandle), 1)
ifnums, err := devhandle.currentInterfaces()
if err != nil {
return err
}
for _, ifnum := range ifnums {
rc := C.libusb_detach_kernel_driver(
(*C.libusb_device_handle)(devhandle), C.int(ifnum))
if rc == C.LIBUSB_ERROR_NOT_FOUND {
rc = 0
}
if rc < 0 {
return UsbError{"libusb_detach_kernel_driver", UsbErrCode(rc)}
}
}
return nil
}
// libusbCurrentInterfaces builds list of interfaces in current configuration
func (devhandle *UsbDevHandle) currentInterfaces() ([]int, error) {
dev := C.libusb_get_device((*C.libusb_device_handle)(devhandle))
// Obtain device descriptor
var c_desc C.libusb_device_descriptor_struct
rc := C.libusb_get_device_descriptor(dev, &c_desc)
if rc < 0 {
return nil, UsbError{"libusb_get_device_descriptor", UsbErrCode(rc)}
}
// Get current configuration
var config C.int
rc = C.libusb_get_configuration((*C.libusb_device_handle)(devhandle), &config)
if rc < 0 {
return nil, UsbError{"libusb_get_configuration", UsbErrCode(rc)}
}
// Get configuration descriptor
var conf *C.libusb_config_descriptor_struct
for cfgNum := 0; cfgNum < int(c_desc.bNumConfigurations); cfgNum++ {
rc = C.libusb_get_config_descriptor(dev, C.uint8_t(cfgNum), &conf)
if rc < 0 {
return nil, UsbError{"libusb_get_configuration", UsbErrCode(rc)}
}
if conf.bConfigurationValue == C.uint8_t(config) {
break
}
C.libusb_free_config_descriptor(conf)
conf = nil
}
if conf == nil {
return nil, errors.New("libusb: unable to find current configuration in device descriptor")
}
defer C.libusb_free_config_descriptor(conf)
// Build list of interface numbers
ifcnt := conf.bNumInterfaces
ifaces := (*[256]C.libusb_interface_struct)(
unsafe.Pointer(conf._interface))[:ifcnt:ifcnt]
ifnumbers := make([]int, 0, ifcnt)
for _, iface := range ifaces {
alt := iface.altsetting
ifnumbers = append(ifnumbers, int(alt.bInterfaceNumber))
}
return ifnumbers, nil
}
// Close a device
func (devhandle *UsbDevHandle) Close() {
C.libusb_close((*C.libusb_device_handle)(devhandle))
}
// Reset a device
func (devhandle *UsbDevHandle) Reset() {
C.libusb_reset_device((*C.libusb_device_handle)(devhandle))
}
// UsbDeviceInfo returns UsbDeviceInfo for the device
func (devhandle *UsbDevHandle) UsbDeviceInfo() (UsbDeviceInfo, error) {
dev := C.libusb_get_device((*C.libusb_device_handle)(devhandle))
var c_desc C.libusb_device_descriptor_struct
var info UsbDeviceInfo
// Obtain device descriptor
rc := C.libusb_get_device_descriptor(dev, &c_desc)
if rc < 0 {
return info, UsbError{"libusb_get_device_descriptor", UsbErrCode(rc)}
}
// Decode device descriptor
info.Vendor = uint16(c_desc.idVendor)
info.Product = uint16(c_desc.idProduct)
info.BasicCaps = devhandle.usbIppBasicCaps()
buf := make([]byte, 256)
strings := []struct {
idx C.uint8_t
str *string
}{
{c_desc.iManufacturer, &info.Manufacturer},
{c_desc.iProduct, &info.ProductName},
{c_desc.iSerialNumber, &info.SerialNumber},
}
for _, s := range strings {
rc := C.libusb_get_string_descriptor_ascii(
(*C.libusb_device_handle)(devhandle),
s.idx,
(*C.uchar)(unsafe.Pointer(&buf[0])),
C.int(len(buf)),
)
if rc > 0 {
*s.str = string(buf[:rc])
}
}
info.PortNum = int(C.libusb_get_port_number(dev))
info.FixUp()
return info, nil
}
// usbIppBasicCaps reads and decodes printer's
// Class-specific Device Info Descriptor to obtain device
// capabilities
//
// See IPP USB specification, section 4.3 for details
//
// This function never fails. In a case of errors, it fall backs
// to the reasonable default
func (devhandle *UsbDevHandle) usbIppBasicCaps() (caps UsbIppBasicCaps) {
// Safe default
caps = UsbIppBasicCapsPrint |
UsbIppBasicCapsScan |
UsbIppBasicCapsFax |
UsbIppBasicCapsAnyHTTP
// Buffer length
const bufLen = 256
// Obtain class-specific Device Info Descriptor
// See IPP USB specification, section 4.3 for details
buf := make([]byte, bufLen)
rc := C.libusb_get_descriptor(
(*C.libusb_device_handle)(devhandle),
0x21, 0,
(*C.uchar)(unsafe.Pointer(&buf[0])),
bufLen)
if rc < 0 {
// Some devices doesn't properly return class-specific
// device descriptor, so ignore an error
return
}
if rc < 10 {
// Malformed response, fall back to default
return
}
// Decode basic capabilities bits
bits := binary.LittleEndian.Uint16(buf[6:8])
if bits == 0 {
// Paranoia. If no caps, return default
return
}
return UsbIppBasicCaps(bits)
}
// OpenUsbInterface opens an interface
func (devhandle *UsbDevHandle) OpenUsbInterface(addr UsbIfAddr) (
*UsbInterface, error) {
// Claim the interface
rc := C.libusb_claim_interface(
(*C.libusb_device_handle)(devhandle),
C.int(addr.Num),
)
if rc < 0 {
return nil, UsbError{"libusb_claim_interface", UsbErrCode(rc)}
}
// Activate alternate setting
rc = C.libusb_set_interface_alt_setting(
(*C.libusb_device_handle)(devhandle),
C.int(addr.Num),
C.int(addr.Alt),
)
if rc < 0 {
C.libusb_release_interface(
(*C.libusb_device_handle)(devhandle),
C.int(addr.Num),
)
return nil, UsbError{"libusb_set_interface_alt_setting", UsbErrCode(rc)}
}
return &UsbInterface{
devhandle: devhandle,
addr: addr,
}, nil
}
// UsbInterface represents IPP-over-USB interface
type UsbInterface struct {
devhandle *UsbDevHandle // Device handle
addr UsbIfAddr // Interface address
}
// Close the interface
func (iface *UsbInterface) Close() {
C.libusb_release_interface(
(*C.libusb_device_handle)(iface.devhandle),
C.int(iface.addr.Num),
)
}
// SoftReset performs interface soft reset, using class-specific
// SOFT_RESET request
//
// This code was inspired by CUPS, and the original comment follows:
//
// This soft reset is specific to the printer device class and is much less
// invasive than the general USB reset libusb_reset_device(). Especially it
// does never happen that the USB addressing and configuration changes. What
// is actually done is that all buffers get flushed and the bulk IN and OUT
// pipes get reset to their default states. This clears all stall conditions.
// See http://cholla.mmto.org/computers/linux/usb/usbprint11.pdf
func (iface *UsbInterface) SoftReset() error {
rc := C.libusb_control_transfer(
(*C.libusb_device_handle)(iface.devhandle),
C.LIBUSB_REQUEST_TYPE_CLASS|
C.LIBUSB_ENDPOINT_OUT|
C.LIBUSB_RECIPIENT_OTHER,
2, 0, C.ushort(iface.addr.Num), nil, 0, 5000)
if rc < 0 {
rc = C.libusb_control_transfer(
(*C.libusb_device_handle)(iface.devhandle),
C.LIBUSB_REQUEST_TYPE_CLASS|
C.LIBUSB_ENDPOINT_OUT|
C.LIBUSB_RECIPIENT_INTERFACE,
2, 0, C.ushort(iface.addr.Num), nil, 0, 5000)
}
if rc < 0 {
return UsbError{"libusb_control_transfer", UsbErrCode(rc)}
}
return nil
}
// Send data to interface. Returns count of bytes actually transmitted
// and error, if any
func (iface *UsbInterface) Send(data []byte,
timeout time.Duration) (n int, err error) {
var transferred C.int
rc := C.libusb_bulk_transfer(
(*C.libusb_device_handle)(iface.devhandle),
C.uint8_t(iface.addr.Out|C.LIBUSB_ENDPOINT_OUT),
(*C.uchar)(unsafe.Pointer(&data[0])),
C.int(len(data)),
&transferred,
C.uint(timeout/time.Millisecond),
)
if rc < 0 {
err = UsbError{"libusb_bulk_transfer", UsbErrCode(rc)}
}
n = int(transferred)
return
}
// Recv data from interface. Returns count of bytes actually transmitted
// and error, if any
//
// Note, if data size is not 512-byte aligned, and device has more data,
// that fits the provided buffer, LIBUSB_ERROR_OVERFLOW error may occur
func (iface *UsbInterface) Recv(data []byte,
timeout time.Duration) (n int, err error) {
var transferred C.int
// Some versions of Linux kernel don't allow bulk transfers to
// be larger that 16kb per URB, and libusb uses some smart-ass
// mechanism to avoid this limitation.
//
// This mechanism seems not to work very reliable on Raspberry Pi
// (see #3 for details). So just limit bulk reads to 16kb
const MAX_BULK_READ = 16384
if len(data) > MAX_BULK_READ {
data = data[0:MAX_BULK_READ]
}
rc := C.libusb_bulk_transfer(
(*C.libusb_device_handle)(iface.devhandle),
C.uint8_t(iface.addr.In|C.LIBUSB_ENDPOINT_IN),
(*C.uchar)(unsafe.Pointer(&data[0])),
C.int(len(data)),
&transferred,
C.uint(timeout/time.Millisecond),
)
if rc == C.LIBUSB_ERROR_PIPE {
iface.ClearHalt(true)
}
if rc < 0 {
err = UsbError{"libusb_bulk_transfer", UsbErrCode(rc)}
}
n = int(transferred)
return
}
// Clear "halted" condition of either input or output endpoint
func (iface *UsbInterface) ClearHalt(in bool) error {
var ep C.uint8_t
if in {
ep = C.uint8_t(iface.addr.In | C.LIBUSB_ENDPOINT_IN)
} else {
ep = C.uint8_t(iface.addr.Out | C.LIBUSB_ENDPOINT_OUT)
}
rc := C.libusb_clear_halt(
(*C.libusb_device_handle)(iface.devhandle),
ep)
if rc < 0 {
return UsbError{"libusb_clear_halt", UsbErrCode(rc)}
}
return nil
}