发布
社区首页 >问答首页 >usb4java:USB错误4:没有这样的设备(它可能已经断开连接)?

usb4java:USB错误4:没有这样的设备(它可能已经断开连接)?

提问于 2025-02-11 17:00:10
回答 1关注 0查看 28

资源已经释放,还是open失败。

代码语言:javascript
代码运行次数:0
复制
LibUsb.freeDeviceList(list, true);报错:USB error 4: No such device (it may have been disconnected)
代码语言:javascript
代码运行次数:0
复制
LibUsb.freeDeviceList(list, false);报错:USB error 12: Operation not supported or unimplemented on this platform
代码语言:javascript
代码运行次数:0
复制
public class Test3 {
    private static final short idVendor = 0x4080;
    private static final short idProduct = 0x00F0;


    public static void main(String[] args) {

        Context context = new Context();
        int result = LibUsb.init(context);
        if(result != LibUsb.SUCCESS) {
            throw new LibUsbException("Unable to initialize libusb.", result);
        }

        //获取对应的USB
        Device device = findDevice(context);

        System.out.println(device);

        //打开设备
        DeviceHandle handle = new DeviceHandle();
        result = LibUsb.open(device, handle);

        if(result != LibUsb.SUCCESS) {
            throw new LibUsbException(result);
        }


    }

    public static Device findDevice(Context context){
        DeviceList list = new DeviceList();
        int result = LibUsb.getDeviceList(context, list);

        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);
                }

                System.out.println("设备: VID="+descriptor.idVendor()+", PID="+descriptor.idProduct());
                System.out.printf("设备: VID=0x%04X, PID=0x%04X%n", descriptor.idVendor(), descriptor.idProduct());
                System.out.println("-------------------------------");

                if (descriptor.idVendor() == idVendor && descriptor.idProduct() == idProduct){

                    return device;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            // 释放资源
            LibUsb.freeDeviceList(list, true);
            LibUsb.exit(context);
        }
        return null;
    }
}
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档