Question: I'd like to start my music player (Clementine) when my bluetooth headset connects to my computer. How do I detect the bluetooth device connecting so I can run a script to start the player?

Answer: 
I didn't like the polling approach, so I did some digging on bluez and DBus. I ended up writing the following script:

```
#!/usr/bin/python

import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gobject

import subprocess

# ID of the device we care about
DEV_ID = '00_1D_54_AB_DC_72'

dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)

# Figure out the path to the headset
man = bus.get_object('org.bluez', '/')
iface = dbus.Interface(man, 'org.bluez.Manager')
adapterPath = iface.DefaultAdapter()

headset = bus.get_object('org.bluez', adapterPath + '/dev_' + DEV_ID)
    # ^^^ I'm not sure if that's kosher. But it works.

def cb(iface=None, mbr=None, path=None):

    if ("org.bluez.Headset" == iface and path.find(DEV_ID) > -1):
        print 'iface: %s' % iface
        print 'mbr: %s' % mbr
        print 'path: %s' % path
        print "\n"
        print "matched"

        if mbr == "Connected":
            subprocess.call(["clementine", "--play"])
            print 'conn'

        elif mbr == "Disconnected":
            subprocess.call(["clementine", "--stop"])
            print 'dconn'

headset.connect_to_signal("Connected", cb, interface_keyword='iface', member_keyword='mbr', path_keyword='path')
headset.connect_to_signal("Disconnected", cb, interface_keyword='iface', member_keyword='mbr', path_keyword='path')

loop = gobject.MainLoop()
loop.run()

```
You write "when your headset connects to your computer". How does it do that, automatically? When you have to trigger it manually, you might as well make it a script and then run your script after the connection has been established. This is what I did to set the default output device to my bluetooth receiver (so I can change the volume with the hardware keys):

```
bluetooth-connect && pactl set-default-sink bluez_sink.0C_A6_94_9A_37_4D

```

Where `bluetooth-connect` looks like this: <https://github.com/sblask/dotfiles/blob/c39d37ad67947b358b4a079cb41ae6f9e4a081d8/.bin/bluetooth-connect.symlink> It assumes everything has been paired and is ready to connect. You find the MAC address in blueman or by running `pacmd list-sinks | grep -e 'name:' -e 'index'` when the bluetooth device is connected. You would want run `bluetooth-connect && your-script`. `your-script` will only be run when the connection was established successfully.