蓝牙Android SPP,将命令串口发送到设备?

时间:2012-04-10 18:56:22

标签: android bluetooth serial-port spp

----------------------编辑--------------------- -----
虽然有点进步,但不是解决方案。如果我在要发送的命令之间插入以下代码,至少允许命令有时间在远程端处理(但这仍然不是正确的方法,正确的方法是等待在发送另一个命令之前回复“>”)...

android.os.SystemClock.sleep(150);

虽然在systemclock处于休眠状态期间,侦听器线程被阻塞,因此调制解调器的输入不会在发送代码序列之后附加到文本视图,这是不太理想的。虽然,睡眠不是正确的方法,我需要找到一个更好的方法,所以我不发送新的命令,直到“>”结果从另一端的设备返回。当我完成这段代码时,我将需要一种方法来处理输入,所以如果我考虑它,睡眠确实没有进展。插入睡眠的例子:

    sendData("enable");
    android.os.SystemClock.sleep(150);
    sendData("password");        
    android.os.SystemClock.sleep(150); 
    sendData("conf t");        
    android.os.SystemClock.sleep(150);     
    sendData("interface eth0");        
    android.os.SystemClock.sleep(150);    
    //etc...etc...etc... 

----------------------以下原帖------------------- -------

我正在使用来自Matt Bell博客的优雅代码片段,位于此处: http://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/

来源位于: http://project-greengiant.googlecode.com/svn/trunk/Blog/Android%20Arduino%20Bluetooth

在没有严重破坏代码的情况下,我试图以一种方式优雅地将命令串行发送到连接的调制解调器,每次等到收到完整的响应,然后再发送下一个命令。 (我知道这不是Android的做事方式,我可以使用其他语言处理心跳)。

到目前为止,这是我正在使用的内容(你会看到我没有做到这一点,实际上这段代码非常有效,直到我需要等待第一个命令完成才发送更多内容命令)。我省略了尽可能多的与此问题无关的代码。提前谢谢。

    package Android.Arduino.Bluetooth;        

    import java.io.IOException;        
    import java.io.InputStream;        
    import java.io.OutputStream;        
    import java.util.Set;        
    import java.util.UUID;        
    import android.app.Activity;        
    import android.bluetooth.BluetoothAdapter;        
    import android.bluetooth.BluetoothDevice;        
    import android.bluetooth.BluetoothSocket;        
    import android.content.Intent;        
    import android.os.Bundle;        
    import android.os.Handler;        
    import android.widget.TextView;        


    public class BluetoothTest extends Activity        
    {        
        TextView myLabel;        
        BluetoothAdapter mBluetoothAdapter;        
        BluetoothSocket mmSocket;        
        BluetoothDevice mmDevice;        
        OutputStream mmOutputStream;        
        InputStream mmInputStream;        
        int counter;        
        Thread workerThread;        
        byte[] readBuffer;        
        int readBufferPosition;        
        volatile boolean stopWorker;        

        @Override        
        public void onCreate(Bundle savedInstanceState)        
        {        
            super.onCreate(savedInstanceState);        
            setContentView(R.layout.main);        

            myLabel = (TextView)findViewById(R.id.label);        

                        try         
                        {        
                            findBT();        
                            openBT();        
                            sendData("enable");        
                          //insert some code to wait for response before sending (or handle that in the above line, or otherwise)
                            sendData("password");        
                          //insert some code to wait for response before sending (or handle that in the above line, or otherwise)        
                            sendData("conf t");        
                          //insert some code to wait for response before sending (or handle that in the above line, or otherwise)        
                            sendData("interface eth0");        
                          //insert some code to wait for response before sending (or handle that in the above line, or otherwise)        
                          //etc...etc...etc...        
                        }        
                        catch (IOException ex) { }                            

        }        

        }        

        void openBT() throws IOException        
        {        
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID        
            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);                
            mmSocket.connect();        
            mmOutputStream = mmSocket.getOutputStream();        
            mmInputStream = mmSocket.getInputStream();        
            beginListenForData();        
            myLabel.append("Bluetooth Opened" + "\n");        
        }        

        void beginListenForData()        
        {        
            final Handler handler = new Handler();         
            final byte delimiter = 62; //This is the ASCII code for a > character indicating all data received        

            stopWorker = false;        
            readBufferPosition = 0;        
            readBuffer = new byte[1024];              

            workerThread = new Thread(new Runnable()        
            {        
                public void run()        
                {                        

                while(!Thread.currentThread().isInterrupted() && !stopWorker)        
                   {        
                        try         
                        {        
                            int bytesAvailable = mmInputStream.available();                                
                            if(bytesAvailable > 0)        
                            {        
                                byte[] packetBytes = new byte[bytesAvailable];        
                                mmInputStream.read(packetBytes);        
                                for(int i=0;i<bytesAvailable;i++)        
                                {        
                                    byte b = packetBytes[i];        
                                    if(b == delimiter)        
                                    {        
                                        byte[] encodedBytes = new byte[readBufferPosition];        
                                        System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);        
                                        final String data = new String(encodedBytes, "US-ASCII");        
                                        readBufferPosition = 0;        

                                        handler.post(new Runnable()        
                                        {        
                                            public void run()        
                                            {                                                    
                                                myLabel.append(data);                                         
                                            }        
                                        });        
                                    }        
                                    else        
                                    {        
                                        readBuffer[readBufferPosition++] = b;        
                                    }        
                                }        
                            }        
                        }        
                        catch (IOException ex)         
                        {        
                            stopWorker = true;        
                        }        
                   }        

                }        
            });        

            workerThread.start();        
        }        

        void sendData(String msg0) throws IOException        
        {        
            msg0 += "\r";        
            mmOutputStream.write(msg0.getBytes());        
            myLabel.append("Data Sent" + "\n");        
        }        

    }        

1 个答案:

答案 0 :(得分:2)

我认识到这是一个非常古老的问题。但是,由于我正在开发一个类似的应用程序,我以不同的方式解决了它,它可能会有所帮助。

您可以通过标志实现发送/响应逻辑,而不是发送之间的延迟。所以在开始时连接是initial。您发送enable并将您的旗帜设为enableRequested。然后让你的听众等待回应。继续发送password后,将标志设置为passwordSent并再次释放该线程。

所以我建议不要在onCreate中执行此操作,而是触发从onCreate连接的线程。这应该很好。