| 1 | // SPDX-FileCopyrightText: 2025 Raphael Rosch <[email protected]> |
| 2 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 3 | |
| 4 | #include "udev_monitor.hpp" |
| 5 | #include <cstring> |
| 6 | #include <iostream> |
| 7 | #include <stdexcept> |
| 8 | |
| 9 | UdevMonitor::UdevMonitor() |
| 10 | { |
| 11 | udev = udev_new(); |
| 12 | if (!udev) throw std::runtime_error("udev_new() failed"); |
| 13 | |
| 14 | monitor = udev_monitor_new_from_netlink(udev, "udev"); |
| 15 | if (!monitor) throw std::runtime_error("udev_monitor_new_from_netlink() failed"); |
| 16 | if (udev_monitor_filter_add_match_subsystem_devtype(monitor, "input", nullptr) < 0) { |
| 17 | udev_monitor_unref(monitor); |
| 18 | udev_unref(udev); |
| 19 | throw std::runtime_error("Failed to add subsystem filter"); |
| 20 | } |
| 21 | if (udev_monitor_enable_receiving(monitor) < 0) { |
| 22 | udev_monitor_unref(monitor); |
| 23 | udev_unref(udev); |
| 24 | throw std::runtime_error("udev monitor enable receiving failed"); |
| 25 | } |
| 26 | |
| 27 | fd = udev_monitor_get_fd(monitor); |
| 28 | if (fd < 0) { |
| 29 | udev_monitor_unref(monitor); |
| 30 | udev_unref(udev); |
| 31 | throw std::runtime_error("Invalid file descriptor from udev monitor"); |
| 32 | } |
| 33 | |
| 34 | auto channel = Glib::IOChannel::create_from_fd(fd); |
| 35 | channel->set_encoding(); // Binary |
| 36 | channel->set_buffered(false); |
| 37 | |
| 38 | watch = Glib::signal_io().connect( |
| 39 | sigc::mem_fun(*this, &UdevMonitor::on_io_event), |
| 40 | channel, |
| 41 | Glib::IO_IN); |
| 42 | } |
| 43 | |
| 44 | UdevMonitor::~UdevMonitor() |
| 45 | { |
| 46 | if (watch) { |
| 47 | watch.disconnect(); // disconnect GLib watch |
| 48 | } |
| 49 | if (monitor) { |
| 50 | udev_monitor_unref(monitor); |
| 51 | monitor = nullptr; |
| 52 | } |
| 53 | if (udev) { |
| 54 | udev_unref(udev); |
| 55 | udev = nullptr; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | bool UdevMonitor::on_io_event(Glib::IOCondition) |
| 60 | { |
| 61 | struct udev_device* dev = udev_monitor_receive_device(monitor); |
| 62 | if (dev) { |
| 63 | const char* action = udev_device_get_action(dev); |
| 64 | const char* devnode = udev_device_get_devnode(dev); |
| 65 | if (devnode && strstr(devnode, "/js")) { |
| 66 | signal_joystick_event.emit(action ? action : "", devnode); |
| 67 | } |
| 68 | udev_device_unref(dev); |
| 69 | } |
| 70 | return true; // Keep watching |
| 71 | } |