Run service based on whether device is plugged in

Is there a way to start/stop a daemon based on whether a device is plugged in?

I note there is a “before” and “after” keyword added now but this only refers to internal snap daemons, not say dev-ttyACM0.device.

Another example would be to only start a daemon if there is a working network connection, e.g after=network-online.target.

Do you mean something like BindsTo=?

Not at this time, but it’s a feature worth discussing. The key problem is that we cannot allow snaps to depend too much on the local system for that sort of behavior, as they need to work across systems and across Linux distributions that have slightly different conventions for it.

For example, it doesn’t really make sense in general to allow a snap to, by default, start a service if /dev/ttyACM0 exists. Either this needs to be done locally by the administrator with some sort of command, or we need to tie this feature in with an interface and with the Hotplug feature that we’ve been slowly landing in the last few months. The latter would allow, for example, the snap to declare a plug for a particular interface (serial? modem?) and then the service might get started when that interface is connected. This mechanism would work on any system, any distribution, and no matter what the particular name of /dev/ttyACM0 is right now, for example.

while hotplug and/or a way to ship a udev rule would be optimal here, a snap using the hardware-observe interface can use udevadm monitor or you can create a daemon in your snap watching the system dbus for udev events and have this daemon act accordingly … a (very hackish, but well working) example that uses a combination of hardware-observe, udisks2 and network-setup-control to import a netplan.yaml in a user-less kiosk image is at:

https://github.com/ogra1/dashkiosk-image-config/blob/master/netplan-import

as an interim workaround, something similar (and probably not in shell :wink: but with a proper dbus monitor in go or python) should be possible for a serial device provided the gadget actually offers an interface to talk to this device node already and this interface is connected.