I'd like to read button mappings from a text file that contains data like this:
DPAD_LEFT = 105
DPAD_RIGHT = 106
DPAD_UP = 103
DPAD_DOWN = 108
The right part is actually the evdev keycode (as defined in <linux/input.h>
).
This is quite hard to read, so I'd like to be able have files like this:
DPAD_LEFT = KEY_LEFT
DPAD_RIGHT = KEY_RIGHT
DPAD_UP = KEY_UP
DPAD_DOWN = KEY_DOWN
But I'm currently not able to convert them back:
char[256] keyname;
some_method_to_read(&keyname, "DPAD_LEFT");
//keyname now contains "KEY_LEFT"
How do I get the corresponding keycode (e.g. 105
)? Is there a standard way to do this?
EDIT: The only way I can think of right now is by duplicating all the keycodes in my source and putting them in an array or map, like the evtest
utility does. But there are a lot of keycodes and this seems quite a bit of overkill to me. Also, this might get out-of-sync with the keycodes defined in <input/linux.h>
at some point.
std::map<string, int> keynames;
#define MAP_KEYCODE(keycode) keynames[#keycode] = keycode
MAP_KEYCODE(KEY_LEFT);
MAP_KEYCODE(KEY_RIGHT);
MAP_KEYCODE(KEY_UP);
MAP_KEYCODE(KEY_DOWN);
// [...]
I found a way to do this properly: By using libevdev's libevdev_event_code_from_name
function.
unsigned int event_type = EV_KEY;
const char* name = "BTN_A";
int code = libevdev_event_code_from_name(event_type, name);
if(code < 0)
{
puts("There was an error!");
}