libusb无法取消初始化上下文

时间:2017-01-10 14:56:54

标签: java usb libusb

我需要一些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);
}

}

有什么建议吗?

1 个答案:

答案 0 :(得分: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