Usb4java USB error 4: Unable to open USB device:
I am trying to communicate with a PS3 DS3 controller. I was able to do it in C#
using the implementation libusb
, but decided to port my implementation to java
. Unfortunately my transition to java was not that smooth. The device seems to be found in the device list, but when I try to open it, I get the following error "USB error 4: Cannot open USB device: no such device (it may have been disconnected)"
public class Main {
private static final short VID = 0x054c;
private static final short PID = 0x0268;
Context context;
public Main() {
context = new Context();
int result = LibUsb.init(context);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to initialize libusb.", result);
}
ByteBuffer data = ByteBuffer.allocate(49);
DeviceHandle ds3Handle = getDeviceHandle(findDevice(VID, PID));
LibUsb.controlTransfer(ds3Handle, (byte)0xa1, (byte)0x1, (short)0x101, (short)0, data, 1000L);
LibUsb.exit(context);
}
private Device findDevice(int vid, int pid) {
Device UsbDevice = null;
DeviceList list = new DeviceList();
int result = LibUsb.getDeviceList(context, list);
if (result < 0) {
throw new LibUsbException("Unable to get device list", result);
}
try {
for(Device device: list) {
DeviceDescriptor descriptor = new DeviceDescriptor();
result = LibUsb.getDeviceDescriptor(device, descriptor);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to read device descriptor", result);
}
if (descriptor.idVendor() == vid && descriptor.idProduct() == pid) {
UsbDevice = device;
System.out.println("found");
}
}
} finally {
LibUsb.freeDeviceList(list, true);
}
return UsbDevice;
}
private DeviceHandle getDeviceHandle(Device device) {
DeviceHandle handle = new DeviceHandle();
int result = LibUsb.open(device, handle);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to open USB device", result);
}
return handle;
}
public static void main(String [] args){
new Main();
}
}
+3
source to share
2 answers
Just passing to false is not enough, you also need to call refDevice with the device you need to return Example:
} finally {
// Ensure the allocated device list is freed
LibUsb.freeDeviceList(list, false);
}
if (deviceFound != null) {
// Device found
LibUsb.refDevice(deviceFound);
}
return deviceFound;
0
source to share