BlueZ

用树莓派玩转蓝牙

BlueZ

首先要在树莓派上安装必要的工具。html

BlueZ是Linux官方的蓝牙协议栈。能够经过BlueZ提供的接口,进行丰富的蓝牙操做。shell

Raspbian中已经安装了BlueZ。使用的版本是5.43。能够检查本身的BlueZ版本:工具

 bluetoothd -v url

低版本的BlueZ对低功耗蓝牙的支持有限。若是使用版本低于5.43,那么建议升级BlueZ。spa

能够用下面的命令检查BlueZ的运行状态:.net

 systemctl status bluetooth 代理

返回结果是:日志

pi@raspberrypi:~ $ systemctl status bluetooth ● bluetooth.service - Bluetooth service Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2019-05-05 18:16:39 CST; 10min ago Docs: man:bluetoothd(8) Main PID: 531 (bluetoothd) Status: "Running" CGroup: /system.slice/bluetooth.service └─531 /usr/lib/bluetooth/bluetoothd May 05 18:16:38 raspberrypi systemd[1]: Starting Bluetooth service... May 05 18:16:39 raspberrypi bluetoothd[531]: Bluetooth daemon 5.43 May 05 18:16:39 raspberrypi systemd[1]: Started Bluetooth service. May 05 18:16:39 raspberrypi bluetoothd[531]: Starting SDP server May 05 18:16:39 raspberrypi bluetoothd[531]: Bluetooth management interface 1.14 initialized May 05 18:16:39 raspberrypi bluetoothd[531]: Failed to obtain handles for "Service Changed" characteristic May 05 18:16:39 raspberrypi bluetoothd[531]: Sap driver initialization failed. May 05 18:16:39 raspberrypi bluetoothd[531]: sap-server: Operation not permitted (1) May 05 18:16:39 raspberrypi bluetoothd[531]: Endpoint registered: sender=:1.10 path=/A2DP/SBC/Source/1 May 05 18:16:39 raspberrypi bluetoothd[531]: Endpoint registered: sender=:1.10 path=/A2DP/SBC/Sink/1

能够看到,蓝牙服务已经打开,并在正常运行。code

能够用下面命令手动启动或关闭蓝牙服务:server

sudo systemctl start bluetooth sudo systemctl stop bluetooth

此外,还能够让蓝牙服务随系统启动:

 sudo systemctl enable bluetooth 

了解树莓派上的蓝牙

在Raspbian中,基本的蓝牙操做能够经过bluez中的 bluetoothctl 命令进行。该命令运行后,将进入到一个新的Shell。

在这个shell中输入:

 list 

将显示树莓派上可用的蓝牙模块,例如:

 Controller B8:27:EB:72:47:5E raspberrypi [default] 

运行scan命令,开启扫描:

 scan on 

扫描启动后,用devices命令,能够打印扫描到蓝牙设备的MAC地址和名称,例如:

 Device 00:9E:C8:62:AF:55 MiBOX3 Device 4D:CE:7A:1D:B8:6A vamei 

若是设备未在清单中列出,输入 scan on 命令设置设备发现模式。 

输入 agent on 命令打开代理。

输入  pair MAC Address  开始配对(支持 tab 键补全)。 

若是使用无 PIN 码设备,再次链接可能须要手工认证。

输入  trust MAC Address  命令。 

最后,用 connect MAC Address 命令创建链接。

此外,还能够用 help 命令得到帮助。使用结束后,能够用 exit 命令退出bluetoothctl。

除了bluetoothctl,在Raspbian是shell中能够经过hciconfig来控制蓝牙模块。好比开关蓝牙模块:

 sudo hciconfig hci0 up #启动hci设备 sudo hciconfig hci0 down #关闭hci设备

命令中的hci0指的是0号HCI设备,即树莓派的蓝牙适配器。

与此同时,能够用下面命令来查看蓝牙设备的工做日志:

 hcidump 

bluez自己还提供了链接和读写工具。但不一样版本的bluez相关功能的差别比较大,并且使用起来不太方便,因此下面使用Node.js的工具来实现相关功能。

相关文章
相关标签/搜索