We'll be using udev for this, first off we'll start by writing the scripts we
want to run when the bluetooth device connects/disconnects. We'll save these
scripts in /bin/. As I only have a bluetooth headphone my shell scripts look
like this:
headphone_connected.sh:
#!/bin/sh
runuser -l USER -c 'notify-send "Headphone connected 🎧"'
and
headphone_disconnected.sh:
#!/bin/sh
runuser -l USER -c 'notify-send "Headphone disconnected 🎧"'
Where you change USER to your username (e.g for me arthur). This is needed as there's a complication of getting into the
x session from root, you don't need to worry about that. I already tried a lot of stuff and this works.
We now wish to run this as a bluetooth device gets connected, for this we'll have to create a udev rule. We do this by creating
a file in /etc/udev/rules.d/ We can call this whatever we want, but it needs to have the ".rules" extension. For example I
created the file BluetoothHeadphone.rules This file looks as follows:
BluetoothHeadphone.rules:
SUBSYSTEM=="bluetooth", ACTION=="add", RUN+="/bin/headphone_connected.sh"
SUBSYSTEM=="bluetooth", ACTION=="remove", RUN+="/bin/headphone_disconnected.sh"
And then we're done! Now we only have to reload udev:
sudo udevadm control --reload