How can I translate Linux keycodes from /dev/input/event* to ASCII in Perl?

后端 未结 4 666
梦谈多话
梦谈多话 2020-12-15 14:06

I\'m writing a Perl script that reads data from the infamous /dev/input/event* and I didn\'t find a way to translate the key codes generated by the kernel into

4条回答
  •  北海茫月
    2020-12-15 14:36

    To read the barcodes from a barcode reader I missed a simple application to get the pure key strokes into a string. That's by far easier to do a complete keyboard translation as the barcodes usually contain mostly numbers and some few normal ascii characters. So, perhaps, this simple python3 script may help as well others to get started. It requires python3-evdev as library. For sure, you may have to adapt the InputDevice. This works for the Manhatten reader.

    from evdev import InputDevice, categorize, ecodes
    
    dev = InputDevice('/dev/input/by-id/usb-040b_6543-if01-event-kbd')
    
    print(dev)
    
    shiftPressed = False
    ctrlPressed = False
    string = ""
    
    for event in dev.read_loop():
        if event.type == ecodes.EV_KEY:
            keyEvent = categorize(event)
            # handle release of special keys
            if keyEvent.keystate == 0:
                if keyEvent.keycode=="KEY_LEFTSHIFT":
                    shiftPressed = False
                    continue
                if keyEvent.keycode=="KEY_LEFTCTRL":
                    ctrlPressed = False
                    continue
            # handle key presses
            if keyEvent.keystate == 1:
                if keyEvent.keycode=="KEY_LEFTSHIFT":
                    shiftPressed = True
                    continue
                if keyEvent.keycode=="KEY_LEFTCTRL":
                    ctrlPressed = True
                    continue
                if ctrlPressed:
                    continue
    
                key = keyEvent.keycode[4:]
    
                if key == "ENTER":
                    print(string)
                    string = ""
                    continue
    
                dict2 = {"Z" : "Y", "Y": "Z"}
                if key in dict2:
                    key = dict2[key]
    
                if not (shiftPressed):
                    key = key.lower()
                else:
                    dict = {"0" : "=",
                            "1" : "!",
                            "2" : "\"",
                            "3" : "§",
                            "4" : "$",
                            "5" : "%",
                            "6" : "&",
                            "7" : "/",
                            "8" : "(",
                            "9" : ")"}
                    if key in dict:
                        key = dict[key]
                string+=key
    

提交回复
热议问题