简体   繁体   English

Linux 和 bash - 如何获取输入设备事件的设备名称?

[英]Linux and bash - How can I get the device name of an input device event?

I'm trying to automate the process of getting a game controller's device event and checking its name, then if the name matches a string, pass the event to another program.我正在尝试自动化获取游戏控制器的设备事件并检查其名称的过程,然后如果名称与字符串匹配,则将事件传递给另一个程序。

By hand, I run evtest /dev/input/eventXX to check the name of the input device, then keyboard interrupt(ctrl-c) to stop it.手动,我运行evtest /dev/input/eventXX来检查输入设备的名称,然后键盘中断(ctrl-c)来停止它。 If that device matches the name of a certain type of game controller, I run the command xboxdrv --evtest /dev/input/eventXX with the same event number.如果该设备与某种类型的游戏控制器的名称匹配,我xboxdrv --evtest /dev/input/eventXX使用相同的事件编号运行命令xboxdrv --evtest /dev/input/eventXX

However, because the "evtest" command continues to print the input device's outputs instead of terminating after printing the name and only exits on keyboard interrupt, I'm not sure how I could have the bash script get the name of the device.但是,因为“evtest”命令继续打印输入设备的输出而不是在打印名称后终止并且仅在键盘中断时退出,所以我不确定如何让 bash 脚本获取设备的名称。

I'm still learning bash so there may be syntax errors in my code.我仍在学习 bash,所以我的代码中可能存在语法错误。 But, here it is:但是,这里是:

#!/bin/sh
WiiUGCName="Wii U Gamecube Adapter Port"

#find the controller(s)
NumberOfEvents=$(ls /dev/input | grep -c event*)

echo "Number of input devices: $NumberOfEvents"

#launch xboxdrv for each controller
i=0
while [ $i < $NumberOfEvents ]; do
    echo "loop"
    OccurrencesOfName=$(evtest /dev/input/event$i | grep -c "$WiiUGCName")
    echo "Occurrences: $OccurrencesOfName"
    if [ $OccurrencesOfName>0 ]; then
        echo "Controller found"
        #launch xboxdrv here
    else
        echo "no controller found"
    fi
    let i=i+1
done

All this code actually does right now is hang at that evtest since it cannot be terminated.所有这些代码现在实际上都挂在那个evtest因为它不能被终止。

The simplest option is to give evtest some reasonable time to print the interesting portion of the output, say 1 second, and then kill it.最简单的选择是给evtest一些合理的时间来打印输出的有趣部分,比如 1 秒,然后evtest它。 If you place that code in a shell function, the resulting code can remain readable.如果将该代码放在 shell 函数中,则生成的代码可以保持可读性。 For example, replace:例如,替换:

OccurrencesOfName=$(evtest /dev/input/event$i | grep -c "$WiiUGCName")

with the invocation of a shell function:调用shell函数:

OccurrencesOfName=$(evtest_and_exit | grep -c "$WiiUGCName")

evtest_and_exit can be defined as follows: evtest_and_exit可以定义如下:

evtest_and_exit() {
    local evtest_pid
    evtest /dev/input/event$i &
    evtest_pid=$!
    sleep 1  # give evtest time to produce output
    kill $evtest_pid
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM