BlueZ 是 Linux 官方的 Bluetooth(蓝牙)协议栈,提供了完整的 Bluetooth 支持,包括 Classic Bluetooth 和 Bluetooth Low Energy(BLE)。BlueZ 由多个组件组成,各组件协同工作,实现 Bluetooth 设备的发现、配对、连接、数据传输等功能。
本文将深入解析 BlueZ 的架构、各组件的功能、它们之间的关系,以及如何使用这些组件进行 Bluetooth 设备管理。
BlueZ 主要由三层组成:
提供 Bluetooth 硬件驱动支持。
通过 mgmt API(Management API) 直接管理 Bluetooth 控制器(Adapter)。
通过 HCI(Host Controller Interface) 控制底层 Bluetooth 硬件。
bluetoothd: 核心后台服务,管理 Bluetooth 设备、连接、协议等,提供 D-Bus API 供应用程序调用。
btmgmt:管理 Bluetooth 适配器,直接与 mgmt API 通信。
bluetoothctl:用于扫描、配对、连接设备,依赖 bluetoothd 并通过 D-Bus 交互。
hcidump、meshctl、obexctl等其他工具提供调试、Mesh 网络、文件传输等功能。
Bluetooth 内核子系统:提供 Bluetooth 硬件支持,包括 HCI、L2CAP、RFCOMM、SCO、A2DP 等协议。
mgmt API:用于管理 Bluetooth 适配器(控制开关、模式等)。
HCI(Host Controller Interface):定义 Bluetooth 硬件通信接口。
bluetoothd 负责管理 Bluetooth 设备,并通过 D-Bus 提供 API,供用户空间应用调用。
支持 GATT(Generic Attribute Profile),实现 BLE 设备的通信。
负责处理配对、信号通知、设备发现、Profile 加载等任务。
组件之间的关系如下图(文字描述):
+----------------------+
| 应用程序 / UI |
+----------------------+
|
| D-Bus
v
+----------------------+
| bluetoothd (守护进程) |
+----------------------+
|
| D-Bus / Netlink
v
+----------------------+
| Bluetooth 内核子系统 |
+----------------------+
|
| HCI
v
+----------------------+
| Bluetooth 适配器 (硬件) |
+----------------------+
在大多数 Linux 发行版(如 Ubuntu、Debian)上,使用以下命令安装 BlueZ:
sudo apt update
sudo apt install bluez bluez-tools
安装完成后,检查 Bluetooth 服务是否运行:
systemctl status bluetooth
btmgmt 直接与内核 mgmt API 交互,可用于适配器管理:
sudo btmgmt
常见命令:
power on # 开启 Bluetooth 适配器
power off # 关闭 Bluetooth 适配器
auto-power on # 设置开机自动开启 Bluetooth
find on # 开始扫描设备
find off # 停止扫描
bluetoothctl 是 BlueZ 提供的交互式工具,主要用于扫描、配对、连接设备:
bluetoothctl
在 bluetoothctl 交互界面中,可以使用以下命令:
power on # 启用 Bluetooth 适配器
scan on # 开始扫描设备
pair XX:XX:XX:XX # 配对设备
connect XX:XX:XX:XX # 连接设备
trust XX:XX:XX:XX # 信任设备
exit # 退出
如果需要调试 Bluetooth 数据包,可以使用 hcidump:
sudo hcidump -X
这将捕获所有 HCI 数据包,帮助开发者分析 Bluetooth 通信。
如果需要管理 Bluetooth Mesh 网络,可以使用 meshctl:
sudo meshctl
示例:
discover-unprovisioned on # 发现未配置的 Mesh 设备
provision XX:XX:XX:XX # 配置设备到 Mesh 网络
connect-network # 连接 Mesh 网络
**OBEX(Object Exchange)**协议用于 Bluetooth 文件传输:
sudo obexctl
示例:
connect XX:XX:XX:XX
send /path/to/file
BlueZ 是 Linux 下功能强大的 Bluetooth 协议栈,提供了完整的** Bluetooth Classic** 和 **BLE **支持。它由多个组件组成,包括:
bluetoothd(后台守护进程):管理 Bluetooth 设备、协议和 D-Bus API。
btmgmt(适配器管理):直接与 Linux 内核通信,管理 Bluetooth 适配器。
bluetoothctl(设备管理):通过 D-Bus 与 bluetoothd 交互,实现设备扫描、配对、连接等功能。
其他工具(如 hcidump、meshctl、obexctl):提供调试、Mesh 网络管理、文件传输等功能。
btmgmt 适用于底层适配器管理,如启用 Bluetooth、设置模式等。
bluetoothctl 适用于常规设备管理,如扫描、配对、连接。
hcidump 适用于调试 Bluetooth 通信数据包。
meshctl 适用于 Bluetooth Mesh 网络管理。
通过合理使用 BlueZ 组件,Linux 设备可以高效管理 Bluetooth 硬件,支持各种 Bluetooth 应用场景。