文章目录
手里有一个蓝牙音箱,不知道为什么用blueman-applet连接时显示连接上了,实际上音箱没有声音,总是要把他删除了,重新配对然后在连接才能正常发声。每次都要手动去重新连一下,很烦人,然后自己就慢慢摸索着写了自己第一个shell脚本
shell脚本说明
通过bluetoothctl info
命令可以查看当前连接的蓝牙音箱的信息。通过对比蓝牙音箱声音正常的时候是这个样子的如图:
然后音箱已连接,实际音箱不发声,输出信息里多了一条UUID: Advanced Audio Distribu.. (0000110d-0000-1000-8000-00805f9b34fb)如下图:
咱是小白一个,咱也不懂,那就利用这条信息作为一个判断音箱是否连接成功的信息吧。代码如下:
#!/bin/bash
I7_ID='00:58:56:6A:C8:2D'
I7_Name='Device: i7 '
IFS=$'\n'
count=0 #记录重试次数
flag=0 #重试标记,flag=0 表示任务正常 flag=1 任务失败需要重试 flag=2 未找到相关设备
ConnectI7() {
Bluetooths() {
$(type -P bluetoothctl) "$@"
}
# 检查蓝牙是否连接成功,当"bluetootctl info"执行失败且"bluetoothctl info | grep -i "UUID: Advanced Audio Distribu"返回为空值时,定义为任务失败需要重试
i7.Connect.Status() {
if [[ $(Bluetooths info | grep -i "UUID: Advanced Audio Distribu") == "" ]] && ! Bluetooths info
then
flag=1
else
flag=0
fi
}
#遍历当前设备是否有蓝牙音箱I7
while true
do
local deviceInfo=$(Bluetooths devices)
for i in $deviceInfo
do
local key=$(echo $i | awk '{print $1": "$3" "$4" "$5}')
local deviceName="$key"
if [ "$deviceName" == "$I7_Name" ]
then
local deviceID=$(echo $i | awk '{print $2}')
echo -e "\n"'发现蓝牙音箱: '$I7_Name
echo -e "\n"'=================================='
echo '== 正在检查蓝牙音箱i7连接状态 =='
echo -e '=================================='"\n"
if ! Bluetooths info
then
echo "蓝牙音箱I7连接异常"
echo -e "\n……正在移除问题设备: 蓝牙音箱i7……\n"
Bluetooths remove "$deviceID"
sleep 5s
echo -e "\n"'重新扫描蓝牙设备'"\n"
Bluetooths --timeout 15 scan on
echo -e "\n……正在重新配对和连接蓝牙音箱i7……\n"
Bluetooths pair "$deviceID"
Bluetooths trust "$deviceID"
Bluetooths connect "$deviceID"
echo -e "\n正在重新检查蓝牙音箱i7连接状态\n"
i7.Connect.Status
break
else
if [[ $(Bluetooths info | grep -i "UUID: Advanced Audio Distribu") != "" ]]
then
echo "蓝牙音箱I7虽然连接成功但似乎工作异常"
echo -e "\n……正在移除问题设备: 蓝牙音箱i7……\n"
Bluetooths remove "$deviceID"
sleep 5s
echo -e "\n"'重新扫描蓝牙设备'"\n"
Bluetooths --timeout 15 scan on
echo -e "\n……正在重新配对和连接蓝牙音箱i7……\n"
Bluetooths pair "$deviceID"
Bluetooths trust "$deviceID"
Bluetooths connect "$deviceID"
echo -e "\n正在重新检查蓝牙音箱i7连接状态\n"
i7.Connect.Status
break
else
flag=0
break
fi
fi
else
flag=2
fi
done
if [ ${flag} -eq 0 ]
then
echo -e "\n蓝牙音箱i7已成功连接\n"
exit
elif [ ${flag} -eq 2 ]
then
echo -e "\n未找到蓝牙音箱i7,正在重试\n"
else
echo -e "\n蓝牙音箱i7连接失败,正在重试\n"
fi
count=$[ ${count} + 1 ]
if [ $count -ge 6 ]
then
echo -e "\n未找到蓝牙音箱i7,退出脚本\n"
exit
fi
echo "========================================"
echo "== 开始第$count次重新连接蓝牙音箱i7 =="
echo "== ……请稍等…… =="
echo -e "========================================\n"
echo -e "====== 3秒后重新连接蓝牙音箱i7 ======\n"
sleep 3s
Bluetooths --timeout 15 scan on
done
}
ConnectI7