问题
I have a barcode scanner connected to my RasPi without any tty, which means headless without a monitor. In other words, a keylogger for number inputs. This scanner reads numerical barcodes like GTIN or EAN. It works, the script is started by sh on boot. The script I use looks like that:
import sys
tStr = ''
while 1:
fp = open('/dev/hidraw3', 'rb')
buffer = fp.read(8)
for c in buffer:
if c:
if c == 40 or c == 88: # [ENTER-key]
function_to_handle_result (tStr)
tStr = ''
elif c == 98 or c == 39:
c = 0
tStr = tStr + str(c)
elif c > 29 and c < 39:
c = c - 29
tStr = tStr + str(c)
elif c > 88 and c < 98:
c = c - 88
tStr = tStr + str(c)
Now I want the user to be able to input numbers manually, in case that the barcode is damaged and/or not readable, and connected a numeric keyboard. Each of these two devices work separately with the script above, if I know the virtual file and its number, like '/dev/hidraw3'.
Now I want to combine the inputs to be able to access the values in one script and one function, and I want to guess the right hidraw-path.
This is my approach, which seems logical to me, but doesn't work. There is no error message, it just does nothing. What am I doing wrong ?
import sys
from pathlib import Path
t = ''
def handle_c(c):
global t
if c == 40 or c == 88:
function_to_handle_result (t)
t = ''
elif c == 98 or c == 39:
c = 0
t = t + str(c)
elif c > 29 and c < 39:
c = c - 29
t = t + str(c)
elif c > 88 and c < 98:
c = c-88
t = t + str(c)
return
hid = {}
f = {}
b = {}
c = {}
while 1:
for i in range(10):
hid[i] = '/dev/hidraw'+str(i) # guessing path
if Path(hid[i]).exists(): # check if path exists
f[i] = open(hid[i], 'rb')
b[i] = f[i].read(8)
for c[i] in b[i]:
if c[i]:
handle_c(c[i])
In earlier approaches I did not use dynamical variables like here, with the same result, it does nothing.
Thanks for your help.
回答1:
you can use python-evdev
for accessing the numeric keyboard ( and also the barcode scanner ). it is a python implementation of the linux evdev
interface that is based on events generated by the input devices, i.e. HID ( https://en.wikipedia.org/wiki/Evdev )
http://python-evdev.readthedocs.io/en/latest/tutorial.html ( for multiple devices see Reading events from multiple devices )
in https://khanhicetea.com/post/read_input_from_usb_keyboard_in_linux/ is code for using evdev with barcode scanner
来源:https://stackoverflow.com/questions/47227502/python-3-try-to-read-from-multiple-hid-inputs-raspberry-pi