Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read all bytes together via Bluetooth?

I have an application that uses the bluetooth to receive some data (bytes) from other device. everything is going well, but I have a small issue on receiving the bytes all together. After receiving the bytes I show them on a Toast just to test them. When the other device sends 10 bytes together (for example: "ABCDEFGHIJ"), the program will take the first byte "A" only and show it on a Toast, then go to the second iteration and read the other 9 bytes and show "BCDEFGHIJ" on the Toast. Here is my code:

byte[] buffer = new byte[1024]; // Read 1K character at a time.
int bytes = 0; // Number of bytes.

while(true)
{
    try
    {
        // Read from the InputStream.
        bytes = bInStream.read(buffer);

        // Send the obtained bytes to the MainActivity.
        mainActivityHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
    }
    catch(IOException e)
    {
        connectionLost();
        break;
    }
}

In the MainActivity, I have:

// The Handler that gets information back from the BluetoothManager.
private final Handler handler = new Handler()
{
    @Override
    public void handleMessage(Message msg)
    {
        switch(msg.what)
        {
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;

                // construct a string from the valid bytes in the buffer.
                String readMessage = new String(readBuf, 0, msg.arg1);
                Toast.makeText(MainActivity.this, readMessage, Toast.LENGTH_SHORT).show();
                break;

            // ...
        }
    }
};

How can I receive all the bytes together?!

like image 832
Eng.Fouad Avatar asked Feb 10 '12 16:02

Eng.Fouad


1 Answers

The bluetooth connection is stream based, not packet based. There is no guarantee or attempt to preserve packetization. So any number of writes can result in any number of reads, just the stream of bytes are guaranteed to be correct. If you need to detect packets, you need to provide your own packet structure to wrap your data. For example, add a length field before each data packet so you can reconstruct on the receiving side.

like image 141
TJD Avatar answered Oct 05 '22 23:10

TJD