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.
#!/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]
Exec=/home/cody/Documents/ 00:00:00:00:00:00

Leave a Reply

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

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

Facebook photo

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

Connecting to %s