如何使用 pybluez 构建 Android 蓝牙服务器应用程序处理从 Raspberry Pi 发送的数据

How to build Android Bluetooth server app handling data sent from Raspberry Pi using pybluez

我想知道如何构建 Android 应用处理从 Raspberry pi 发送的数据。

我在 Raspberry Pi 上安装了 pybluez 模块并使用以下 python 脚本发送数据。

import bluetooth
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((targetBluetoothMacAddress, port)) 
                      #targetBluetoothMacAddress is my phone MacAddress
sock.send("hello!!")
sock.close()

在我的 phone 上,我确实看到两个设备配对成功。但是找不到获取从 Raspberry Pi 发送的数据的方法。有没有办法构建一个应用程序来处理来自 sock.send() 的数据?

您需要参考 Android 蓝牙 API,但是您可以非常轻松地构建应用程序。首先,您要做的是获取对 BluetoothDevice that represents the Raspberry Pi you wanna connect to. You can do this by calling BluetoothAdapter.startDiscovery() or by directly asking the framework for a device with the MAC address of the Raspberry Pi by calling BluetoothAdapter.getRemoteDevice(...).

的引用

获得设备后,您会想要打开 BluetoothSocket with the device. To do this call createRfcommSocketToServiceRecord(UUID). The UUID argument will more thank likely "0001101-0000-1000-8000-00805F9B34FB" if you're connecting to the Raspberry Pi using SPP. The create method will return to you a BluetoothSocket which you will need to call connect() on. Note, connect is a blocking call and you will need to perform all this work in a worker thread to prevent locking up your UI. If connect returns successfully you've successfully connected with the device. In order to achieve back and forth communication with the device, you'll need to get ahold to it's Input and Output streams by calling the following two methods getInputStream() and getOutputStream() on BluetoothSocket

一旦你有了这两个流,你就可以在两个设备之间来回发送字节数据。请注意,从流中读取和写入是阻塞操作,因此我建议创建两个单独的线程来读取和写入数据,将流和处理程序传入线程构造函数,以便您可以将数据发回 UI 线程.