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

转载于:https://www.cnblogs.com/Java-Script/p/11095648.html

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值