5

我正在尝试与 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();
}
}
4

2 回答 2

9

LibUsb.freeDeviceList(list, true);

true就是问题所在。“最终布尔 unrefDevices”显示在 javadoc 中。您的代码在您有机会打开设备之前释放它。

于 2015-02-26T12:39:57.367 回答
1

仅更改为 false 还不够,您还需要使用需要返回的设备调用 refDevice 示例:

    } finally {
        // Ensure the allocated device list is freed
        LibUsb.freeDeviceList(list, false);
    }

    if (deviceFound != null) {
        // Device found
        LibUsb.refDevice(deviceFound);
    }
    return deviceFound;
于 2017-08-11T15:17:01.323 回答