我试图用Java编写一个简单的脚本来从蓝牙设备读取数据,该设备吐出恒定的数据流。我知道设备正在运行,因为我可以使用Python解决问题,但最终我想使用Java。

我有一些示例代码,但是它挂在read命令上。

// 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());
    }
}


}

请注意,问题似乎在于read()调用认为没有可用数据。但是,蓝牙设备会不断吐出数据(它是一个传感器)。这是我的Python代码,可以正常工作:

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>'


请帮忙,

谢谢!

最佳答案

读取将阻止并等待数据;更好的习惯用法是使用available():

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

07-24 19:07
查看更多