现在
transferred
获得正确的数据大小,但缓冲区中没有字节,为什么?
public static void handle(short vid, short pid) {
Device device = findDevice(vid, pid);
Pair pair = findBulkInEndpoint(device, LibUsb.TRANSFER_TYPE_BULK);
if (pair == null) {
System.out.println("No bulk - in endpoint found.");
return;
}
int result;
DeviceHandle handle = new DeviceHandle();
result = LibUsb.open(device, handle);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to open device", result);
}
try {
result = LibUsb.claimInterface(handle, pair.interfaceDescriptor.iInterface());
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to claim interface", result);
}
boolean running = true;
while (running) {
ByteBuffer buffer = BufferUtils.allocateByteBuffer(1024).order(ByteOrder.LITTLE_ENDIAN);
IntBuffer transferred = IntBuffer.allocate(1);
result = LibUsb.bulkTransfer(handle, pair.endpointDescriptor.bEndpointAddress(), buffer, transferred, 10000);
if (result == 0) {
int len = transferred.get();
System.out.println("Read " + len);
buffer.flip();
byte[] bytes = new byte[len];
buffer.get(bytes, 0, len); //limit=0, position=0, throw BufferUnderflowException
System.out.println(new String(bytes));
} else {
throw new LibUsbException("Bulk transfer error", result);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
} finally {
LibUsb.close(handle);
}
}
您可能想尝试JavaDoesUSB。使用起来更加方便。
下面的代码假设接口号和端点号是已知的,这是已知设备的情况。如果需要的话也可以检测到。
int INTERFACE_NO = 1;
int ENDPOINT_IN = 1;
public static void handle(int vid, int pid) {
var device = Usb.findDevice(vid, pid).get();
device.open();
device.claimInterface(INTERFACE_NO);
boolean running = true;
while (running) {
var bytes = device.transferIn(ENDPOINT_IN);
System.out.println(new String(bytes, StandardCharsets.UTF_8));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
device.close();
}
请注意,JavaDoesUSB 是使用 Foreign Function & Memory API 构建的。所以它至少需要 Java 22。