Skip to content

Instantly share code, notes, and snippets.

@wvengen
Last active February 22, 2024 13:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wvengen/03b9f57f6c3909a20749 to your computer and use it in GitHub Desktop.
Save wvengen/03b9f57f6c3909a20749 to your computer and use it in GitHub Desktop.
Hack to use Android phone as barcode scanner for pc
#!/usr/bin/env ruby
#
# Hack to use Android phone as barcode scanner for pc.
#
# Installation and setup:
# * Enable usb debugging on your Android phone
# * Make sure you have an Android SDK installed
# * Make sure xdotool is installed (apt-get has it) http://www.semicomplete.com/projects/xdotool/
# * Build and install https://github.com/majido/clipper
# * Start service: `adb shell su -c \'am startservice ca.zgrs.clipper/.ClipboardService\'`
# * Start barcode scanning app like https://f-droid.org/repository/browse/?fdid=com.google.zxing.client.android
# * Make sure _copy to clipboard_ is enabled in preferences
# * Adapt the method `action` in this file to your use
#
# Usage:
# * Make sure computer can connect to phone through adb (usb cable)
# * Start this script on computer (you probably need Linux or related)
# * Start barcode scan app on phone
# * Rinse, repeat
#
# customize this method to do something with the scanned barcode
def action(barcode)
# open url and wait until a window the specified title is present
openurl 'https://books.google.com/?hl=en', 'Google Books'
# type these keys into the current window
injectkey "alt+s"
injectkeys barcode + "\t "
end
def getclip
r = `adb shell am broadcast -a clipper.get`
r =~ /data="(.*)"\s*$/ and $1
end
def openurl(url, title)
%x(xdg-open '#{url}')
%x(xdotool search --sync --limit 1 '#{title}' windowfocus)
end
def injectkey(s)
%x(xdotool key '#{s}')
end
def injectkeys(s)
%x(xdotool type --delay 50 '#{s}')
end
lastclip = nil
while true do
clip = getclip
if clip =~ /^[0-9]+$/ && clip != lastclip
puts "scan #{clip}"
action clip
end
lastclip = clip
sleep 0.5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment