在Linux上以Python列出附近/可发现的蓝牙设备,包括已配对的蓝牙设备

我正在尝试使用Linux上的Python 列出所有附近的/可发现的蓝牙设备, 包括已经配对的 蓝牙设备。

我知道如何使用其地址列出设备的服务,并且可以成功连接:

services = bluetooth.find_service(address='...')

如果我不指定任何条件,则阅读PyBluez文档时,我希望附近的任何设备都能显示出来:

“如果未指定任何条件,则返回检测到的所有附近服务的列表。”

我现在唯一需要的是能够列出已经配对的设备,无论它们是打开,关闭,附近还是不打开。就像我在所有设置-> Ubuntu / Unity中的蓝牙中获得的列表一样。

顺便说一句,以下内容 列出本机上已配对的设备,即使它们在/附近也是如此。可能是因为一旦配对便无法发现它们:

import bluetooth

for d in bluetooth.discover_devices(flush_cache=True):

print d

有任何想法吗 …?

我找到并安装了“ bluez-tools”。

bt-device --list

…给我我需要的信息,即添加设备的地址。

我检查了C源代码,发现它可能不像我想象的那么容易。

仍然不知道如何在Python中执行此操作…

我认为DBUS可能是我应该读的书。似乎很复杂。如果有人可以共享一些代码,我将非常高兴。:)

回答:

自从采用蓝牙API的第5版以来,@

Micke解决方案中使用的大多数功能都已删除,并且与总线的交互通过ObjectManager.GetManagedObjects [1]进行。

import dbus

def proxyobj(bus, path, interface):

""" commodity to apply an interface to a proxy object """

obj = bus.get_object('org.bluez', path)

return dbus.Interface(obj, interface)

def filter_by_interface(objects, interface_name):

""" filters the objects based on their support

for the specified interface """

result = []

for path in objects.keys():

interfaces = objects[path]

for interface in interfaces.keys():

if interface == interface_name:

result.append(path)

return result

bus = dbus.SystemBus()

# we need a dbus object manager

manager = proxyobj(bus, "/", "org.freedesktop.DBus.ObjectManager")

objects = manager.GetManagedObjects()

# once we get the objects we have to pick the bluetooth devices.

# They support the org.bluez.Device1 interface

devices = filter_by_interface(objects, "org.bluez.Device1")

# now we are ready to get the informations we need

bt_devices = []

for device in devices:

obj = proxyobj(bus, device, 'org.freedesktop.DBus.Properties')

bt_devices.append({

"name": str(obj.Get("org.bluez.Device1", "Name")),

"addr": str(obj.Get("org.bluez.Device1", "Address"))

})

bt_device列表中有与所需的数据字典:即

例如

[{

'name': 'BBC micro:bit [zigiz]',

'addr': 'E0:7C:62:5A:B1:8C'

}, {

'name': 'BBC micro:bit [putup]',

'addr': 'FC:CC:69:48:5B:32'

}]

参考:[1] http://www.bluez.org/bluez-5-api-introduction-and-porting-

guide/

以上是 在Linux上以Python列出附近/可发现的蓝牙设备,包括已配对的蓝牙设备 的全部内容, 来源链接: utcz.com/qa/422505.html

回到顶部