我花了相当多的时间试图找出使用 usb4java (Libusb) 的低级函数连续读取大量数据的最佳方法。
在全速设备中,我需要读取的数据量是 640kbyte/s,理论上是可能的,而且我应该使用不到一半的可用带宽。我遇到的问题是我正在读取的数据有可能来自丢失或损坏的数据的故障。
我已经尝试过同步和异步,结果相似。在这里,我发布了我在异步模式下用来执行此操作的代码,不胜感激。
public Void doInBackground() {
loop = true;
handle = comm_device_async.gethandle();
buffer = BufferUtils.allocateByteBuffer(PacketSize).order(ByteOrder.LITTLE_ENDIAN);
Transfer transfer = LibUsb.allocTransfer();
LibUsb.fillBulkTransfer(transfer, handle, IN_ENDPOINT, buffer, read_callback, null, TIMEOUT);
int result = LibUsb.submitTransfer(transfer);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to submit transfer", result);
}
while (loop) {
synchronized (synchObj) {
while (!transfercompleted) {
try {
synchObj.wait();
} catch (InterruptedException ex) {
Logger.getLogger(GraphPanel_JChart2D.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
transfercompleted = false;
multipledatashort[readcyclecount] = read_callback_data;
readcyclecount++;
if (readcyclecount == readcycles) {
synchronized (dataListShort) {
dataListShort.add(multipledatashort);
dataListShort.notify();
}
readcyclecount = 0;
}
}
return null;
}
TransferCallback read_callback = new TransferCallback() {
ByteBuffer buffer;
long startTime = 0;
@Override
public void processTransfer(Transfer transfer) {
System.out.println("ReadCallback loop time " + (System.nanoTime() / 1000 - startTime));
startTime = System.nanoTime() / 1000;
read_callback_data = new short[transfer.buffer().capacity() / 2];
for (int i = 0; i < read_callback_data.length; i++)
read_callback_data[i] = transfer.buffer().getShort();
synchronized (synchObj) {
transfercompleted = true;
synchObj.notify();
}
buffer = BufferUtils.allocateByteBuffer(PacketSize).order(
ByteOrder.LITTLE_ENDIAN);
LibUsb.fillBulkTransfer(transfer, collectWorker_usb4java_async_fast.handle, IN_ENDPOINT, buffer,
read_callback, null, TIMEOUT);
int result = LibUsb.submitTransfer(transfer);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to submit transfer", result);
}
}
};