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: 
To discover a successfully established Bluetooth connection we can run

```
sdptool browse xx:xx:xx:xx:xx:xx

```

By this the SDB connection will be tested for a connection to the given MAC address. It may take considerable time until browsing times out with an error like

```
Failed to connect to SDP server on 00:0C:78:4F:B6:B5: Host is down

```

We don't know the exact purpose of your script, but most likely you wish to play audio via Clementine when a headset was connected.

Then we could just see whether there is a Bluetooth audio sink with

```
pacmd list-sinks | grep xx_xx_xx_xx_xx_xx

```

Where `xx_xx_xx_xx_xx_xx` is the MAC address (`:` needs to be replaced with `_`). The output will then tell you whether there is a Bluetooth audio sink available or nothing if not.

See [this answer](https://askubuntu.com/a/72076/3940) on how to switch audio to this sink.

---

### [Stream2ip](https://launchpad.net/stream2ip)

With **stream2ip** we can define a shell command or a script to run after a connection was established. There also is an option to automatically start a supported media player after a connection was established:

![enter image description here](https://i.stack.imgur.com/EiNvK.png)

Stream2ip will also try to reconnect the currently running playback stream to the Bluetooth audio device in case the connection was interrupted.
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.