Created
August 11, 2023 17:58
-
-
Save killbus/d177f7e5cb731feee06dd03fb9d0ba16 to your computer and use it in GitHub Desktop.
Linux bluetoothctl auto pair and connect device
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 | |
# The MAC address of the Bluetooth device to remove and connect | |
DEVICE_MAC="AA:AA:AA:AA:AA:AA" | |
# Create a coprocess for bluetoothctl | |
coproc bluetoothctl | |
# Function to send a command to the coprocess | |
send_command() { | |
echo "$1" >&"${COPROC[1]}" | |
} | |
# Send initial commands to remove the device and start scanning | |
send_command "remove $DEVICE_MAC" | |
send_command "scan on" | |
# Wait for the device to be discovered | |
TIMEOUT=30 # Set a timeout of 30 seconds | |
connected=1 | |
while [ $TIMEOUT -gt 0 ]; do | |
# Attempt to connect to the device | |
send_command "connect $DEVICE_MAC" | |
read -t 1 -u "${COPROC[0]}" output | |
# Check if the connection attempt was successful | |
if [[ "$output" == *"Connection successful"* ]]; then | |
echo "Device $DEVICE_MAC removed (if paired), scanned for, and reconnected (if found)." | |
connected=0 | |
break | |
fi | |
sleep 1 | |
((TIMEOUT--)) | |
done | |
# Stop scanning | |
send_command "scan off" | |
# Close the coprocess | |
exec {COPROC[1]}>&- | |
exec {COPROC[0]}<&- | |
if [ $connected -eq 1 ]; then | |
echo "Device $DEVICE_MAC was not rediscovered during scanning or was never paired." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment