BlueZ

用树莓派玩转蓝牙

BlueZ

首先要在树莓派上安装必要的工具。
BlueZ是Linux官方的蓝牙协议栈。可以通过BlueZ提供的接口,进行丰富的蓝牙操作。
Raspbian中已经安装了BlueZ。使用的版本是5.43。可以检查自己的BlueZ版本:

 bluetoothd -v 

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

可以用下面的命令检查BlueZ的运行状态:

 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

可以看到,蓝牙服务已经打开,并在正常运行。

可以用下面命令手动启动或关闭蓝牙服务:

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的工具来实现相关功能。

猜你喜欢

转载自www.cnblogs.com/Java-Script/p/11095648.html