我正在编写一个Python脚本来搜索蓝牙设备,并使用RFCOMM连接它们。此设备具有Passkey/密码。我正在使用PyBlueZ,据我所知,这个库无法处理Passkey/Password连接(连接到密码保护设备的Python PyBluez)。
我能够发现这些设备并检索它们的名称和地址:
nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True,
flush_cache=True, lookup_class=False)但是,如果试图连接到特定的设备,则使用:
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect((addr,port)) 我得到一个错误'Device or resource busy (16)'。
我使用hcitool和蓝牙代理尝试了一些bash命令,但我需要以编程的方式进行连接。我能够使用以下步骤连接到我的设备:如何在Linux上从命令行对蓝牙设备。
我想问是否有人使用Python连接到带有Passkey/密码的蓝牙设备。我正在考虑使用subprocess.call()在Python中使用bash命令,但我不确定这是否是一个好主意。
谢谢你的帮助。
发布于 2016-05-27 15:40:30
最后,我能够连接到一个使用PyBlueZ的设备。我希望这个答案将来能对其他人有所帮助。我尝试了以下几点:
首先,导入模块并发现设备。
import bluetooth, subprocess
nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True,
flush_cache=True, lookup_class=False)当您发现要连接的设备时,您需要知道端口、地址和密码。有了这些信息,接下来要做的是:
name = name # Device name
addr = addr # Device Address
port = 1 # RFCOMM port
passkey = "1111" # passkey of the device you want to connect
# kill any "bluetooth-agent" process that is already running
subprocess.call("kill -9 `pidof bluetooth-agent`",shell=True)
# Start a new "bluetooth-agent" process where XXXX is the passkey
status = subprocess.call("bluetooth-agent " + passkey + " &",shell=True)
# Now, connect in the same way as always with PyBlueZ
try:
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect((addr,port))
except bluetooth.btcommon.BluetoothError as err:
# Error handler
pass现在,你是连在一起的!您可以将套接字用于所需的任务:
s.recv(1024) # Buffer size
s.send("Hello World!")正式的PyBlueZ文档可获得这里
发布于 2022-12-01 00:44:49
有没有一种通过蓝牙连接两部手机的方法,脚本应该在Linux主机上运行。有使用pybluez或其他API的建议吗?
我看到了一些例子,其中Linux主机被用作客户端并连接电话(这是一个服务器),但是这里我想使用Linux主机作为运行脚本的设备,并让两部手机通过蓝牙连接。
https://stackoverflow.com/questions/37465157
复制相似问题