简体   繁体   English

在 Linux/C++ 中枚举 USB 设备

[英]Enum USB devices in Linux/C++

Im writing IO routines for a linux device that will have various and changing USB devices connected to it.我正在为一个 linux 设备编写 IO 例程,该设备将连接各种不断变化的 USB 设备。 To this end I need to be able to figure out which device is connected to which port so I can open it with the correct software.为此,我需要能够确定哪个设备连接到哪个端口,以便我可以使用正确的软件打开它。 Something akin to 'udevinfo' would be ideal but I have no idea how to start in writing such.类似于“udevinfo”的东西是理想的,但我不知道如何开始写这样的东西。

Suggestions on c++ apis to read?关于 C++ api 阅读的建议?

Take a look at libudev++ . 看一下libudev ++ It seems to be what you're looking for. 这似乎是你在寻找的东西。

请参阅libusblibusb_get_device_listlibusb_get_bus_numberlibusb_get_device_address

GIO should help you in that. GIO应该帮助你。 Connecting to the volume-added and volume-removed signals will alert your program to any storage device added or removed from the system. 连接到增加 音量和删除音量的信号将提醒您的程序任何添加到系统或从系统中删除的存储设备。 If you do not need the level of control provided by GIO, you can use libudev++ which provided a high level wrapper over GIO. 如果您不需要GIO提供的控制级别,您可以使用libudev ++ ,它提供了一个高级别的GIO包装器。

我不知道你需要什么样的信息,但你可以通过/ sys / bus / usb?

I ended up using a BASH solution in the chkconfig file. 我最终在chkconfig文件中使用了BASH解决方案。 I walk through all ttyUSB entries and look at the driver info for each: 我浏览所有ttyUSB条目并查看每个条目的驱动程序信息:

USB_ID=`egrep -i "mct u232|pl2303|keyspan" -m 1 /proc/tty/driver/usbserial | awk '{ printf( "$d", $1 )}'`
if [ -z $USB_ID ]
then
   echo $echo_n "No USB serial adapter found.";
   exit 1
fi

More recent solution:最近的解决方案:

Iterate over these file system directories:遍历这些文件系统目录:

/dev/serial/by-id
/dev/snd/by-id
/dev/disk/by-id
/dev/input/by-id
/dev/v4l/by-id

depending on what device class you are looking for.取决于您要查找的设备类别。

For example, finding the serial port for my Arduino Nano:例如,为我的 Arduino Nano 寻找串口:

#include <filesystem>
#include <string>

const std::string path = "/dev/serial/by-id";

for( const auto & file : std::filesystem::directory_iterator( path ) )
{
    const std::string s = "NANO_33_IoT";
    if( file.path().generic_string().find(s) )
    {
        return file.path();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM