Skip to content

Instantly share code, notes, and snippets.

@Romern
Last active April 8, 2022 11:52
Show Gist options
  • Save Romern/2a63b831b9b2b6a9723d1001e609fd1f to your computer and use it in GitHub Desktop.
Save Romern/2a63b831b9b2b6a9723d1001e609fd1f to your computer and use it in GitHub Desktop.
Script to poll for the buttons on a scanner and run a script if pressed. Currently just checks if any button is pressed, but could be easily adjustable.
#!/bin/bash -e
FOLDER="/home/roman/Scanned/"
PORT="$(lsusb | grep CanoScan | pcregrep -o1 "Bus ([0-9]*)")"
DEVICE="$(lsusb | grep CanoScan | pcregrep -o1 "Device ([0-9]*)")"
SCANBD_DEVICE="genesys:libusb:${PORT}:${DEVICE}"
scanimage --format jpeg -d ${SCANBD_DEVICE} --source Flatbed --resolution 300 -o /tmp/scan.jpg
tesseract /tmp/scan.jpg "${FOLDER}/scan_$(date +'%FT%T')" -l deu pdf
import sane
import time
import argparse
import os
import subprocess
parser = argparse.ArgumentParser(description="If any button on the scanner is pressed, run the script.")
parser.add_argument("script", help="Path to script which should be run on button press.")
parser.add_argument("--pollinginterval", default=1.0, help="Polling interval in seconds.")
parser.add_argument("--devicesubstring", default="LiDE 200", help="Substring to look for in device name.")
args = parser.parse_args()
while True:
try:
print("Initializing...")
sane.init()
device = next(d for d in sane.get_devices() if args.devicesubstring in str(d))
interface = sane.open(device[0])
options = [o[0] for o in interface.dev.get_options() if "button" in str(o)]
print("Polling...")
while True:
for o in options:
try:
is_pressed = interface.dev.get_option(o)==1
except:
is_pressed = False
if args.devicesubstring not in str(subprocess.check_output("lsusb")):
interface.close()
raise Exception("not connected!")
if is_pressed:
interface.close()
print("Running script...")
result = os.system(args.script)
interface = sane.open(device[0])
time.sleep(args.pollinginterval)
except Exception as e:
print(e)
sane.exit()
print("Device not working or not connected, sleep for a couple of seconds...")
time.sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment