Bluetooth Pairing Script using Expect in Bash

Needed a quick script to do automated pairing in Linux of already known bluetooth devices. I’m using my Switch and L4T Ubuntu to stream using Moonlight and hate having to repair my controllers every time.

Credit to RamonGilabert and the people in the below discussion for their work and iterations. My modification was removing expect of controller (since it wouldn’t work for me), raising the sleep from 5 to 10 on the scanning phase, and adding a connect at the end of the script to force connect the Joycons. Works pretty darn well if I do say so myself.

https://gist.github.com/RamonGilabert/046727b302b4d9fb0055
#!/usr/bin/expect -f

set prompt "#"
set address [lindex $argv 0]

spawn bluetoothctl
expect -re $prompt
send "remove $address\r"
sleep 1
expect -re $prompt
send "scan on\r"
send_user "\nSleeping\r"
sleep 10
send_user "\nDone sleeping\r"
send "scan off\r"
send "trust $address\r"
sleep 2
send "pair $address\r"
sleep 2
send "0000\r"
sleep 3
send_user "\nShould be paired now.\r"
send "connect $address\r"
send "quit\r"
expect eof

Also, as a bonus here is the below Launcher file to be placed on your desktop as “ControllerName.desktop” that does the invocation of the script. Basically just ripped off the Chromium Launcher file.

#!/usr/bin/env xdg-open

[Desktop Entry]
Version=1.0
Name=GreyLeft
Exec=/home/cody/Documents/bluetoothConnect.sh 00:00:00:00:00:00
Terminal=true
X-MultipleArgs=false
Type=Application
Icon=preferences-desktop-remote-desktop
Categories=Network;
MimeType=text/html;text/xml;application/xhtml_xml;x-scheme-handler/http;x-scheme-handler/https;
StartupNotify=true
Name[en_US]=GreyLeft.desktop

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s