本文适用于低功耗蓝牙设备(BLE)的连接与调试,对于经典蓝牙设备或许会有不同。
开始使用
在终端中输入bluetoothctl进入工具,
输入help可查看当前菜单下所有支持的命令:
Menu main:
Available commands:
-------------------
advertise Advertise Options Submenu
monitor Advertisement Monitor Options Submenu
scan Scan Options Submenu
gatt Generic Attribute Submenu
admin Admin Policy Submenu
list List available controllers
show [ctrl] Controller information
select <ctrl> Select default controller
devices List available devices
paired-devices List paired devices
system-alias <name> Set controller alias
reset-alias Reset controller alias
power <on/off> Set controller power
pairable <on/off> Set controller pairable mode
discoverable <on/off> Set controller discoverable mode
discoverable-timeout [value] Set discoverable timeout
agent <on/off/capability> Enable/disable agent with given capability
default-agent Set agent as the default one
advertise <on/off/type> Enable/disable advertising with given type
set-alias <alias> Set device alias
scan <on/off/bredr/le> Scan for devices
info [dev] Device information
pair [dev] Pair with device
cancel-pairing [dev] Cancel pairing with device
trust [dev] Trust device
untrust [dev] Untrust device
block [dev] Block device
unblock [dev] Unblock device
remove <dev> Remove device
connect <dev> Connect device
disconnect [dev] Disconnect device
menu <name> Select submenu
version Display version
quit Quit program
exit Quit program
help Display help about this program
export Print environment variables
连接设备
使用scan on开始搜索设备,
注:使用scan off可以停止搜索。
[NEW]开头的字段代表新搜索到的设备,[CHG]开头的字段代表设备状态变化(一般是信号强度变化),[DEL]开头的字段代表丢失设备信号。
使用connect <MAC地址>连接设备,例如:
connect 12:34:56:78:90:AB
注:使用disconnect可以断开连接。
此时工具会提示开始尝试连接:
Attempting to connect to 12:34:56:78:90:AB
出现以下提示
[CHG] Device 12:34:56:78:90:AB Connected: yes
Connection successful
则连接成功
设备操作
设备连接完成后,我们需要开始对其进行操作。使用menu gatt进入 GATT 协议子菜单。
注:使用back可退出子菜单。
显示设备所有属性:
list-attributes
使用select-attribute+属性的UUID或路径即可选中属性进行操作,例如
select-attribute a6ed0202-d344-460a-8075-b9e8ec90d71b
select-attribute /org/bluez/hci0/dev_12_34_56_78_90_AB/service000c/char000d
注:使用attribute-info可查看当前已选中属性信息。
attribute-info <UUID/属性路径>可查看任意属性的详细信息
发送数据
注:在进行发送/读取/接受操作时请注意是否对该特性具有相关权限
使用write来发送数据,示例如下:
单位字节发送:
write 0x01
多位字节发送:
write '0x01 0x02 0x03 0x04 0xab 0xcd 0xef'
读取数据
使用read来读取
接收通知
使用notify进行操作:
打开通知接收
notify on
关闭通知接收
notify off