蓝牙通信不含Android和IOT设备

时间:2016-11-02 10:57:31

标签: android python bluetooth

我正在尝试在Android和IOT(intel galileo)设备之间建立蓝牙通信。

IOT端的代码(我将其保留为客户端),它会将数据发送到android,但这里有一个端口号是硬编码的。这是在python中。

def record_transmit_to_subscriber(self, subscriber, message):
    server_addr = subscriber
    port = 6 
    client_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    try:
        client_socket.connect((server_addr, port))

        client_socket.send(message)

        client_socket.close()
        return True
    except Exception as e:
        print "Unable to make connection with subscriber", subscriber
        return False

现在在android(服务器端):

private static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
       BluetoothServerSocket tmp = null;
        BluetoothAdapter mBluetoothAdapter =    BluetoothAdapter.getDefaultAdapter();
        try {
            // MY_UUID is the applications UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) {
            GlobalUtils.writeLogFile("Error in BLE Listening " + e.getMessage());
        }
        mmServerSocket = tmp;
    } catch (Exception e){
        GlobalUtils.writeLogFile("Exception in Accept Thread " + e.getMessage());
    }

我相信在这段代码中存在一些问题,在客户端它使用端口号,而在服务器端则使用uuid。有人可以纠正如何修改此代码以使连接工作。

1 个答案:

答案 0 :(得分:0)

似乎你忘了创建套接字和流:

try {
    BluetoothDevice bluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("<MAC_address_of_your_device>");
    mSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);

    mSocket.connect();
} catch (IOException e) {
   Log.e(TAG, "Fail connect");
}

// Get the input and output streams for BT socket
try {
    inStream = mSocket.getInputStream();
    outStream = mSocket.getOutputStream();
} catch (IOException e) {
    Log.e(TAG, "Fail to open socket streams");
}

您可以为Thread(例如inStreaminStream.read(<data_buffer>);的读取数据创建Thread,以便将数据写入outStream(例如{{1} }})。