I am attempting to interface with the PS3's DS3 controller. I have managed to do so in C#
using an implementation of libusb
but decided to move my implementation to java
. Unfortunately my move to java has not been so smooth. The device seems to be found in the device list but when I attempt to open it I get the following error " USB error 4: Unable to 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();
}
}
LibUsb.freeDeviceList(list, true);
That true
is the problem. "final boolean unrefDevices" is shown in javadoc. Your code is releasing the Device before you have a chance to open it.
Just changing to false it 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With