Autoconnecting Bluetooth Devices

Is there a way to set the Bluetooth in Ubuntu to autoconnect to devices it is paired to when it is turned on. Furthermore, is there a way to automatically change the sound output to a Bluetooth headset on connection?


Pulseaudio >= 1.0

By editing the /etc/pulse/default.pa we can load the pulseaudio module module-switch-on-connect to autoconnect to an audio sink as soon as it is presented to the pulseaudio sound server. We need to insert the following line

load-module module-switch-on-connect

Previous versions of pulseaudio

Bluetooth devices are recognized in PulseAudio as soon as they are present. However connection needs to be made manually in audio settings. There is a GUI that allows one-click connection to BT devices (stream2ip).

Edit: From version 0.2.5 stream2ip allows auto-connecting to Bluetooth devices.

Edit: you can set up your bluez device as default device (e.g. by using pactl or in the config settings) with fallback to internal audio if no bluetooth device is present.

Edit: Here is a quick and dirty Python script to give you an idea on how to do the job:

#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# bt-autoconnect
# Autoconnects Bluetooth Devices to PulseAudio
# (c) Takkat Nebuk
# Licence: GPLv3
# usage:
# bt-autoconnect <MAC> <timeout>

import subprocess
import time
import sys
import string

cli_options = sys.argv

def main():
    MAC = cli_options[1]
    timeout = cli_options[2]
    PMAC = string.replace(MAC,':','_') # PA don't know ':', needs '_'
    pa_args = ['pacmd set-default-sink bluez_sink.' + PMAC]
    bt_args = ['sdptool browse ' + MAC]
    err = False
    while err == False:
        if subprocess.call(bt_args, shell=True) == 0:
            err = subprocess.call(pa_args, shell=True)
        time.sleep(int(timeout))
    exit()

if __name__ == "__main__":
    main()

Just copy this script and save it as bt-autoconnect.py. Make the script executable or run it from command line (recommended) by cd /script/directory and then type:

python bt-autoconnect.py [MAC] [timeout]

Replace MAC by the MAC of your Bluetooth device (e.g. 00:0C:78:4F:B6:B5) and set a desired timeout (e.g. 10) in seconds when the script looks for the device. This script will then listen to the given MAC every timeout seconds for a Bluetooth device and connects it to PulseAudio if present. The script will run forever until it's being killed or the virtual terminal was closed.

Sometimes PulseAudio seems not to be aware of the device being present again after it has been switched out. With some hope pulseaudio -k makes it reappear.

Not fancy, no GUI but at least in my settings it worked o.k..

Edit for those interested: bt-autoconnect with GUI for convenient setup is released. Please file bugs or suggestions there. Thank you for testing.