Alex Rivera | Logout

Android InputStream dropping first two bytes (modified BluetoothChat)

Asked 2012-09-02T20:55:21.440
8

I've used code from BluetoothChat example to send and receive byte data from a Bluetooth Scale. The scale receives the command from the device, then sends back a byte array. {2,198,48,48,48,48,199,3} The 2 = STX, and the 198 = packet start, and 199 = packet end, and 3 = ETX in our comms protocol.

All works just fine, except that the following code in the BluetoothChatService.java reacts strangely in that it drops the first two bytes.

/**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket, String socketType) {
            Log.d(TAG, "create ConnectedThread: " + socketType);
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            final byte[] buffer = new byte[1024];
            int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);

                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
            
Edit
Report

1 Answer

0

I was in the same position as you a few weeks ago.

I discovered The read count is random when using read(buffer). So you will never truly predict how big the next data packet will be.

The simple fix for me was to read a single byte at a time using read() and add it to a local buffer until every byte is received.

Hope this helps.

answered 2013-02-06T13:16:11.667

Your Answer