September 3rd 2017

linux, udev

Creating Udev Rules

Mostly this article.
Most people will be using systemd now, so systemctl should be used instead of init/service etc.

As a proof of concept I wrote a rule that executes a script when my phone is connected via USB. The phone contains two devices with the same vendor and product ID, and the script could be called twice. So I adjusted it to additionally check for a unique serial::

ACTION=="add", SUBSYSTEM=="usb", \
ATTRS{idVendor}=="XXXX", ATTRS{idProduct}=="XXXX", \

The process of obtaining this info is outlined right at the top of the article.

saved as /etc/udev/rules.d/51-my-phone-add.rules.

A little improvement for Sending Notifications to the Current User from a Script Executed by Root

Instead of calling a wrapper script as a different user (as outlined in the article), create a function inside your bash script:

function notify {
    sudo -i -u username DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/1000/bus" notify-send "$1" "$2"

The user is hardwired here; this is just a hack that will work on most systems.
Please note running sudo with the -i option!
Please note that, according to the article two more environment variables are needed, but DBUS_SESSION_BUS_ADDRESS was sufficient for me. YMMV.

Now you can call this from inside the phoneconnect script with e.g.

notify "Doing things:" "Connecting phone..."