Skip to content

Instantly share code, notes, and snippets.

@CLCL

CLCL/barcode.py

Last active Jul 15, 2019
Embed
What would you like to do?
バーコードスキャナのHIDデバイスをつないで、コンソールでスクリプトを実行したら入力待ち、スキャンしたら画面に表示する。
#!/usr/bin/python3
#https://codeday.me/jp/qa/20190304/361513.html
import signal, sys
import evdev
from evdev import InputDevice, ecodes, list_devices, categorize
# キースキャンコードとキャラクターの対応リスト
scancodes = {
# Scancode: ASCIICode
2: '1', 3: '2', 4: '3', 5: '4',
6: '5', 7: '6', 8: '7', 9: '8',
10: '9', 11: '0', 28: 'CRLF'
}
barCodeDeviceString = 'USB BARCODE SCANNER USB BARCODE SCANNER'
devices = map(InputDevice, list_devices())
for device in devices:
print(device.name)
if device.name == barCodeDeviceString:
dev = InputDevice(device.path)
if not 'dev' in locals():
sys.exit("Device '{barCodeDeviceString}' not connected.".format(**locals()))
def signal_handler(signal, frame):
print("\nStopping")
dev.ungrab()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
dev.grab()
def main():
code = ''
for event in dev.read_loop():
if event.type == evdev.ecodes.EV_KEY:
data = evdev.categorize(event)
if data.keystate == 1: # Down events only
key_lookup = scancodes.get(data.scancode) or ''
if key_lookup == 'CRLF':
print(code)
code = ''
else:
code += key_lookup
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment