I'm developing an Android application using the USB Host API connected to a FT232 USB chip. The FT232 device transmits large amounts of samples (20KBps) to the Android SBC. However, I noticed that occasionally I'm losing some samples. I have a USB analyzer connected to see the communication between the two endpoints. I can see a delay in some of the USB packets.
The FT232 USB packets are 64KB and my thread is repeatedly calling the bulktransfer api to retrieve the next packet and to fill the circular buffer. I have another thread that is reading the data from the circular buffer. Both threads are synchronized when reading and writing to the circular buffer. I'm not sure if the reading thread is blocking too long, which causes the writing thread to the miss some of the packets? Any ideas or suggestions on improving this?
Baud Rate 460800, 8, N, 1
Below is my code snippet.
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;
}
}