Skip to content

Instantly share code, notes, and snippets.

@SebastianGrans
Last active January 20, 2022 23:51
Show Gist options
  • Save SebastianGrans/99d5068d5eaa86b20f6a305e22fc76e9 to your computer and use it in GitHub Desktop.
Save SebastianGrans/99d5068d5eaa86b20f6a305e22fc76e9 to your computer and use it in GitHub Desktop.
Cycle the bluetooth connection to a device on MacOS
# The bluetooth connection to my stereo started crackling after being connected for a while.
# Reconnecting to it solved the problem, but got annoying to do manually.
#
# Installation:
# 1. Get the following dependencies
# * blueutil - https://github.com/toy/blueutil
# * terminal-notifier (optional) - https://github.com/julienXX/terminal-notifier
# 2. Find the MAC address of the bluetooth device of interest using `blueutil`
# * `blueutil --paired`
# 3. Add the function to your .bashrc (or .zshrc, etc.)
# * Make sure to add the address that you found to the script.
# 4. Source the aforementioned file.
# 5. Executing `fixstereo` should now cycle the connection with the device!
#
# You can then create an app using the built in Automator app which can be executed from spotlight.
#
function fixstereo () {
MAC_ADDRESS=>>write your mac address here<<
connected=$(blueutil --is-connected ${MAC_ADDRESS})
if [[ $connected -eq 1 ]]; then
echo "Stereo is connected. Trying to cycle the connection."
blueutil --disconnect ${MAC_ADDRESS}
retval=$?
if [[ $retval -ne 0 ]]; then
terminal-notifier -title 'Could not disconnect stereo' -message 'Blueutil error code: ${retval}'
return $retval
fi
fi
echo "Stereo is disconnected. Let's try to connect!"
blueutil --connect ${MAC_ADDRESS}
retval=$?
if [[ $retval -ne 0 ]]; then
terminal-notifier -title 'Could not reconnect to stereo'
return $retval
fi
if [[ $connected -eq 1 ]]; then
terminal-notifier -title 'Successfully cycled the stereo connection' -message ''
else
terminal-notifier -title 'Successfully connected to the stereo' -message ''
fi
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment