diff --git a/usb/device.go b/usb/device.go index 5a7b8be..7abf63b 100644 --- a/usb/device.go +++ b/usb/device.go @@ -4,6 +4,7 @@ package usb import "C" import ( + "log" "fmt" "reflect" "runtime" @@ -58,6 +59,7 @@ func (d *Device) Reset() error { } func (d *Device) Control(rType, request uint8, val, idx uint16, data []byte) (int, error) { + log.Printf("control xfer: %d:%d/%d:%d %x", idx, rType, request, val, string(data)) dataSlice := (*reflect.SliceHeader)(unsafe.Pointer(&data)) n := C.libusb_control_transfer( d.handle, diff --git a/usb/usb.go b/usb/usb.go index 8b719ad..3df8bcc 100644 --- a/usb/usb.go +++ b/usb/usb.go @@ -5,13 +5,15 @@ package usb import "C" import ( + "log" "reflect" "runtime" "unsafe" ) type Context struct { - ctx *C.libusb_context + ctx *C.libusb_context + done chan struct{} } func (c *Context) Debug(level int) { @@ -19,12 +21,29 @@ func (c *Context) Debug(level int) { } func NewContext() *Context { - c := new(Context) + c := &Context{ + done: make(chan struct{}), + } if errno := C.libusb_init(&c.ctx); errno != 0 { panic(usbError(errno)) } + go func() { + for { + select { + case <-c.done: + return + default: + } + if errno := C.libusb_handle_events(c.ctx); errno < 0 { + log.Printf("handle_events: error: %s", usbError(errno)) + continue + } + log.Printf("handle_events returned") + } + }() + // This doesn't seem to actually get called. Sigh. runtime.SetFinalizer(c, (*Context).Close) @@ -73,6 +92,7 @@ func (c *Context) ListDevices(each func(desc *Descriptor) bool) ([]*Device, erro } func (c *Context) Close() error { + close(c.done) if c.ctx != nil { C.libusb_exit(c.ctx) }