Android data receiving via USB OTG

77 Views Asked by At

I have a USB device that is connected to the phone and the device sends data to the phone. The problem is that the phone keeps receiving (every 16 milliseconds) 2 bytes of data (1, 96) via usb, but it is not sent by the software on the device. If the device sends a message, these 2 bytes are included at the beginning of the message. So if the device sends a message like this: 2 5 4 1 3 It arrives like this: 1 96 2 5 4 1 3. This makes data processing quite difficult, especially if, for example, the package is fragmented because the received messages' length is not predictable so I have to handle it with timer.

I read a bit about FTDI devices and I've found this: The first 2 bytes of every packet are used as status bytes for the driver. This status is sent every 16 milliseconds, even when no data is present in the device. Now I know what is these two bytes but can I somehow disable it?

The code I use for data receiving:

private void ReceiveDataThread()
{
byte[] buffer = new byte[BUFFER_SIZE];

while (isRunning)
{
    int receivedBytes = usbConnection.BulkTransfer(usbEndpointIn, buffer, BUFFER_SIZE, 0);
    if (receivedBytes > 0)
    {
            byte[] receivedData = new byte[receivedBytes];
            Array.Copy(buffer, receivedData, receivedBytes);
            DataReceived?.Invoke(this, receivedData);
    }
}
}
1

There are 1 best solutions below

0
Jianwei Sun - MSFT On

According to snachmsm, cause you use:

Array.Copy(buffer, receivedData, receivedBytes);

It copies whole data. So you can modify it to this:

if (receivedBytes > 2)
{
    byte[] receivedData = new byte[receivedBytes-2];
    Array.Copy(buffer, 2, receivedData, 0, receivedBytes-2);
    ...
}

It can remove the first 2 bytes and copy buffer to receivedData from Index 2.