出现这个问题的原因是由于Bluez库还未完全支持BLE,因此需要手动对特定的属性进行设置。下面是解决方法的代码示例:
首先要确认你的Bluez版本是否支持BLE:
dpkg -s bluez | grep Version
如果版本号大于等于5.31,那么就支持BLE;否则需要先升级Bluez版本。
步骤一:升级Bluez版本(如果需要)。
sudo apt-get update
sudo apt-get upgrade bluez
步骤二:配置GATT服务路径。 在Bluez 5.42及以上版本中使用以下命令:
sudo hciconfig hci0 reset
sudo btmgmt le on
sudo btmgmt bredr off
sudo btmgmt power on
sudo hcitool lescan
在Bluez 5.41及以下版本中使用以下命令:
sudo hciconfig hci0 down
sudo hciconfig hci0 up
sudo hciconfig hci0 leadv 3
sudo hciconfig hci0 noscan
sudo hciconfig hci0 -p connectable
sudo hciconfig hci0 sspmode 0
sudo hciconfig hci0 nosecmgr
sudo hciconfig hci0 noencrypt
sudo hciconfig hci0 lescan
步骤三:连接远程设备。 使用以下Python代码连接远程蓝牙设备:
import dbus
import dbus.exceptions
import dbus.mainloop.glib
import dbus.mainloop.qt
DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager'
DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties'
bus = None
device_path = None
def find_adapter(bus):
adapter_path = None
# 查找与Bluez代理相关联的适配器。
obj = bus.get_object('org.bluez', '/')
mgr = dbus.Interface(obj, DBUS_OM_IFACE)
objects = mgr.GetManagedObjects()
for path, ifaces in objects.items():
adapter = ifaces.get('org.bluez.Adapter1')
if adapter is None:
continue
if 'adapter0' in path:
adapter_path = path
break
if not adapter_path:
raise Exception('适配器未找到')
return adapter_path
def discover_device(bus, adapter_path):
global device_path
iface = dbus.Interface(bus.get_object('org.bluez', adapter_path),
'org.bluez.Adapter1')
iface.StartDiscovery()
# 监听接口以获取设备路径。
bus.add_signal_receiver(device_found_callback,
bus_name='org.bluez',
signal_name='InterfacesAdded')
# 等待发现设备。
while True:
if device_path:
break
dbus.mainloop.glib
上一篇:BlueZ设置连接间隔