Created
May 11, 2026 17:09
-
-
Save robjinman/9d7bea82d7f6315f695a2d3c1ee8db45 to your computer and use it in GitHub Desktop.
Poll events from input devices using libevdev
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <libevdev-1.0/libevdev/libevdev.h> | |
| #include <filesystem> | |
| #include <iostream> | |
| #include <vector> | |
| #include <fcntl.h> | |
| struct InputDevice | |
| { | |
| int fileDescriptor = 0; | |
| libevdev* device = nullptr; | |
| }; | |
| int main() | |
| { | |
| std::vector<InputDevice> devices; | |
| const std::string base = "/dev/input/event"; | |
| for (auto const& entry : std::filesystem::directory_iterator{"/dev/input"}) { | |
| auto path = entry.path().string(); | |
| if (path.starts_with(base)) { | |
| int i = std::stoi(path.substr(base.length())); | |
| if (i + 1 > devices.size()) { | |
| devices.resize(i + 1); | |
| } | |
| devices[i].fileDescriptor = open(path.c_str(), O_RDONLY | O_NONBLOCK); | |
| if (libevdev_new_from_fd(devices[i].fileDescriptor, &devices[i].device) < 0) { | |
| std::cerr << "Failed to init libevdev\n"; | |
| return 1; | |
| } | |
| std::cout << "Input device: " << libevdev_get_name(devices[i].device) << "\n"; | |
| } | |
| } | |
| while (1) { | |
| for (size_t i = 0; i < devices.size(); ++i) { | |
| auto& device = devices[i]; | |
| input_event event; | |
| auto result = libevdev_next_event(device.device, LIBEVDEV_READ_FLAG_NORMAL, &event); | |
| if (result == LIBEVDEV_READ_STATUS_SUCCESS) { | |
| std::cout << i << ": " << "Event: " << libevdev_event_type_get_name(event.type) << " " | |
| << libevdev_event_code_get_name(event.type, event.code) << " " << event.value << "\n"; | |
| } | |
| } | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment