bluetooth.connect() 产生 BluetToothError(112),而通过 bluetoothctl 连接效果很好

bluetooth.connect() yields BluetToothError(112), while connect via bluetoothctl works well

我正在尝试学习使用 Python 与蓝牙设备通信,但第一步失败了。

我可以使用 bluetoothctl 成功连接到给定设备:

[bluetooth]# connect F5:EE:1C:40:21:44
Attempting to connect to F5:EE:1C:40:21:44
[CHG] Device F5:EE:1C:40:21:44 Connected: yes
Connection successful
[NEW] Primary Service (Handle 0xa9bd)
    /org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000a
    00001801-0000-1000-8000-00805f9b34fb
    Generic Attribute Profile
[NEW] Primary Service (Handle 0xa9bd)
    /org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000b
    53300001-0023-4bd4-bbd5-a6920e4c5653
    Vendor specific
[NEW] Characteristic (Handle 0x6f54)
    /org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000b/char000c
    53300002-0023-4bd4-bbd5-a6920e4c5653
    Vendor specific
[NEW] Characteristic (Handle 0x6604)
    /org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000b/char000e
    53300003-0023-4bd4-bbd5-a6920e4c5653
    Vendor specific
[NEW] Descriptor (Handle 0x0164)
    /org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000b/char000e/desc0010
    00002902-0000-1000-8000-00805f9b34fb
    Client Characteristic Configuration

但尝试通过 Python3 的 pybluez 模块连接会导致出现异常:

sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect(("F5:EE:1C:40:21:44", 1))
...
BluetoothError                            Traceback (most recent call last)
<ipython-input-17-2af54455681d> in <module>
----> 1 sock.connect(("F5:EE:1C:40:21:44", 1))

~/.local/lib/python3.9/site-packages/bluetooth/bluez.py in connect(self, *args, **kwargs)

BluetoothError: [Errno 112] Host is down

我在这里做错了什么?很可能我只是缺少蓝牙开发的基础知识 - 也许你可以给我一个方向..

查看您在连接 bluetoothctl 时共享的日志信息,您似乎正在连接到蓝牙低功耗 (BLE) 设备。

您使用 PyBlueZ 发出的命令是连接到蓝牙经典 (BR/EDR) 设备,我怀疑这就是设备没有响应的原因。

PyBlueZ 使用已弃用的 API 用于 BlueZ。当前支持的 APIs 记录在: https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc

这是Device API that is used for connecting to a device. Below is an example of how to use it with the generic D-Bus library pydbus

from time import sleep
import pydbus

DEVICE_ADDR = 'F5:EE:1C:40:21:44' #  device address


# DBus object paths
BLUEZ_SERVICE = 'org.bluez'
device_path = f"/org/bluez/hci0/dev_{DEVICE_ADDR.replace(':', '_')}"

# setup dbus
bus = pydbus.SystemBus()
device = bus.get(BLUEZ_SERVICE, device_path)

# Connect to device
device.Connect()
sleep(10)
device.Disconnect()