简体   繁体   English

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

[英]Pybluez client to Android Bluetooth socket server

I've been trying to make a two way bluetooth RFCOMM communications between an android phone (as the server) and a surface pro tablet running python pybluez(as the client). 我一直在尝试在Android手机(作为服务器)和运行python pybluez(作为客户端)的Surface Pro平板电脑之间进行双向蓝牙RFCOMM通信。 My main problem stems from the Python. 我的主要问题来自Python。 It's not connecting to my android phone that is waiting. 它未连接到正在等待的Android手机。 I manually connected the two devices and then started the server (Android phone). 我手动连接了两个设备,然后启动了服务器(Android手机)。 It gets stuck on "TrackingFlow. Listening...". 它卡在“ TrackingFlow。正在监听...”上。 When I run the Python script I get the error below. 当我运行Python脚本时,出现以下错误。 I found some other stack overflow issues but they weren't explicit. 我发现了其他一些堆栈溢出问题,但不是很明显。

Java Client Side: 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 Client Side 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.

I think the error was due to the UUID used at server side. 我认为该错误是由于服务器端使用了UUID。 Whenever, server is created with a particular UUID, the client should connect to that particular UUID only. 每当使用特定UUID创建服务器时,客户端都应仅连接到该特定UUID。 Otherwise timeout will occur. 否则会发生超时。

In this case, client is trying to connect to the default UUID of serial port 00001101-0000-1000-8000-00805F9B34FB. 在这种情况下,客户端尝试连接到串行端口00001101-0000-1000-8000-00805F9B34FB的默认UUID。

To make above code work, use the default serial port UUID in server code. 要使上述代码起作用,请在服务器代码中使用默认的串行端口UUID。

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

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