简体   繁体   English

捆绑inputStream.read消息

[英]Bundling inputStream.read messages

I am using the Android Bluetooth Chat sample code to chat (send commands + receive responses) with a bluetooth device. 我正在使用Android蓝牙聊天示例代码与蓝牙设备聊天(发送命令+接收响应)。 It is working fine when I send a command, and I receive a response from the device that is passed to message handler. 当我发送命令时,它工作正常,并且收到了从设备传递到消息处理程序的响应。 The issue I am having is the response is cut up into pieces. 我遇到的问题是响应被分成几部分。

Example: 例:

I send the string "{Lights:ON}\\n" and my activity correctly displays Me: {Lights:ON} . 我发送了字符串"{Lights:ON}\\n" ,我的活动正确显示了Me: {Lights:ON} The device lights turn on and it returns it's response "{FLash_Lights:ON}\\n" . 设备指示灯亮起,并返回响应"{FLash_Lights:ON}\\n" However my activity displays DeviceName: {Fla , new line, DeviceName: sh_Lights:ON} (or some variation ect). 但是,我的活动显示DeviceName: {Fla ,换行, DeviceName: sh_Lights:ON} (或某些变化形式)。

Now I am new to threading and bluetooth in general but I have traced the issue down to the connected thread class (in bluetoothchatservice), more specifically the public void run() to listen to incoming bytes. 现在,我是线程和蓝牙的新手,但我已将问题归结为连接的线程类(在bluetoothchatservice中),更具体地说是侦听传入字节的public void run()

     public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[9000];
            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(BluetoothActivity.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    // Start the service over to restart listening mode
                    BluetoothThreading.this.start();
                    break;
                }
            }
        }

I understand that this was made to listen for any bytes coming in (as a chat service). 我了解这是为了侦听传入的任何字节(作为聊天服务)。 However I know exactly what I am writing to the device and I know the response I should be receiving, what I would like to do is bundle this response before sending it back to the mHandler. 但是我确切地知道我正在写的设备,我知道我应该收到的响应, 我想做的是在将此响应发送回mHandler之前将其打包。

Any help with this would be amazing! 任何帮助将是惊人的! Thank you! 谢谢!

Note : I know that using this sample as a way of sending a command to a device and receiving a response is a bit overkill (especially since I know exactly what I'm sending and need to receive directly afterwards). 注意 :我知道使用此示例作为向设备发送命令并接收响应的方法有点过大(特别是因为我确切知道我要发送的内容,之后需要直接接收)。 It would be great to be pointed to any simplified sample you may know of as well. 指出您可能还知道的任何简化样本,将是非常棒的。 At the end of the day I just need to search, connect to device, push button to send byte[] to device, receive byte[] response, print + store it. 在一天结束时,我只需要搜索,连接到设备,按下按钮即可将byte []发送到设备,接收byte []响应,打印并存储它。

The 'read()' is blocking call and returns when few bytes are received over bluetooth. “ read()”正在阻止调用,并在通过蓝牙接收到少量字节时返回。 The count of 'few' is not fixed, and that's the reason why incoming response appears to be broken into pieces. “很少”的计数不是固定的,这就是传入响应似乎被分解成碎片的原因。 Therefore to retrieve complete response, all these pieces must be joined together. 因此,要获取完整的响应,必须将所有这些部分连接在一起。

Where the response stream is terminated with a specific character, then following code logic can accumulate the bytes arriving before the terminating character. 在响应流以特定字符终止的情况下,随后的代码逻辑可以累加在终止字符之前到达的字节。 And once terminating character is detected, the accumulated response is sent to main activity. 并且一旦检测到终止字符,则将累积的响应发送到主要活动。 (Note that in the code snippet below, the terminating character used is 0x0a). (请注意,在下面的代码段中,使用的终止字符为0x0a)。

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

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

        btInStream.write(Arrays.copyOf(buffer, bytes) );

        if (buffer[bytes - 1] == 0x0a){
            mHandler.obtainMessage(MainActivity.MESSAGE_READ, btInStream.size(), 0,btInStream.toByteArray());
            .sendToTarget();
            btInStream.reset();
        }
    } catch (IOException e) {
        Log.e(TAG, "disconnected", e);
        connectionLost();
        // Start the service over to restart listening mode
        BluetoothThreading.this.start();
        break;
    }
}
}

Also note that code is not tested but proposed as one approach to resolve the issue mentioned in the question. 还要注意,代码未经测试,但被提议作为解决问题中提到的问题的一种方法。 Mat be it will need corrections at few places. 可能需要在几个地方进行更正。 Please test and inform the results. 请测试并告知结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM