Skip to content

Instantly share code, notes, and snippets.

@thiagozs
Forked from AndBondStyle/bluetooth-reconnect
Created April 24, 2023 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagozs/fbac560bce63109b6deb270f28d75822 to your computer and use it in GitHub Desktop.
Save thiagozs/fbac560bce63109b6deb270f28d75822 to your computer and use it in GitHub Desktop.
Simple linux service for brute-force bluetooth auto-connection

bluetooth-reconnect

Inspired by bluetooth-autoconnect, but much simplier and actually works. Based on systemd service (daemon) which does the following, repeatedly:

  1. Run check command (e.g. check if device exists). If it returns zero, continue.
  2. Try to run bluetoothctl connect <MAC>. No checks if bluetooth is on, etc. Dead simple.
  3. Sleep for delay seconds (configurable).

How to install

git clone https://gist.github.com/bc178789a441ce73b51e1e0637393aac.git bluetooth-reconnect && cd bluetooth-reconnect
sudo chmod +x bluetooth-reconnect
# Edit `bluetooth-reconnect` file according to your needs. Try if it works with ./bluetooth-reconnect
sudo cp bluetooth-reconnect /usr/bin
sudo cp bluetooth-reconnect.service /etc/systemd/system
sudo systemctl enable bluetooth-reconnect
sudo systemctl start bluetooth-reconnect
# Check if it's alive
sudo systemctl status bluetooth-reconnect

References

#!/bin/bash
# Miminum delay between iterations, in seconds
delay=10
# Pairs of [bluetooth MAC, test expression]
targets=(
"98:B6:E9:47:F0:4F" "test ! -e /dev/input/js0"
"98:B6:E9:72:6C:31" "test -z \"\$(bluetoothctl info 98:B6:E9:72:6C:31 | grep 'Connected: yes')\""
)
function try_target() {
if eval $2
then
echo "Target $1 (check: $2) -> check true, trying to connect";
bluetoothctl connect "$1";
else
echo "Target $1 (check: $2) -> check false, skipping"
fi
}
last_time=$(date +%s)
while true
do
# seq args: <start> <step> <end>
for i in $(seq 1 2 ${#targets[@]});
do try_target "${targets[i-1]}" "${targets[i]}"
done
curr_time=$(date +%s)
elapsed=$((curr_time - last_time))
loop_delay=$((elapsed>delay ? 0 : (delay-elapsed)))
echo "Loop finished, sleeping for $loop_delay sec"
sleep $loop_delay
last_time=$(date +%s)
done
[Unit]
Description=Bluetooth reconnect service
Before=bluetooth.service
[Service]
ExecStart=/usr/bin/bluetooth-reconnect
[Install]
WantedBy=bluetooth.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment