我正在使用连接到FT232 USB芯片的USB Host API开发Android应用程序。 FT232设备将大量样本(20KBps)传输到Android SBC。但是,我注意到偶尔会丢失一些样品。我连接了USB分析仪,以查看两个端点之间的通信。我可以看到一些USB数据包的延迟。
FT232 USB数据包是64KB,我的线程重复调用bulktransfer api来检索下一个数据包并填充循环缓冲区。我有另一个线程从循环缓冲区读取数据。读取和写入循环缓冲区时,两个线程都是同步的。 我不确定读取线程是否阻塞太长,导致写入线程错过了一些数据包?有关改进的任何想法或建议吗?
波特率460800,8,N,1
以下是我的代码段。
public class UsbClass {
private static final int MAX_BUFFER_SIZE = 512000;
private byte[] circularBuffer = new byte[MAX_BUFFER_SIZE];
private int writeIndex=0;
private int readIndex=0;
ReadUsbThread usbReadThread;
ParseDataThread parseThread;
public UsbClass() {
super();
usbReadThread = new ReadUsbThread();
usbReadThread.start();
parseThread = new ParseDataThread();
parseThread.start();
}
// Read data from USB endpoint
public class ReadUsbThread extends Thread {
public ReadUsbThread() {
}
int length;
byte[] buffer = new byte[64];
public void run() {
while(true)
{
length = conn.bulkTransfer(epIN, buffer, buffer.length, 100);
if(length>2)
{
writeCircularBuffer(buffer, length);
}
else
Thread.sleep(1);
}
}
}
// Parse the data from circular buffer
public class ParseDataThread extends Thread {
public ParseDataThread() {
}
byte[] data;
public void run() {
while(true)
{
data = readCircularBuffer(1);
// do something with data
}
}
}
// Write to circular buffer
public synchronized void writeCircularBuffer(byte[] buffer, int length)
{
for(int i = 2; i<length; i++)
{
circularBuffer[writeIndex++] = buffer[i];
if(writeIndex == MAX_BUFFER_SIZE)
writeIndex=0;
}
}
// Read from circular buffer
public synchronized byte[] readCircularBuffer(int length)
{
byte[] buffer = new byte[length];
for(int i = 0; i<length; i++)
{
buffer[i] = circularBuffer[readIndex++];
if(readIndex == MAX_BUFFER_SIZE)
readIndex=0;
}
return buffer;
}
}