Start program when inserting / removing an USB device

For my digital signage / kiosk system I want to start a slideshow when inserting an USB stick and show a splash screen when no USB stick is inserted. This is how I did it.

Enable USB automounting

Enable automounting of a (single) USB stick in read-only mode to /mnt/usb1 when inserting it. Add a line to to /etc/fstab:

/dev/sda1 /mnt/usb1 auto noatime,ro,nofail,noauto,x-systemd.automount

Install an image viewer

Install FIM (manpage) framebuffer image viewer:

sudo apt install fim

Create a slideshow service

Create a new systemd service file /lib/systemd/system/slideshow.service that will start a slideshow using fim and reads images from our automounted directory /mnt/usb1:

[Unit]
Description=Digital signage slideshow using FBI
Conflicts=splash.service

[Service]
StandardInput=tty
StandardOutput=tty
ExecStart=/usr/bin/fim -a -q --no-history /mnt/usb1/ --sort -c 'while(1){display;sleep "10";next;}'
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target

Create splash screen service

We need to show our splash screen initially on boot, so create new systemd service file /lib/systemd/system/splash.service. t expects a splash image in /usr/share/kiosk/splash.png:

[Unit]
Description=Digital signage splash using FBI
DefaultDependencies=no
After=local-fs.target
Conflicts=slideshow.service

[Service]
StandardInput=tty
StandardOutput=tty
Type=oneshot
ExecStart=/usr/bin/fim -a -q --no-history /usr/share/kiosk/splash.png
Restart=on-failure
RestartSec=2

[Install]
WantedBy=sysinit.target

Enable the service in systemd:

sudo systemctl enable splash.service

When editing your unit files remember to reload them using:

sudo systemctl daemon-reload

Create a UDEV rule

We need an UDEV rule to trigger when the stick is inserted and removed. Create a new file /etc/udev/rules.d/99-usbstick.rules that will start the appropriate services as root:

ACTION=="add", SUBSYSTEM=="block", SUBSYSTEMS=="usb", RUN{program}+="/usr/bin/systemctl --no-block stop splash.service", RUN{program}+="/usr/bin/systemctl --no-block start slideshow.service"
ACTION=="remove", SUBSYSTEM=="block", SUBSYSTEMS=="usb", RUN{program}+="/usr/bin/systemctl --no-block stop slideshow.service", RUN{program}+="/usr/bin/systemctl --no-block start splash.service"

Reload you UDEV rules and restart the UDEV service:

sudo udevadm control --reload-rules && sudo service systemd-udevd --full-restart

Published by HorstBaerbel

Software developer by trade and interest, but I venture into the electronics- and diy-world from time to time.

2 thoughts on “Start program when inserting / removing an USB device

Leave a comment

Design a site like this with WordPress.com
Get started