Kir*_*yuk 2 python linux bluetooth bluez pybluez
我需要将所有连接的蓝牙设备连接到我的计算机。我找到了图书馆,但无法连接设备
简单查询示例:
import bluetooth
nearby_devices = bluetooth.discover_devices(lookup_names=True)
print("Found {} devices.".format(len(nearby_devices)))
for addr, name in nearby_devices:
print(" {} - {}".format(addr, name))
Run Code Online (Sandbox Code Playgroud)
问题中的代码片段是扫描新设备,而不是报告连接的设备。
PyBluez 库尚未积极开发,因此我倾向于避免使用它。
BlueZ(Linux 上的蓝牙堆栈)通过 D-Bus 提供一组 API,可以使用 D-Bus 绑定通过 Python 访问这些 API。在大多数情况下我更喜欢pydbus 。
BlueZ API 的文档位于:
https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/adapter-api.txt
https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/device-api.txt
作为如何在 Python3 中实现这一点的示例:
import pydbus
bus = pydbus.SystemBus()
adapter = bus.get('org.bluez', '/org/bluez/hci0')
mngr = bus.get('org.bluez', '/')
def list_connected_devices():
mngd_objs = mngr.GetManagedObjects()
for path in mngd_objs:
con_state = mngd_objs[path].get('org.bluez.Device1', {}).get('Connected', False)
if con_state:
addr = mngd_objs[path].get('org.bluez.Device1', {}).get('Address')
name = mngd_objs[path].get('org.bluez.Device1', {}).get('Name')
print(f'Device {name} [{addr}] is connected')
if __name__ == '__main__':
list_connected_devices()
Run Code Online (Sandbox Code Playgroud)