Ubuntu 22.04下如何通过DBus实现快速BLE设备发现?
解决Ubuntu下BLE设备发现速度慢的DBus方案
监听「Bluetooth Settings」的DBus消息
直接用系统自带的dbus-monitor工具就能捕获目标应用的DBus通信:
- 先找到「Bluetooth Settings」的进程ID(它是
gnome-control-center的一部分):pgrep gnome-control-center - 监听该进程的会话总线消息(GUI应用一般用会话总线):
dbus-monitor --session --pid=你的进程ID - 如果想精准过滤Bluez相关的信号/调用,也可以用更窄的过滤规则:
dbus-monitor --session "interface='org.bluez.Adapter1'" "interface='org.bluez.Device1'"
启动扫描操作时,就能看到GUI发送的DBus命令和接收的设备发现信号了。
DBus自省工具
有两个实用工具可以帮你查看Bluez的DBus接口细节:
- gdbus introspect:命令行工具,直接查看指定DBus对象的所有方法、信号和属性,比Bluez官方文档更直观:
gdbus introspect --system --dest org.bluez --object-path /org/bluez/hci0 - d-feet:图形化DBus浏览器,能可视化浏览所有DBus服务、接口,还能手动调用方法测试,直接在Ubuntu软件中心搜索安装即可。
Python通过DBus调用Bluez实现BLE扫描的示例
用GNOME官方的Gio库(和「Bluetooth Settings」用的是同一框架)写的扫描代码,速度会和GUI一致:
from gi.repository import Gio, GLib def on_device_discovered(manager, obj_path, interfaces): # 只处理BLE设备的发现信号 if 'org.bluez.Device1' in interfaces: dev_props = interfaces['org.bluez.Device1'] dev_name = dev_props.get('Name', '未命名设备') dev_mac = obj_path.split('/')[-1] print(f"找到BLE设备: {dev_name} ({dev_mac})") def start_ble_scan(): # 连接系统总线(Bluez运行在系统总线上) system_bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) # 获取蓝牙适配器的DBus代理 adapter_proxy = Gio.DBusProxy.new_sync( system_bus, Gio.DBusProxyFlags.NONE, None, 'org.bluez', '/org/bluez/hci0', # 替换成你的蓝牙适配器路径,一般是hci0 'org.bluez.Adapter1', None ) # 监听设备添加事件 obj_manager = Gio.DBusObjectManagerClient.new_sync( system_bus, Gio.DBusObjectManagerClientFlags.NONE, 'org.bluez', '/org/bluez', None, None ) obj_manager.connect('object-added', on_device_discovered) # 启动LE扫描(传入空参数字典即可) adapter_proxy.StartDiscovery('(a{sv})', {}) # 启动事件循环处理DBus信号 main_loop = GLib.MainLoop() try: main_loop.run() except KeyboardInterrupt: # 终止扫描并退出循环 adapter_proxy.StopDiscovery() main_loop.quit() if __name__ == '__main__': start_ble_scan()
运行前需要安装依赖:
sudo apt install python3-gi python3-dbus
内容的提问来源于stack exchange,提问作者Marcus
相关产品推荐
相关产品推荐

