从连接的USB设备中检索“设备实例路径”

时间:2015-11-20 17:50:19

标签: c++ windows usb

我已经关注了一些资源,包括this,其中我可以检索一堆属性,如USB设备的pid,vid等,但我需要检索“设备实例路径”,因为它包含序列号(最后4位数)这最终是我想要的。

我尝试使用来自here的代码来检索序列号,但它是针对USB存储设备的,我的是一个独立的设备,其USB连接类似于相机。

$("table").on("click", ".btn-danger", function() {
  var fire = $("<span>").addClass("glyphicon glyphicon-fire").attr("aria-hidden", "true").fadeIn(1000);
  $(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-danger btn-width").append(fire));
  $(this).parent().parent().remove(); // Remove entire row
});

问题在于代码的这一部分:

QString USBDevices::findDevice()
{
    GUID*pClassGuid = NULL;
    LPCTSTR pszEnumerator = TEXT("USB");

    unsigned i, j;
    DWORD dwSize, dwPropertyRegDataType;
    DEVPROPTYPE ulPropertyType;
    CONFIGRET status;
    HDEVINFO hDevInfo;
    SP_DEVINFO_DATA DeviceInfoData;
    const static LPCTSTR arPrefix[3] = {TEXT("VID_"), TEXT("PID_"), TEXT("MI_")};
    TCHAR szDeviceInstanceID [MAX_DEVICE_ID_LEN];
    TCHAR szDesc[1024], szHardwareIDs[4096];
    WCHAR szBuffer[4096];
    LPTSTR pszToken, pszNextToken;
    TCHAR szVid[MAX_DEVICE_ID_LEN], szPid[MAX_DEVICE_ID_LEN], szMi[MAX_DEVICE_ID_LEN];
    FN_SetupDiGetDevicePropertyW fn_SetupDiGetDevicePropertyW = (FN_SetupDiGetDevicePropertyW)
        GetProcAddress (GetModuleHandle (TEXT("Setupapi.dll")), "SetupDiGetDevicePropertyW");

    // List all connected USB devices
    hDevInfo = SetupDiGetClassDevs (pClassGuid, pszEnumerator, NULL,
                                    pClassGuid != NULL ? DIGCF_PRESENT: DIGCF_ALLCLASSES | DIGCF_PRESENT);


    //hDevInfo = SetupDiGetClassDevs(NULL,0,0, DIGCF_PRESENT | DIGCF_ALLCLASSES | DIGCF_DEVICEINTERFACE);

    if (hDevInfo == INVALID_HANDLE_VALUE)
        return "";

    // Find the ones that are driverless
    for (i = 0; ; i++)  {
        DeviceInfoData.cbSize = sizeof (DeviceInfoData);
        if (!SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData))
            break;

        status = CM_Get_Device_ID(DeviceInfoData.DevInst, szDeviceInstanceID , MAX_PATH, 0);
        if (status != CR_SUCCESS)
            continue;

        // Display device instance ID
        qDebug() << QString::fromWCharArray(szDeviceInstanceID);

        if (SetupDiGetDeviceRegistryProperty (hDevInfo, &DeviceInfoData, SPDRP_DEVICEDESC,
                                              &dwPropertyRegDataType, (BYTE*)szDesc,
                                              sizeof(szDesc),   // The size, in bytes
                                              &dwSize))
            qDebug() << "    Device Description: " << QString::fromWCharArray(szDesc);

        if (SetupDiGetDeviceRegistryProperty (hDevInfo, &DeviceInfoData, SPDRP_HARDWAREID,
                                              &dwPropertyRegDataType, (BYTE*)szHardwareIDs,
                                              sizeof(szHardwareIDs),    // The size, in bytes
                                              &dwSize)) {
            LPCTSTR pszId;
            qDebug() << "    Hardware IDs:\n";
            for (pszId=szHardwareIDs;
                 *pszId != TEXT('\0') && pszId + dwSize/sizeof(TCHAR) <= szHardwareIDs + ARRAYSIZE(szHardwareIDs);
                 pszId += lstrlen(pszId)+1) {

                qDebug() << QString::fromWCharArray(pszId);
            }
        }

        // Retreive the device description as reported by the device itself
        // On Vista and earlier, we can use only SPDRP_DEVICEDESC
        // On Windows 7, the information we want ("Bus reported device description") is
        // accessed through DEVPKEY_Device_BusReportedDeviceDesc
        if (fn_SetupDiGetDevicePropertyW && fn_SetupDiGetDevicePropertyW (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_BusReportedDeviceDesc,
                                                                          &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0)) {

            if (fn_SetupDiGetDevicePropertyW (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_BusReportedDeviceDesc,
                                              &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0))
            {
                QString busReportedDeviceDescription = QString::fromWCharArray(szBuffer);
                qDebug() << "    Bus Reported Device Description: " << QString::fromWCharArray(szBuffer);

                if ( busReportedDeviceDescription == MY_DEVICE )
                {
                    qDebug() << getSerialNum( hDevInfo );
                    return busReportedDeviceDescription;
                }
            }
            if (fn_SetupDiGetDevicePropertyW (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_Manufacturer,
                                              &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0)) {
                qDebug() << "    Device Manufacturer: " << QString::fromWCharArray(szBuffer);
            }
            if (fn_SetupDiGetDevicePropertyW (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_FriendlyName,
                                              &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0)) {
                qDebug() << "    Device Friendly Name: " <<  QString::fromWCharArray(szBuffer);
            }
            if (fn_SetupDiGetDevicePropertyW (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_LocationInfo,
                                              &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0)) {
                qDebug() << "    Device Location Info: " << QString::fromWCharArray(szBuffer);
            }
            if (fn_SetupDiGetDevicePropertyW (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_SecuritySDS,
                                              &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0)) {
                // See Security Descriptor Definition Language on MSDN
                // (http://msdn.microsoft.com/en-us/library/windows/desktop/aa379567(v=vs.85).aspx)
                qDebug() << "    Device Security Descriptor String: " << QString::fromWCharArray(szBuffer);
            }
            if (fn_SetupDiGetDevicePropertyW (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_ContainerId,
                                              &ulPropertyType, (BYTE*)szDesc, sizeof(szDesc), &dwSize, 0)) {
                StringFromGUID2((REFGUID)szDesc, szBuffer, ARRAY_SIZE(szBuffer));
                qDebug() << "    ContainerId: " << QString::fromWCharArray(szBuffer);
            }
            if (fn_SetupDiGetDevicePropertyW (hDevInfo, &DeviceInfoData, &DEVPKEY_DeviceDisplay_Category,
                                              &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0))
                qDebug() << "    Device Display Category: " << QString::fromWCharArray(szBuffer);
        }

        QString deviceInstanceID( QString::fromWCharArray( szDeviceInstanceID ) );
        QRegExp splitBy("(\\\\|\\&|\\#)");
        QStringList deviceInstanceIDItems = deviceInstanceID.split(splitBy);

        QString vid;
        QString pid;
        QString mi;

        if (deviceInstanceIDItems.count() > 1)
            vid = deviceInstanceIDItems[1].contains("VID_") ? deviceInstanceIDItems[1] : "";

        if (deviceInstanceIDItems.count() > 2)
            pid = deviceInstanceIDItems[2].contains("PID_") ? deviceInstanceIDItems[2] : "";

        if (deviceInstanceIDItems.count() > 3)
            mi = deviceInstanceIDItems[3].contains("MI_") ? deviceInstanceIDItems[3] : "";

        if (!vid.isEmpty())
            qDebug() << "    vid:  " << vid;
        if (!pid.isEmpty())
            qDebug() << "    pid: " << pid;
        if (!mi.isEmpty())
            qDebug() << "    mi: " << mi;

    }

    return "";
}

QString USBDevices::getSerialNum(HDEVINFO hDevInfo)
{
    // Get a context structure for the device interface
       // of a device information set.
       BYTE Buf[1024];
       PSP_DEVICE_INTERFACE_DETAIL_DATA pspdidd =
          (PSP_DEVICE_INTERFACE_DETAIL_DATA)Buf;
       SP_DEVICE_INTERFACE_DATA         spdid;
       SP_DEVINFO_DATA                  spdd;

       spdid.cbSize = sizeof( spdid );

       DWORD dwIndex = 0;
       while ( true )
       {
          if ( ! SetupDiEnumDeviceInterfaces( hDevInfo, NULL,
                                              //&GUID_DEVINTERFACE_USB_DISK,
                                              &my_guid,
                                              dwIndex, &spdid ))
          {
            qDebug() << "GetLastError code" << GetLastError();
            break;
          }

          DWORD dwSize = 0;
          SetupDiGetDeviceInterfaceDetail( hDevInfo, &spdid, NULL,
                                           0, &dwSize, NULL );

          if (( dwSize != 0 ) && ( dwSize <= sizeof( Buf )))
          {
             pspdidd->cbSize = sizeof( *pspdidd ); // 5 Bytes!

             ZeroMemory((PVOID)&spdd, sizeof(spdd));
             spdd.cbSize = sizeof(spdd);

             long res = SetupDiGetDeviceInterfaceDetail(
                hDevInfo, &spdid, pspdidd,
                dwSize, &dwSize, &spdd );
//                 if ( res )
//                 {
//                    HANDLE hDrive = CreateFile( pspdidd->DevicePath,0,
//                                                FILE_SHARE_READ | FILE_SHARE_WRITE,
//                                                NULL, OPEN_EXISTING, 0, NULL );
//                    if ( hDrive != INVALID_HANDLE_VALUE )
//                    {
//                       DWORD usbDeviceNumber = getDeviceNumber( hDrive );

//                       if ( usbDeviceNumber == volumeDeviceNumber )
//                       {
//                          fprintf( "%s", pspdidd->DevicePath );
//                       }
//                    }
//                    CloseHandle( hDrive );
//                 }

             qDebug() << "Device Path" << pspdidd->DevicePath;

             QString devicePath = QString::fromWCharArray( pspdidd->DevicePath );

             return devicePath;
          }
          dwIndex++;
       }

       return "";
}

返回错误代码269,因此它不会检索任何信息。我尝试提供几种不同的GUID,我认为这样可以解决问题,但事实并非如此,我不确定应该提供什么GUID,因为我的不是存储设备。

1 个答案:

答案 0 :(得分:0)

您应该使用已启用标记SetupDiGetClassDevs和某些接口类GUID调用DIGCF_DEVICEINTERFACE。然后,使用相同的GUID调用SetupDiEnumDeviceInterfaces。在你的情况下,我认为GUID_DEVINTERFACE_USB_DEVICE将完成这项工作。

您可以找到符合条件的GUID here