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. Since the phone contains two devices, the script would be called twice; so I adjusted it to check for a unique serial, in addition to vendor & product:

ACTION=="add", SUBSYSTEM=="usb", \
ATTRS{idVendor}=="XXXX", ATTRS{idProduct}=="XXXX", \
ATTR{serial}=="XXXXXXXXXXXXX", \
RUN+="/path/to/script/phoneconnect"

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..."

Sep 3rd, 2017