java - libusb 无法取消初始化上下文

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

}

有什么建议吗?

最佳答案

您没有初始化上下文,这就是您在尝试取消初始化上下文时收到错误的原因,请参阅 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 协议(protocol)的更深入信息,请参阅 http://www.beyondlogic.org/usbnutshell/usb1.shtml

关于java - libusb 无法取消初始化上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41571769/

相关文章:

java - 向JFrame添加graphics2d

python - 使用 NI-488.2 将 GPIB 转换为 USB

macos - 如果设备自启动后插入,IOHIDDeviceRegisterInputValueCallback 将失败

windows - libusb-win32 : Automated installation of a driver filter

c++ - 如何将 libusb 与 libevent 一起使用?

Java:串行线程限制问题

java - 在 Java 中使用 Hibernate 插入 70000 条记录时出现网关超时错误

java - 为什么这种迭代的 trie-traversal 不能在查询时产生正确的单词?

embedded - Linux 上的 USB 软件环回设备

c - C 中的结构体定义?