-
Notifications
You must be signed in to change notification settings - Fork 2
/
btmenu
executable file
·97 lines (77 loc) · 1.86 KB
/
btmenu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/bin/bash
_bluetoothctl() {
LC_ALL=C timeout 30 bluetoothctl
}
mode=connect
# Name -> MAC
declare -A DEVICES
while read -r _ mac name; do
DEVICES["$name"]=$mac
done < <(echo "devices" | _bluetoothctl | awk '$1 == "Device"')
notify() {
local msg
local is_error
msg=${1?BUG: no message}
is_error=${2:-0}
if command -v notify-send >/dev/null 2>&1; then
notify-send "btmenu" "$msg" # TODO: escaping
fi
if (( is_error )); then
printf 'ERROR: %s\n' "$msg" >&2
else
printf '%s\n' "$msg"
fi
}
execute_mode() {
local mode
local name
local mac
local preposition
local expected_to_connect
local retries
mode=${1?BUG: missing mode}
retries=15
case $mode in
connect)
preposition=to
expected_to_connect=yes
;;
disconnect)
preposition=from
expected_to_connect=no
;;
esac
if ! (( ${#DEVICES[@]} )); then
notify "No devices found. Are they registered with D-Bus?" 1
return 2
fi
name=$(printf '%s\n' "${!DEVICES[@]}" | dmenu -p "btmenu" "${dmenu_args[@]}")
[[ $name ]] || return
mac=${DEVICES["$name"]}
notify "Attempting to $mode $preposition $name"
while (( retries-- )); do
printf 'power on\n%s %s\n' "$mode" "$mac" | _bluetoothctl
if printf 'info %s\n' "$mac" |
_bluetoothctl |
grep -Pq '^[\t ]+Connected: '"$expected_to_connect"; then
notify "${mode^}ed $preposition $name"
return 0
fi
sleep 1
done
ret="$?"
notify "Failed to $mode $preposition $name" 1
return "$ret"
}
i=2
for arg do
if [[ $arg == :: ]]; then
dmenu_args=( "${@:$i}" )
break
fi
case "$arg" in
-d) mode=disconnect ;;
esac
(( i++ ))
done
execute_mode "$mode"