蓝牙ASCII协议

时间:2011-04-30 02:24:06

标签: android bluetooth communication

我正在尝试与蓝牙设备通信。我在设备上的信息表明

“通信协议是ASCII,逗号分隔输出值。消息由回车符和换行符对终止。当使用终端仿真器保存为文件时,这些结果可以读入Excel电子表格。”

如何从此设备发送和接收?我尝试过使用InputStreamReader和OutputStreamWriter,但我认为这不起作用。

编辑:

用于发送我正在尝试的数据:

public void send(String s){
            try {
                writer.write(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

,其中

try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            inStream = tmpIn;
            writer = new OutputStreamWriter(tmpOut);

你也可以看到我在哪里使用inStream这是一个简单的InputStream。我也尝试过InputStreamReader,但我只是回来了随机字符。使用InputStream,无论发送什么设备,我只读4个字节,所以我不确定发送是否正常。

我应该使用什么?谢谢!

2 个答案:

答案 0 :(得分:0)

您应该查看IO Streams上的Java文档以了解整体情况。

对于检索,我假设您使用的是InputStream.read()方法,它一次读取一个字节。要一次检索几个字节,您应该使用byte[]缓冲区。但那不是你的情况,只是仅供参考。

在您的情况下,您不需要使用InputStream方法,而是使用InputStreamReader,因为 Reader对字符进行操作,而不是字节。正如您在协议描述的引用中所述,您有单独的ASCII行。在这种情况下,BufferedReader很方便,因为它有readLine()方法。

所以你可以

    in = socket.getInputStream();
    InputStreamReader isr = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(isr);

然后

    String line = br.readLine();

要发送数据,您应该使用OutputStreamWriter。

请记住:请在使用后关闭溪流!在finaly{}条款中

答案 1 :(得分:0)

我正在跟进,以防其他人遇到同样的问题。我遇到的一个问题是我试图与之通信的设备正在等待/ n和/ r的特定顺序,并且如果不正确则会锁定,所以我不知道它是否正常工作。

以下是我用于发送和接收的代码,我现在已在几台设备上使用它,它似乎运行良好。

    /**
 * 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 socket;
    private final InputStream inStream;
    private final OutputStream outStream;
    private final DataInputStream datIn;

    public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "create ConnectedThread");
        this.socket = 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);
        }

        inStream = tmpIn;
        outStream = tmpOut;
        datIn = new DataInputStream(inStream);
    }

    public void run() {
        Log.i(TAG, "BEGIN ConnectedThread");
        Bundle data = new Bundle();

        // Keep listening to the InputStream while connected
        while (true) {
            Log.i(TAG, "Reading...");
            try {
                // Read from the InputStream
                String results;
                Log.i(TAG, "Recieved:");
                results = datIn.readLine();
                Log.i(TAG, results);

             // Send the obtained bytes to the UI Activity
                data.putString("results", results);
                Message m = handler.obtainMessage(); // get a new message from the handler
                m.setData(data); // add the data to the message
                m.what = MESSAGE_READ;
                handler.sendMessage(m);
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                handler.obtainMessage(MESSAGE_DISCONNECTED).sendToTarget();
                setState(STATE_NONE);
                // Start the service over to restart listening mode
                break;
            }
        }
    }

    /**
     * Write to the connected OutStream.
     * @param buffer  The bytes to write
     */
    public void write(byte[] buffer) {
        try {
            outStream.write(buffer);
            Log.i(TAG, "Sending: " + new String(buffer));

        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
}

/**
 * Write to the ConnectedThread in an unsynchronized manner
 * @param out The bytes to write
 * @see ConnectedThread#write(byte[])
 */
public void send(byte[] out) {
    // Create temporary object
    ConnectedThread r;
    // Synchronize a copy of the ConnectedThread
    synchronized (this) {
        if (state != STATE_CONNECTED) return;
        r = connectedThread;
    }
    // Perform the write unsynchronized
    r.write(out);
}