Linux udev Rules to Run pactl

linuxudev

Trying to check if an a2dp profile exists each time a bluetooth device connects/disconnects. I created two udev rules:

# ACTION=="add", SUBSYSTEM=="bluetooth", RUN+="/bin/sh -c '/home/myuser/on-connect-bluetooth.sh > /tmp/on-connect-bluetooth.log 2>&1'"
# ACTION=="remove", SUBSYSTEM=="bluetooth", RUN+="/bin/sh -c '/home/myuser/on-connect-bluetooth.sh > /tmp/on-connect-bluetooth.log 2>&1'"

The script use pactl list short to check the presence of an a2dp.sink. The script works when executed from the command line but when executed by udev, I get:

Connection failure: Connection refused
pa_context_connect() failed: Connection refused

I tried using sudo -u myuser pactl list short to no avail, I get the same result.

How can I execute pactl from a script executed by a udev rule?

Best Answer

You have multiple problems in here:

(1) Pulseaudio is by default per-user, not system wide, so you can only access it as the user for which it is started. See here for more details.

(2) udev rules run in a very restricted environment.

One possible solution is to use Bluetooth tools (which are a mess, too, I know) to find out if the a2dp profile exists.

The current generation of the Bluetooth tools is so horribly integrated with the rest of the system that it is unlikely you'll find anything in /sys/device. Last time I looked, everything interesting was hidden behind some badly documented DBUS API.

Related Question