首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >蓝牙通信b/w Android和物联网设备

蓝牙通信b/w Android和物联网设备
EN

Stack Overflow用户
提问于 2016-11-02 18:57:31
回答 1查看 258关注 0票数 0

我正在尝试建立Android和IOT (英特尔伽利略)设备之间的蓝牙通信。

IOT端的代码(我将它作为客户端),它将发送数据到android,但这里的一个端口号是硬编码的。这是用python编写的。

代码语言:javascript
复制
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 (服务器)端:

代码语言:javascript
复制
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。有没有人可以纠正一下如何修改此代码以使连接工作。

EN

回答 1

Stack Overflow用户

发布于 2016-11-02 19:12:13

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

代码语言:javascript
复制
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");
}

然后,您可以创建用于从inStream读取数据的Thread (例如,inStream.read(<data_buffer>); )和用于将数据写入outStreamThread (例如,outStream.write(<data_buffer>); outStream.flush();)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40378240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档