用樹莓派玩轉藍牙
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的工具來實現相關功能。