Ejemplo n.º 1
0
// RegisterHotplugCallback registers a hotplug callback function. The callback will fire when
// a matching event occurs on a device matching vendorID, productID and class.
// HOTPLUG_ANY can be used to match any vendor ID, product ID or device class.
// If enumerate is true, the callback is called for matching currently attached devices.
// It returns a function that can be called to deregister the callback.
// Returning true from the callback will also deregister the callback.
// Closing the context will deregister all callbacks automatically.
func (c *Context) RegisterHotplugCallback(vendorID int, productID int, class int, enumerate bool, callback HotplugCallback, event HotplugEvent, events ...HotplugEvent) (func(), error) {
	var handle hotplugHandle
	data := hotplugCallbackData{
		f:   callback,
		ctx: c,
	}
	// store the data in go memory, since we can't pass it to cgo.
	dataID := callbacks.add(&data)
	c.addCallback(dataID)

	var enumflag C.libusb_hotplug_flag
	if enumerate {
		enumflag = 1
	} else {
		enumflag = 0
	}

	for _, e := range events {
		event |= e
	}

	res := C.attachCallback(c.ctx, C.libusb_hotplug_event(event), enumflag, C.int(vendorID), C.int(productID), C.int(class), dataID, (*C.libusb_hotplug_callback_handle)(&handle))
	if res != C.LIBUSB_SUCCESS {
		callbacks.remove(dataID)
		c.removeCallback(dataID)
		return nil, usbError(res)
	}
	return func() {
		C.libusb_hotplug_deregister_callback(c.ctx, C.libusb_hotplug_callback_handle(handle))
		callbacks.remove(dataID)
		c.removeCallback(dataID)
	}, nil
}
Ejemplo n.º 2
0
func (ctx *Context) RegisterHotplugCallback(vendor_id int, product_id int, class int, callback HotplugCallback, events HotplugEvent, enumerate bool) (HotplugHandle, error) {
	mutexHotplugCallbackMap.Lock()
	defer mutexHotplugCallbackMap.Unlock()
	var handle HotplugHandle
	data := hotplugCallbackData{
		f: callback,
	}
	dataPtr := unsafe.Pointer(&data)

	var enumflag C.libusb_hotplug_flag
	if enumerate {
		enumflag = 1
	} else {
		enumflag = 0
	}

	res := C.attachCallback(ctx.ctx, C.libusb_hotplug_event(events), enumflag, C.int(vendor_id), C.int(product_id), C.int(class), dataPtr, (*C.libusb_hotplug_callback_handle)(&handle))
	if res != C.LIBUSB_SUCCESS {
		return 0, usbError(res)
	}
	data.h = handle
	// protect the data from the garbage collector
	hotplugCallbackMap[handle] = &data
	return handle, nil
}