9

I have a program running on Raspbian Stretch, talking to a mobile phone via USB, using a specialized protocol implemented on top of libusb.

I'd like the program to run on startup, so I make up a systemd service file, but not sure what target it should run after:

[Unit]
Description=My Program
After=network.target  <-- ???

[Service]
ExecStart=/home/pi/myprogram
User=root

[Install]
WantedBy=multi-user.target

This content can do the job, but what should it be after properly? How could I say "after USB is ready"?

Most info I can find on the web is about setting up udev rules, which I understand is to load a kernel module on seeing a certain device, which I don't think is what I want.

Any help is appreciated.

Nick Lee
  • 233
  • 1
  • 2
  • 6

2 Answers2

7

I have not solved this before, but it seems like it could be a good fit for "path-based activation".

Instead of having an "After=" clause in your service file, you would create a .path file, as described in man systemd.path.

Find a suitable file under /dev/bus/usb or /sys/bus/usb, whose presence indicates that "USB is up". Then have systemd monitor the file path using the .path file you'll create. The .path file would then activate your .service file when the file exists.

Mark Stosberg
  • 624
  • 3
  • 7
  • 1
    Thank you. I eventually monitor the path `/dev/bus/usb/001`. That's where Raspberry Pi's USB bus is. For anyone interested in a concrete example, [here](https://unix.stackexchange.com/a/203661/186939) is another nice answer. – Nick Lee May 17 '18 at 14:20
  • Forgive my ignorance... *"Find a suitable file under `/dev/bus/usb` or `/sys/bus/usb` ..."* - Isn't that Systemd's job? It seems like a service should only need to `After=USB.ready` or something similar. – jww Dec 25 '19 at 15:29
  • `After=` takes a system unit name and there is no USB service run by systemd, nor do systemd units represent events like "USB Ready". USB devices are represented on the system as files, so systemd's path-based activation is appropriate here, the alternate answer to create a "systemd device unit" is also good. – Mark Stosberg Jan 07 '20 at 20:22
6

What I would do is to create a systemd device unit using the an udev rule. E.g.: create /etc/udev/rules.d/20-usb-bus.rules with:

KERNEL=="usb[1-2]", TAG+="systemd"

At next boot (or udev rules reload) you will now have your system device unit:

# systemctl status dev-bus-usb-001-001.device
● dev-bus-usb-001-001.device - 2.0 root hub
...
# systemctl status dev-bus-usb-002-001.device
● dev-bus-usb-002-001.device - 3.0 root hub
...

You can now make your service start after USB bus is ready by adding:

[Unit]
...
After=dev-bus-usb-001-001.device dev-bus-usb-002-001.device

to your systemd service.

Diego
  • 201
  • 2
  • 3