Skip to content

Instantly share code, notes, and snippets.

@gareve
Created June 8, 2023 16:05
Show Gist options
  • Save gareve/0a75f284650d8d74055aa8c7c31a5e3d to your computer and use it in GitHub Desktop.
Save gareve/0a75f284650d8d74055aa8c7c31a5e3d to your computer and use it in GitHub Desktop.
[USB Foot Pedal] Trigger a terminal command with your foot

Problem

While working on scripts, I execute it hundreds of times while iterating on it (big fan of baby steps approach).

To run my script, I usually have to switch focus to my terminal & run the last command, which makes me lose a bit of focus after the 10th+ time.

One solution is to use a file monitor that runs a command everytime a file gets modified, but in my experience, for most scripts I want to decide when to rerun the script.

After buying a USB foot pedal, I was wondering how can I use it to automate this small inconvenience.

Solution

Run an arbitrary terminal command everytime we detect a USB device event in Python.

Python Code below

Explanation Video on https://www.youtube.com/watch?v=VaVcv8CMePw

# $ sudo evtest
# No device specified, trying to scan all of /dev/input/event*
# Available devices:
# /dev/input/event24: PCsensor FootSwitch
# Select the device event number [0-24]: ^C
import os
import argparse
from evdev import InputDevice, ecodes, KeyEvent
RED = '\033[91m'
GREEN='\033[92m'
ENDCOLOR='\033[0m'
parser = argparse.ArgumentParser(description='Process a command on every button press of a foot pedal')
parser.add_argument('--device', required=True,help='Input Device e.g. /dev/input/event22. Find it with $ evtest')
parser.add_argument('cmd',help='Command to be run on every key press')
args = parser.parse_args()
print(args.device)
if os.geteuid() != 0:
print(f"{RED}USB handling needs root to run{ENDCOLOR}")
raise Exception('Needs to run as root')
device = InputDevice(args.device)
print(f"{GREEN}{device}{ENDCOLOR}")
print(f"{GREEN}Getting exclusive access to input device{ENDCOLOR}")
print(f"cmd$ {GREEN} {args.cmd}{ENDCOLOR}")
device.grab()
try:
for event in device.read_loop():
if event.type == ecodes.EV_KEY and event.value == KeyEvent.key_up:
os.system(args.cmd)
finally:
print(f"{GREEN}Releasing exclusive access to input device{ENDCOLOR}")
device.ungrab()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment