Skip to content

Instantly share code, notes, and snippets.

@oneyb
Created September 20, 2018 08:17
Show Gist options
  • Save oneyb/19fd2e2df74344d205846da944ab0537 to your computer and use it in GitHub Desktop.
Save oneyb/19fd2e2df74344d205846da944ab0537 to your computer and use it in GitHub Desktop.

Sync stuff automatically once it’s plugged in

This strategy worked for me: https://www.pcsuggest.com/run-shell-scripts-from-udev-rules/

The contents of /etc/udev/rules.d/phone-plugin.rules follow.

# The following is killed as the documentation explains about `RUN'
# ACTION=="add",ATTRS{idVendor}=="04e8",ATTRS{idProduct}=="6860",RUN+="/bin/su oney -c /home/oney/bin/.sync_phone.sh | at now"
# The service activated is a USER service, so the following doesn't work
# ACTION=="add",ATTRS{idVendor}=="04e8", ATTRS{idProduct}=="6860",TAG+="systemd",ENV{SYSTEMD_WANTS}="sync-phone.service" 
# The following rule works just right :)
ACTION=="add",ATTRS{idVendor}=="04e8",ATTRS{idProduct}=="6860",TAG+="systemd",ENV{SYSTEMD_USER_WANTS}="sync-phone.service" 

Which calls the user service sync-phone.service.

[Unit]
Description=Automatically sync phone with udev and systemd

[Service]
WorkingDirectory=%h
Type=oneshot
ExecStart=%h/bin/.sync_phone.sh
StandardOutput=journal

[Install]
WantedBy=multi-user.target

Which is activated as follows.

systemctl --user enable sync-phone

And that’s it. Whenever I plug my android phone into the USB port udev starts the specified service which has great logging through journalctl -xef. Syncthing would be easier but for huge files (music collections) that can be a drain on battery. Systemd is nice and udev is pretty handy (for those who prefer wires).

Continue reading to see where I failed.

I couldn’t get just systemd to work

https://blog.tjll.net/systemd-for-device-activation-and-media-archiving/#hardware

From:

systemctl --all --full -t device

I get the systemd device info, which I use to create and enable the following service \~/.config/systemd/user/sync-phone-systemd.service.

[Unit]
Description=Automatically sync phone with *just* systemd
After=dev-serial-by-id-usb-SAMSUNG_SAMSUNG_Android_iSerialRemoved-if01.device
BindsTo=dev-serial-by-id-usb-SAMSUNG_SAMSUNG_Android_iSerialRemoved-if01.device
Requisite=dev-serial-by-id-usb-SAMSUNG_SAMSUNG_Android_iSerialRemoved-if01.device

[Service]
WorkingDirectory=%h
Type=oneshot
ExecStart=%h/bin/.sync_phone.sh
StandardOutput=journal

[Install]
WantedBy=dev-serial-by-id-usb-SAMSUNG_SAMSUNG_Android_iSerialRemoved-if01.device

But I get a timeout error. Bummer. Any ideas why this strategy would not work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment