加载中...
linux usb设备数量和类型识别

一、整体思路

1、获取 /sys/bus/usb/devices 目录下文件信息。如下所示

2、例如 1-1 usb设备信息,可以通过命令ls 1-1查看

ls 1-1
1-1:1.0              bmAttributes         manufacturer
authorized           busnum               maxchild
avoid_reset_quirk    configuration        port
bConfigurationValue  descriptors          product
bDeviceClass         dev                  quirks
bDeviceProtocol      devnum               removable
bDeviceSubClass      devpath              remove
bMaxPacketSize0      driver               speed
bMaxPower            ep_00                subsystem
bNumConfigurations   idProduct            uevent
bNumInterfaces       idVendor             urbnum
bcdDevice            ltm_capable          version


其中product中就是该usb设备类型
3、获取usb设备类型

cat /1-1/product
AltoBeam_WIFI


返回显示该设备是一个usb wifi。

因此要知道设备上的usb设备数量以及类型就需要对这些文件进行读取。

二、代码实现

#define SYS_USB_INFO  "/sys/bus/usb/devices"

static UsbType_s g_astUsbType[10];

typedef struct 
{
    XM_CHAR aPort[256];
    XM_CHAR aType[256];
} UsbType_s;

//获取usb设备类型,成功返回 0 ;失败返回 -1;
static XM_S32 Usb_getState(char* pPath,char* pType)
{
    DIR *pstDir = NULL;
    struct stat ststat;    
    struct dirent *pstDirent = NULL;
    XM_CHAR aFileName[256]={};
    XM_S32 fd = -1;
    XM_S32 ret = -1;
    
    pstDir = opendir(pPath);
    pstDirent = readdir(pstDir);
    while(NULL != pstDirent)
    {
        if(strcmp("product",pstDirent->d_name) == 0)
        {
            strcpy(aFileName,pPath);
            strcat(aFileName,"/product");
            fd = open(aFileName,O_RDONLY);
            if(fd > 0 && !stat(aFileName, &ststat))
            {
                if(read(fd, pType,ststat.st_size))
                {
                    ret = 0;
                }
            }
            break;
        }
        pstDirent = readdir(pstDir);
    }
    close(fd);
    closedir(pstDir);
    return ret;
}

//获取usb接口设备连接数以及设备类型
//有usb设备返回0,失败返回-1,pNum返回usb设备个数,ppstUsbType是usb设备信息
XM_S32 LibXmDvr_Usb_getState(XM_S32 *pNum,UsbType_s** ppstUsbType)
{
    DIR *pstDir;
    struct dirent *pstDirent = NULL;
    XM_CHAR aPath[256]={};
    XM_CHAR aType[50]={};
    XM_S32 index = 0;

    pstDir = opendir(SYS_USB_INFO);
    pstDirent = readdir(pstDir);
    while(NULL != pstDirent)
    { 
        memset(aPath,0,256);
        strcpy(aPath,SYS_USB_INFO);
        strcat(aPath,"/");
        strcat(aPath,pstDirent->d_name);
        memset(aType,0,50);
        if(!Usb_getState(aPath,aType) && index < 10)
        {
            if(strstr(aType,"usbhc-nvtivot"))
            {
                pstDirent = readdir(pstDir);
                continue;
            }
            strcpy(g_astUsbType[index].aPort,pstDirent->d_name);
            strcpy(g_astUsbType[index].aType,aType);
            index++;
        }
        pstDirent = readdir(pstDir);
    }    
    closedir(pstDir);
    *pNum = index;
    *ppstUsbType = g_astUsbType;

    return (index > 0)&&(index <= 10) ? 0 : -1;
}
上一篇:
IPV6服务器搭建
下一篇:
命令读写寄存器
本文目录
本文目录