介绍完BLE之后,下面简单操作蓝牙
# 复位蓝牙
echo 0 > /sys/class/rfkill/rfkill0/state
sleep 1
echo 1 > /sys/class/rfkill/rfkill0/state
sleep 1
# 绑定蓝牙设备
hciattach -n ttyS1 xradio > /dev/null 2>&1 &
sleep 8
# 启用蓝牙设备
hciconfig hci0 up
hciconfig hci0 piscan
hcitool scan #扫描经典蓝牙
hcitool lescan #扫描BL低功耗蓝牙
1、先启动蓝牙,进入可搜索状态
# 复位蓝牙
echo 0 > /sys/class/rfkill/rfkill0/state
sleep 1
echo 1 > /sys/class/rfkill/rfkill0/state
sleep 1
# 绑定设备
hciattach -n ttyS1 xradio > /dev/null 2>&1 &
sleep 8
# 启用蓝牙设备
hciconfig hci0 up
hciconfig hci0 piscan
# 免认证
hciconfig hci0 auth
# 广播
hciconfig hci0 leadv
2、进入 bluetoothctl 交互界面
# bluetoothctl
Agent registered
[CHG] Controller 22:92:C9:8C:04:EA Pairable: yes
[bluetooth]#
3、手机使用BLE调试助手连接蓝牙,如下图所示

4、连接后,bluetoothctl会发生变化,此时已经进入交互界面
4、但是我们没有其他服务,只能做一些简单的操作,比如读取,因为现有的服务是 bluetoothctl 提供的
5、下面我们添加自己的服务
5.1 进入菜单
[6B-3C-BF-AD-2A-A8]# menu gatt
Menu gatt:
Available commands:
-------------------
list-attributes [dev/local] List attributes
select-attribute <attribute/UUID> Select attribute
attribute-info [attribute/UUID] Select attribute
read [offset] Read attribute value
write <data=xx xx ...> [offset] [type] Write attribute value
acquire-write Acquire Write file descriptor
release-write Release Write file descriptor
....
5.2 添加自己的service和characteristic
[bluetoothctl] register-service 0xFFFF # (Choose yes when asked if primary service)
[bluetoothctl] register-characteristic 0xAAAA read # (Select a value of 1 when prompted)# 输入的值是初始值,每次读取,会加一
[bluetoothctl] register-characteristic 0xBBBB read,write # (Select a value of 0 when prompted)
[bluetoothctl] register-characteristic 0xCCCC read # (Select a value of 2 when prompted)
[bluetoothctl] register-application # (This commits the services/characteristics and registers the profile)
[bluetoothctl] back
[bluetoothctl] advertise on
通过 show 操作可以看到刚才添加的0xffff 服务

5.3 手机重新连接蓝牙
服务从 3 项变为 4 项,第 4 项即为我们刚才添加的服务。
5.4 读写操作
在有上传按钮的服务上传数据
此时收到:

读操作的话,直接读取就好了,值为刚才我们设置的值。
至此测试完毕
hciconfig hci0 up #启动蓝牙设备
hciconfig hci0 off #关闭蓝牙设备
hciconfig hci0 reset #重启蓝牙设备
l2ping -i hci0 -c 4 21:12:A3:C4:50:66
sdptool browse local # local可以改成其它蓝牙的mac地址
hciconfig -a
hcitool dev
Devices:
hci0 22:22:2A:B0:9C:3C
hciconfig hci0 leadv / noleadv
(此时调试助手已经连接)
hcitool -i hci0 con
Connections:
> LE 60:AB:D1:B5:A6:FB handle 0 state 1 lm PERIPHERAL
直接体现在进行蓝牙连接时,是否输入连接PIN密码,用于PIN配对
hciconfig hci0 auth/noauth
hciconfig hci0 lm master、hciconfig hci0 lm slave
hciconfig hci0 name 、hciconfig hci0 name BLXX
hciconfig hci0 lestates
bluetoothctl --monitor gatt.list-attributes
其他操作自己慢慢摸索哈,我一个人只能啃成这样了,如有写得不对的地方大佬指正。