【问题标题】:libusb cannot deinitialize contextlibusb 无法取消初始化上下文
【发布时间】:2017-01-10 14:56:54
【问题描述】:

我需要一些关于 Java 中 IllegalStateException 的帮助。 我有一个应该从 USB 设备读取数据的源代码。

那段代码还没写完,但是我已经收到如下错误报告

Exception in thread "main" java.lang.IllegalStateException: default context is not initialized at org.usb4java.Libusb.exit(Native Method) at testnew.main(testnew.java:122) 

第 122 行是LibUsb.exit(null)

代码如下

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import javax.usb.UsbConfiguration;
import javax.usb.UsbDevice;
import javax.usb.UsbDeviceDescriptor;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;
import javax.usb.UsbHostManager;
import javax.usb.UsbHub;
import javax.usb.UsbInterface;
import javax.usb.UsbInterfacePolicy;
import javax.usb.UsbNotActiveException;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;

import org.usb4java.BufferUtils;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;

public class testnew {

private final static short VENDOR_ID = 0x0403;
private final static short PRODUCT_ID = 0x6001;
private static byte IN_ENDPOINT = (byte) 0x81;
private static long TIMEOUT = 5000;
private final static int INTERFACE = 0;
private final static Object CONNECT_HEADER = 000;
private final static Object CONNECT_BODY = 000;

public static UsbDevice getHygrometerDevice(UsbHub hub) {
    UsbDevice launcher = null;

    for (Object object : hub.getAttachedUsbDevices()) {
        UsbDevice device = (UsbDevice) object;
        if (device.isUsbHub()) {
            launcher = getHygrometerDevice((UsbHub) device);
            if (launcher != null)
                return launcher;
        } else {
            UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
            if (desc.idVendor() == VENDOR_ID && desc.idProduct() == PRODUCT_ID)
                return device;
        }
    }
    return null;
}

public static char readKey() {
    try {
        String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
        if (line.length() > 0)
            return line.charAt(0);
        return 0;
    } catch (IOException e) {
        throw new RuntimeException("Unable to read key", e);
    }
}

public static ByteBuffer read(DeviceHandle handle, int size) {
    ByteBuffer buffer = BufferUtils.allocateByteBuffer(size).order(ByteOrder.LITTLE_ENDIAN);
    IntBuffer transferred = BufferUtils.allocateIntBuffer();
    int result = LibUsb.bulkTransfer(handle, IN_ENDPOINT, buffer, transferred, TIMEOUT);
    if (result != LibUsb.SUCCESS) {
        throw new LibUsbException("Unable to read data", result);
    }
    System.out.println(transferred.get() + " bytes read from device");
    return buffer;
}

public static void main(String[] args) {
    // Search for the missile launcher USB device and stop when not found
    UsbDevice device;
    try {
        device = getHygrometerDevice(UsbHostManager.getUsbServices().getRootUsbHub());

        if (device == null) {
            System.err.println("Missile launcher not found.");
            System.exit(1);
            return;
        }

        // Claim the interface
        UsbConfiguration configuration = device.getUsbConfiguration((byte) 1);
        UsbInterface iface = configuration.getUsbInterface((byte) INTERFACE);

        iface.claim(new UsbInterfacePolicy() {
            @Override
            public boolean forceClaim(UsbInterface usbInterface) {
                return true;
            }
        });

        iface.getUsbEndpoint(IN_ENDPOINT).getUsbPipe().addUsbPipeListener(new UsbPipeListener() {

            @Override
            public void errorEventOccurred(UsbPipeErrorEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void dataEventOccurred(UsbPipeDataEvent arg0) {
                for (byte b : arg0.getData())
                    System.out.print(b);
                System.out.print("\n");
            }
        });
        ;
    } catch (UsbNotActiveException | UsbDisconnectedException | UsbException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    // Deinitialize the libusb context
    LibUsb.exit(null);
}

}

有什么建议吗?

【问题讨论】:

    标签: java usb libusb


    【解决方案1】:

    您没有初始化上下文这就是为什么您在尝试取消初始化时收到错误,请参阅http://www.programcreek.com/java-api-examples/index.php?api=org.usb4javaLibUsb 示例 17

    public static void main(String[] args)
    {
      //Initialize the libusb context
    
    int result = LibUsb.Init(null);
    if (result != LibUsb.SUCCESS){
         throw new LibUsbException("Unable to initialze libusb",result);
    }
    [...]
    

    如何打开管道取决于你要选择什么传输类型(批量传输、同步传输、异步传输),见http://usb4java.org/quickstart/javax-usb.html

    你可以使用同步传输(复制自http://usb4java.org/quickstart/javax-usb.html

    UsbEndpoint endpoint = iface.getUsbEndpoint((byte) 0x83);
    UsbPipe pipe = endpoint.getUsbPipe();
    pipe.open();
    try
    {
        byte[] data = new byte[8];
        int received = pipe.syncSubmit(data);
        System.out.println(received + " bytes received");
    }
    finally
    {
        pipe.close();
    }
    

    有 IN 端点和 OUT 端点,你写入 OUT 并从 IN 读取。控制转移到 EP0。所有 USB 通信均由主机设备发起,这意味着 USB 设备甚至无法发起通信。

    有关 USB 协议的详细信息,请参阅http://www.beyondlogic.org/usbnutshell/usb1.shtml

    【讨论】:

    • 好的,知道了。那是一个简单的错误..我该如何继续?我想从管道中读出数据..但首先我必须打开管道..在哪里?以及如何读出数据?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多