From 0998cc370d09e0240732482662459eca22a2a234 Mon Sep 17 00:00:00 2001 From: Kevin Pearson Date: Thu, 1 Oct 2020 10:55:03 -0400 Subject: [PATCH] Add error context to failures to open devices This should address common misconceptions of "No matching or compatible device found" by isolating permission problems from lack of a matching device in the system. --- src/classes/Keyboard.cpp | 8 ++++++++ src/main.cpp | 12 +++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/classes/Keyboard.cpp b/src/classes/Keyboard.cpp index b34b74d..74817d5 100644 --- a/src/classes/Keyboard.cpp +++ b/src/classes/Keyboard.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #if defined(hidapi) #include @@ -200,6 +201,8 @@ bool LedKeyboard::open(uint16_t vendorID, uint16_t productID, string serial) { if (! dev) { currentDevice.model = KeyboardModel::unknown; + errno = ENODEV; + hid_exit(); return false; } @@ -209,6 +212,7 @@ bool LedKeyboard::open(uint16_t vendorID, uint16_t productID, string serial) { if(m_hidHandle == 0) { hid_exit(); + errno = EACCES; return false; } @@ -294,6 +298,7 @@ bool LedKeyboard::open(uint16_t vendorID, uint16_t productID, string serial) { if (currentDevice.model == KeyboardModel::unknown) { libusb_exit(m_ctx); + errno = ENODEV; m_ctx = NULL; return false; } @@ -303,6 +308,7 @@ bool LedKeyboard::open(uint16_t vendorID, uint16_t productID, string serial) { if(m_hidHandle == NULL) { libusb_exit(m_ctx); + errno = EACCES; m_ctx = NULL; return false; } @@ -310,6 +316,7 @@ bool LedKeyboard::open(uint16_t vendorID, uint16_t productID, string serial) { if(libusb_kernel_driver_active(m_hidHandle, 1) == 1) { if(libusb_detach_kernel_driver(m_hidHandle, 1) != 0) { libusb_exit(m_ctx); + errno = EACCES; m_ctx = NULL; return false; } @@ -322,6 +329,7 @@ bool LedKeyboard::open(uint16_t vendorID, uint16_t productID, string serial) { m_isKernellDetached = false; } libusb_exit(m_ctx); + errno = EACCES; m_ctx = NULL; return false; } diff --git a/src/main.cpp b/src/main.cpp index e867327..2099027 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -323,7 +323,17 @@ int main(int argc, char **argv) { //Initialize the device for use if (!kbd.open(vendorID, productID, serial)) { - std::cout << "Matching or compatible device not found !" << std::endl; + switch (errno) + { + case ENODEV: + std::cout << "Matching or compatible device not found" << std::endl; + break; + case EACCES: + std::cout << "Access denied: Check device access permissions or run as a privileged user (root/sudo)" << std::endl; + break; + default: + std::cout << "Unknown error: errno=" << errno << std::endl; + } return 2; }