【问题标题】:Pairing bluetooth devices with Passkey/Password in python - RFCOMM (Linux)在 python 中将蓝牙设备与密码/密码配对 - RFCOMM (Linux)
【发布时间】:2016-09-24 17:05:09
【问题描述】:

我正在编写一个 Python 脚本来搜索蓝牙设备并使用 RFCOMM 连接它们。该设备具有密码/密码。我正在使用 PyBlueZ,据我所知,这个库无法处理密码/密码连接 (Python PyBluez connecting to passkey protected device)。

我能够发现这些设备并检索它们的名称和地址:

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)'

我使用 hcitoolbluetooth-agent 尝试了一些 bash 命令,但我需要以编程方式进行连接。我能够使用此处描述的步骤连接到我的设备:How to pair a bluetooth device from command line on Linux

我想询问是否有人使用 Python 使用密码/密码连接到蓝牙设备。我正在考虑使用subprocess.call() 在 Python 中使用 bash 命令,但我不确定这是否是个好主意。

感谢您的帮助。

【问题讨论】:

    标签: python linux bluetooth pybluez


    【解决方案1】:

    我终于可以使用 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 文档可在 here

    【讨论】:

    • 嗨,叶海亚。是的,这是一个命令。 bluetooth-agent 是一个管理配对码的工具。您可以阅读更多相关信息:askubuntu.com/questions/763939/…wiki.debian.org/BluetoothUser#Pairing_using_CLI
    • 好的,谢谢,基本上是:your bluetooth agent 例如bluetoothctl
    • 是的。如果没有bluetooth-agent,可以使用bluetoothctl
    • 那么有没有我可以安装的bluetooth-agent 软件包,或者它只是一个名称,指的是我提到的类别,例如bluetoothctl
    • 对未来的读者来说,不是所有的debians dist都有bluetooth-agent,它明确提到:“如果bluetooth-agent不可用,请尝试bluetoothctl
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 2012-07-22
    相关资源
    最近更新 更多