如何在彼此不认识的情况下通过蓝牙连接两个设备

How to connect two devices through bluetooth without knowing each other

我正在编写 python 脚本,该脚本 运行 在 raspberry pi 上运行。 android 应用程序需要能够通过蓝牙连接到 raspberry pi 并向其发送一些数据。

我不确定如何连接它们,因为服务器 (pi) 不知道 android 的名称,客户端(应用程序)不知道 [=18] 的地址和端口=].蓝牙连接有没有干净的解决方案?

这是当前的服务器代码。当前的解决方案是在特定端口上设置服务器 运行,但这似乎不是很干净,因为 mac address/port 每次都可能不同。

import bluetooth

    hostMACAdress = '' # need to fill this in
    port = 3
    backlog = 1
    size = 1024
    socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    socket.bind((hostMACAdress, port))
        socket.listen(backlog)
        
try:
    client, clientInfo = socket.accept()
    while True:
        data = client.recv(size)
        if data:
            print(data)
            client.send(data) # Echo

RPi 脚本中的主机 MAC 地址将是 RPi 的地址。您将必须声明一个端口,但是许多 Android 应用程序,例如Serial Bluetooth Terminal 将搜索端口。

您需要先将 RPi 与 Android phone 配对。有一个很好的程序:https://bluedot.readthedocs.io/en/latest/pairpiandroid.html

最近版本的 RPi OS 存在问题,其中 PulseAudio 可以使用 RFCOMM 串行端口配置文件 (SPP),因此如果 PulseAudio 抱怨 rfcomm 已在使用中,您可能必须停止它。

最后,您不需要使用 bluetooth 依赖项。可以使用标准 Python 套接字库来完成。更多详细信息,请访问:https://blog.kevindoran.co/bluetooth-programming-with-python-3/