Created
July 7, 2019 23:56
-
-
Save thiagoghisi/50c3ba835ea72cdb0318fb3306fd2c76 to your computer and use it in GitHub Desktop.
Script for Mac OSX to Restart Bluetooth service & Reconnect all recently paired devices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
echo "Restarting bluetooth service..." | |
blueutil -p 0 && sleep 1 && blueutil -p 1 | |
echo "Waiting bluetooth service to be restored..." | |
until blueutil -p | grep "1" >/dev/null; do sleep 1; done | |
echo "Searching for devices not connected..." | |
devices=($(blueutil --paired | grep "not connected" | awk -F '[ ,]' '{print $2}')) | |
echo "Found ${#devices[@]} recently paired devices not connected" | |
for device in ${devices[@]}; do | |
for retry in {1..5}; do | |
echo "Trying to connect to ${device} ..." | |
if blueutil --connect ${device}; then break; fi | |
echo "Failed to connect to ${device}" | |
sleep 1 | |
done | |
done |
Here's another version adapted from above that selects only recently paired devices (within the last day), and also prints out the device name. Note that the script requires a recent version of blueutil
that can output JSON.
#!/bin/bash
# Restart the Bluetooth stack on macOS
#
# Adapted from https://gist.github.com/thiagoghisi/50c3ba835ea72cdb0318fb3306fd2c76
# See discussion at https://gist.github.com/nicolasembleton/afc19940da26716f8e90
# ensure blueutil and jq are installed
for bin in blueutil jq; do
if ! hash $bin 2> /dev/null; then
echo >&2 "Please install \"$_\" first!"
exit 1
fi
done
echo 'Restarting the Bluetooth service...'
blueutil -p 0 && sleep 1 && blueutil -p 1
echo 'Waiting for service to be restored...'
until [[ `blueutil -p` == 1 ]]; do sleep 1; done
echo 'Searching for recently paired devices...'
_IFS=$IFS; IFS=$'\n'
# jq expression returns lines: <address> <name>
devices=($(blueutil --recent --format json | jq -r 'def daysAgo(days): (now | floor) - (days * 86400); daysAgo(1) as $recent | .[] | select((.recentAccessDate | sub("[-+]\\d{2}:\\d{2}$"; "Z") | fromdate) > $recent and .paired and (.connected | not)) | .address + " " + .name'))
echo "Found ${#devices[@]} paired device(s) not connected."
for dev in ${devices[@]}; do
addr=$(echo "$dev" | colrm 18)
name=$(echo "$dev" | colrm 1 18)
for retry in {1..3}; do
echo "Trying to connect to ${addr}: ${name}..."
if blueutil --connect ${addr} 2> /dev/null; then break; fi
[[ $retry == 3 ]] && echo "FAILED to connect to ${addr}: ${name}."
sleep 1
done
done
IFS=$_IFS
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requirements:
homebrew
(https://brew.sh/) andblueutil
(https://github.com/toy/blueutil) installed:$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
$ brew install blueutil