我正在尝试与PS3的DS3控制器连接。我已使用C#
的实现在libusb
中设法完成了此操作,但我决定将我的实现移至java
。不幸的是,我转向java并不是那么顺利。该设备似乎在设备列表中找到,但当我尝试打开它时,我收到以下错误“USB错误4:无法打开USB设备:没有这样的设备(可能已断开连接)”
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();
}
}
答案 0 :(得分:8)
LibUsb.freeDeviceList(list,true);
true
是问题所在。 “final boolean unrefDevices”显示在javadoc中。您的代码在您有机会打开它之前正在释放它。