6

What is a foolproof method to find the event device node for the hardware keyboard or mouse?

What I have tried is to read /proc/bus/input/devices and search for 'Keyboard' or 'Mouse' in the device name, but this doesn't work always, as the device names vary a lot.

The other option was to select the ones with Handlers=kbd and Handlers=mouseX, but on a laptop, there are other devices like 'Power button', 'Video bus' with Handlers=kbd too.

vikraman
  • 358
  • 7
  • 14

2 Answers2

0

This is example to find keyboard event:

const std::string get_dev_event_kbd()
{
    std::string sline, sdev="/dev/input/", sH="", sBEV="";
    std::ifstream ifs("/proc/bus/input/devices");
    auto trimstr=[](std::string &s)
    {
        int i=0, n=s.length(); //left
        while ((i<n)&&((s[i]==' ')||(s[i]=='\t'))) i++;
        s=(i>0)?s.substr(i):s;
        n=s.length()-1; i=n; //right
        while ((i>0)&&((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n')||(s[i]=='\r'))) i--;
        s=(i<n)?s.substr(0,i+1):s;
    };

    while (std::getline(ifs,sline).good())
    {
        if (sline[0]=='H')
        {
            sH=sline.substr(sline.rfind(" event"));
            trimstr(sH);
        }
        if (sline.substr(0,5)=="B: EV")
        {
            sBEV=sline.substr(sline.find('=')+1);
            trimstr(sBEV);
        }
        if (sBEV=="120013") break;
    }
    sdev+=sH;
    return sdev;
}

See: this and this for more details. Also, if you get error 13 (Permission denied) error when doing open() on the device, check if group 'input' is defined for it and add your user to the group

Community
  • 1
  • 1
slashmais
  • 7,069
  • 9
  • 54
  • 80
0

All input devices have &input_class value in the dev->class field. So you can iterate over all the devices and check for (dev->class == &input_class). Next, for each input device you have found you'll need to see if it has a valid keyboard/mouse device name (for ex. "mice", "mouse%d", etc).

Ilya Matveychikov
  • 3,936
  • 2
  • 27
  • 42