Pybluez客户端到Android蓝牙套接字服务器

时间:2015-09-28 21:05:01

标签: android python sockets bluetooth

我一直试图在Android手机(作为服务器)和运行python pybluez(作为客户端)的表面专业平板电脑之间进行双向蓝牙RFCOMM通信。我的主要问题源于Python。它没有连接到我正在等待的Android手机。我手动连接了两台设备,然后启动了服务器(Android手机)。它被卡在" TrackingFlow上。收听...&#34 ;.当我运行Python脚本时,我得到以下错误。我发现了其他一些堆栈溢出问题,但它们并不明确。

Java客户端:

private static String btAdress = "00:00:00:00:00:00";
private static final UUID MY_UUID = UUID.fromString("08C2B2EF-7C87-3D00-0CDC-9A2ADC420BFF");
public BluetoothDevice device;


private static final int DISCOVERABLE_REQUEST_CODE = 0x1;
private boolean CONTINUE_READ_WRITE = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    log.debug(Logs.DEV_DEBUG, "[rosie] Running the rosie program");
    getActionBar().setDisplayHomeAsUpEnabled(true);
    enableBackButton();
    addViewOnUiThread("Rosie Project ");
    setContentView(R.layout.rosie_project_activity);
    //Always make sure that Bluetooth server is discoverable during listening...
    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    startActivityForResult(discoverableIntent, DISCOVERABLE_REQUEST_CODE);
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    addViewOnUiThread("TrackingFlow Creating thread to start listening...");
    new Thread(reader).start();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if(socket != null){
        try{
            is.close();
            os.close();
            socket.close();
        }catch(Exception e){}
        CONTINUE_READ_WRITE = false;
    }
}

private BluetoothSocket socket;
private InputStream is;
private OutputStreamWriter os;
private Runnable reader = new Runnable() {
    public void run() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        try {
            BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord("RosieProject", MY_UUID);
            addViewOnUiThread("TrackingFlow. Listening...");
            socket = serverSocket.accept();
            addViewOnUiThread("TrackingFlow. Socket accepted...");
            is = socket.getInputStream();
            os = new OutputStreamWriter(socket.getOutputStream());
            new Thread(writter).start();

            int bufferSize = 1024;
            int bytesRead = -1;
            byte[] buffer = new byte[bufferSize];
            //Keep reading the messages while connection is open...
            while(CONTINUE_READ_WRITE){
                final StringBuilder sb = new StringBuilder();
                bytesRead = is.read(buffer);
                if (bytesRead != -1) {
                    String result = "";
                    while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0)){
                        result = result + new String(buffer, 0, bytesRead - 1);
                        bytesRead = is.read(buffer);
                    }
                    result = result + new String(buffer, 0, bytesRead - 1);
                    sb.append(result);
                }
                addViewOnUiThread("TrackingFlow. Read: " + sb.toString());
                //Show message on UIThread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(RosieProjectActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        } catch (IOException e) {e.printStackTrace();}
    }
};

private Runnable writter = new Runnable() {

    @Override
    public void run() {
        int index = 0;
        while(CONTINUE_READ_WRITE){
            try {
                os.write("Message From Server" + (index++) + "\n");
                os.flush();
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
};



@Override
public void onResume() {
    super.onResume();
}

@Override
public void onPause() {
    super.onPause();
}

@Override
public void onStop() {
    super.onStop();
}


protected void enableBackButton() {
    new AwaitLatchTask() {
        protected void onPostExecute(Boolean result) {
            getActionBar().setHomeButtonEnabled(true);
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }.execute();
}

@Override
public void handleButtonPress(View view) {
    //Clear the result set
    addViewOnUiThread("Begin Sequence");


}

Python客户端

import bluetooth

bd_addr = "f8:a9:d0:1c:f9:8f"
port = 1

sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))

sock.send("hello!! 21321")

sock.close()




IOError: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

1 个答案:

答案 0 :(得分:0)

我认为错误是由于服务器端使用的UUID造成的。每当使用特定UUID创建服务器时,客户端应仅连接到该特定UUID。否则将发生超时。

在这种情况下,客户端正在尝试连接到串行端口00001101-0000-1000-8000-00805F9B34FB的默认UUID。

要使上述代码有效,请在服务器代码中使用默认串行端口UUID。