-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbluetooth
executable file
·136 lines (119 loc) · 2.52 KB
/
bluetooth
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#!/usr/bin/env bash
set -euo pipefail
assert_command() {
if ! type "${1}" >/dev/null 2>&1; then
echo "${2:-"command not found: ${1}"}"
exit 1
fi
}
assert_val() {
if [[ -z "${1}" ]]; then
echo "${2}"
exit 1
fi
}
assert_func() {
if ! declare -F "${1}" >/dev/null; then
echo "${2}"
exit 1
fi
}
_darwin_power() {
case "${1:-"?"}" in
1|on) blueutil --power 1;;
0|off) blueutil --power 0;;
?) blueutil --power ;;
*) exit 1 ;;
esac
}
_darwin_restart() {
bluetooth power off
bluetooth power on
}
_darwin_connect() {
local disconnect="no"
while (( "$#" )); do
case "${1}" in
--disconnect)
disconnect="yes"
shift;;
*)
shift;;
esac
done
local -r blob="$(blueutil --format=json --paired)"
local -r name="$(echo "${blob}" | jq -r '.[].name' | fzf)"
local -r id="$(echo "${blob}" | jq -r ".[] | select(.name =\"${name}\") | .address")"
if [[ "${disconnect}" = "yes" ]]; then
blueutil --disconnect "${id}"
fi
blueutil --connect "${id}"
}
_linux_power() {
case "${1:-"?"}" in
1|on) bluetoothctl power on;;
0|off) bluetoothctl power off;;
?) bluetoothctl show | grep --quiet "Powered: yes" && echo "1" || echo "0" ;;
*) exit 1 ;;
esac
}
_linux_restart() {
if [[ -z "$(bluetoothctl list)" ]]; then
sudo modprobe -r btusb
sudo modprobe btusb
while [[ -z "$(bluetoothctl list)" ]]; do
sleep 0.2
done
fi
bluetooth power off
bluetooth power on
}
_linux_connect() {
local disconnect="no"
while (( "$#" )); do
case "${1}" in
--disconnect)
disconnect="yes"
shift;;
*)
shift;;
esac
done
local -r blob="$(bluetoothctl paired-devices)"
local -r name="$(echo "${blob}" | sed -e 's/\S* \S* //' | fzf)"
assert_val "${name}" "failed to select device"
local -r id="$(echo "${blob}" | grep "${name}" | awk '{ print $2 }')"
if [[ "${disconnect}" = "yes" ]]; then
bluetoothctl disconnect "${id}"
fi
bluetoothctl connect "${id}"
}
declare OS=""
case "${OSTYPE}" in
darwin*)
assert_command blueutil
OS="darwin"
;;
linux*)
assert_command bluetoothctl
OS="linux"
;;
*)
echo "Unsupported OS!"
exit 1;;
esac
declare -r cmd="${1:-"help"}"
shift || true
case "${cmd}" in
help)
cat << HELP
USAGE:
bluetooth power [0|1|on|off]
bluetooth restart
bluetooth connect
HELP
exit 0
esac
declare -r func="_${OS}_${cmd}"
assert_func "${func}" "invalid command: ${cmd}"
$func $@