Script to reconnect Bluetooth device in Linux

Example of a radio with iPod dock connector, now with Bluetooth receiver

Today I wasted several hours to write a small script that helps you to use a Bluetooth audio device with several Linux computers.

Problem: Several computers, one Bluetooth receiver

Our radio in the kitchen got upcycled with a Bluetooth receiver that fits into the obsolete 30 pin iPod dock connector. This receivers are cheap and easy and help lots of devices to get an interface to modern equipment.

Unfortunately our receiver can only handle one pairing, which means that every-time my girlfriend used the radio before me, I had to open the KDE bluedevil menu to delete, search and newly connect the device before I could listen to music in the kitchen (and vice versa). Time consuming and annoying.

Linux and Bluetooth

Bluetooth is a very common standard to connect phones and computers to audio devices like headphones and loudspeakers. But for Linux users Bluetooth is not the easiest thing and it's known to be not very well documented. OK, the Bluetooth standard changes more often than other technologies and the Linux Bluetooth tools improved as well, but also the tool names changed more then once and there was also the chance from pure ALSA to PulseAudio…

None of that helped me today to find a quick, simple solution for my small problem. I found numerous old guides for long gone tools and interfaces and the current Linux Bluetooth tools are not built to be run from scripts?!

Solution

OK, after many searches, try and errors and climbing up from the legacy tools to the more recent ones I managed to have a script that:

  • Deletes a connection to previously used Bluetooth device
  • Scans for Bluetooth devices
  • Creates a new connection incl. pairing to the deleted device.

connect-i-link.sh

#!/bin/bash

# remove old connection 
echo -e 'power on\ndisconnect EB:06:BF:0A:13:6F\nremove EB:06:BF:0A:13:6F\nquit' | bluetoothctl

# scan bluetooth devices for 20 s
timeout -k 20 15 bt-adapter --discover

# create a new pairing and connection
bt-device --connect EB:06:BF:0A:13:6F

# the command above does not connect audio, so do again a connection with bluetoothctl
echo -e 'trust EB:06:BF:0A:13:6F\nconnect EB:06:BF:0A:13:6F\ninfo EB:06:BF:0A:13:6F\nquit' | bluetoothctl

You have to replace the MAC address (EB:06:BF:0A:13:6F) in the script with the address of your device. You find this address in bluedevil or with bluetoothctl (command: scan on)

To get Bluetooth audio working in recent Linux distributions (> 2018) you have to install:

apt install bluez bluez-tools bluez-firmware pulseaudio-module-bluetooth

Discussion

Enter your comment. Wiki syntax is allowed:
D​ W A I V
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International