doc
doc

Reputation: 817

InputStream.available() reports no bytes when listening to Bluetooth RFCOMM server that constantly streams data

I am trying to write a simple script in Java to read data from a bluetooth device that spits out a constant stream of data. I know the device is working, because I can solve my problem using Python, but I want to use Java eventually.

I have some sample code, but it hangs on the read command.

// Ref http://homepages.ius.edu/rwisman/C490/html/JavaandBluetooth.htm
import java.io.*;
import javax.microedition.io.*;
//import javax.bluetooth.*;

public class RFCOMMClient {
    public static void main(String args[]) {
    try {
        StreamConnection conn = (StreamConnection) Connector.open(
        "btspp://00078093523B:2", Connector.READ, true);

        InputStream is = conn.openInputStream();

        byte buffer[] = new byte[8];
        try {
            int bytes_read = is.read(buffer, 0, 8);
            String received = new String(buffer, 0, bytes_read);
            System.out.println("received: " + received);
        } catch (IOException e) {
            System.out.println(" FAIL");
            System.err.print(e.toString());
        }
        conn.close();
    } catch (IOException e) {
        System.err.print(e.toString());
    }
}

}

Note that the problem seems to be that the read() call believes there is no data available. However, the bluetooth device constantly spits out data (it is a sensor). Here is my Python code which does work:

In [1]: import bluetooth

In [2]: address = "00:07:80:93:52:3B"

In [3]: s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

In [4]: s.connect((address,1))

In [5]: s.recv(1024)
Out[5]: '<CONFIDENTIALDATAREMOVED>'

Please help,

Thanks!

Upvotes: 2

Views: 1121

Answers (1)

mcfinnigan
mcfinnigan

Reputation: 11638

read will block and wait for data; a better idiom would be to use available():

int bytesToRead = is.available();
if(bytesToRead > 0)
    is.read(buffer, 0, bytesToRead);
else
    // wait for data to become available

Upvotes: 1

Related Questions