[英]How to connect two devices through bluetooth without knowing each other
I'm writing a python script that is running on a raspberry pi.我正在编写一个在树莓派上运行的 python 脚本。 An android app needs to be able to connect to the raspberry pi through bluetooth and send it some data.
android 应用程序需要能够通过蓝牙连接到树莓派并向其发送一些数据。
I am not sure how to connect them because the server (pi) will not know the name of the android, and client (application) won't know the address and port of the raspberry pi.我不知道如何连接它们,因为服务器(pi)不知道 android 的名称,客户端(应用程序)不知道树莓派的地址和端口。 Is there a clean solution to the bluetooth connection?
蓝牙连接有干净的解决方案吗?
Here is the current server code.这是当前的服务器代码。 The current solution is have the server run on a specific port, but this doesn't seem very clean as the mac address/port may be different each time.
当前的解决方案是让服务器在特定端口上运行,但这似乎不是很干净,因为 mac 地址/端口可能每次都不同。
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
The host MAC address in your script on the RPi will be the address of the RPi. RPi 上脚本中的主机 MAC 地址将是 RPi 的地址。 You will have to declare a port, but many Android apps eg Serial Bluetooth Terminal will search for the port.
您必须声明一个端口,但许多 Android 应用程序(例如串行蓝牙终端)会搜索该端口。
You will need to pair the RPi and the Android phone first.您需要先将 RPi 和 Android 手机配对。 There is a good procedure at: https://bluedot.readthedocs.io/en/latest/pairpiandroid.html
有一个很好的程序: https://bluedot.readthedocs.io/en/latest/pairpiandroid.html
There is an issue on recent versions of the RPi OS where PulseAudio can be using the RFCOMM Serial Port Profile (SPP) so you may have to stop PulseAudio if it is complaining about rfcomm already in use.在最新版本的 RPi OS 上存在一个问题,其中 PulseAudio 可以使用 RFCOMM 串行端口配置文件 (SPP),因此如果 PulseAudio 抱怨 rfcomm 已在使用中,您可能必须停止它。
Finally, you don't need to use the bluetooth
dependency.最后,您不需要使用
bluetooth
依赖项。 It can be done using the standard Python socket library.可以使用标准的 Python 套接字库来完成。 More details at:https://blog.kevindoran.co/bluetooth-programming-with-python-3/
更多详情请访问:https://blog.kevindoran.co/bluetooth-programming-with-python-3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.