Friday, August 8, 2025

Udev Rules and Systemd Service for Auto Running python scripts on USB insert / removal

How to Run .py When usb is plugged/unplugged

1. /etc/udev/rules.d/99-gamepad.rules - CREATED

# Start service when F310 is plugged in
ACTION=="add", SUBSYSTEM=="input", ATTRS{idVendor}=="046d", ATTRS{idProduct}=="c216", KERNEL=="event*", TAG+="systemd", ENV{SYSTEMD_WANTS}="macros@%k.service"

# Stop service when F310 is unplugged
ACTION=="remove", SUBSYSTEM=="input", ENV{ID_MODEL}=="Logitech_Dual_Action", KERNEL=="event*", RUN+="/bin/systemctl stop macros@%k.service"

Purpose: Detects when the Logitech F310 gamepad (product ID c216) is plugged in or unplugged and triggers systemd service actions.

2. /etc/systemd/system/macros@.service - CREATED

[Unit]
Description=Logitech F310 Macros for %i
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/mint22/macros.py
Restart=on-failure
User=mint22
Group=mint22
Environment=HOME=/home/mint22
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Purpose: Systemd template service that runs the Python script when triggered by udev. The @ makes it a template service that can be instantiated with device names (like macros@event13.service).

3. /home/mint22/macros.py - EXISTING (permissions updated)

Changes made:

  • Ensured executable permissions: chmod +x /home/mint22/macros.py
  • Added user to input group: sudo usermod -a -G input mint22

Purpose: Your existing Python script that contains the gamepad macro functionality.

Commands Run to Apply Changes:

# Reload udev rules to recognize the new gamepad detection rule
sudo udevadm control --reload-rules

# Reload systemd to recognize the new service template
sudo systemctl daemon-reload

# Set proper permissions
chmod +x /home/mint22/macros.py
sudo usermod -a -G input mint22

How It Works:

  1. When F310 is plugged in → udev detects it → starts macros@eventX.service → runs macros.py
  2. When F310 is unplugged → udev detects removal → stops the service → terminates macros.py

The system automatically handles starting and stopping the script based on the physical presence of the gamepad.

No comments:

Post a Comment