コード例 #1
0
ファイル: libhid.c プロジェクト: samy-gh/avr_proj
const T_HID_HDL* HidOpen( const char* const my_manufacturer, const char* const my_product )
{
	int f = 0;
	int i = 0;
	ULONG Needed, l;
	GUID HidGuid;
	HDEVINFO DeviceInfoSet;
	HIDD_ATTRIBUTES DeviceAttributes;
	SP_DEVICE_INTERFACE_DATA DevData;
	PSP_INTERFACE_DEVICE_DETAIL_DATA DevDetail;
	//SP_DEVICE_INTERFACE_DETAIL_DATA *MyDeviceInterfaceDetailData;
	HANDLE hHID = NULL;						// USB-IO dev handle
	T_HID_HDL_LOCAL*	libhid_handle = NULL;
	const int my_product_id = MY_PID;

	if( !hHID_DLL ) {
		return NULL;
	}

	DeviceAttributes.Size = sizeof(HIDD_ATTRIBUTES);
	DevData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

	HidD_GetHidGuid( &HidGuid );

	DeviceInfoSet =
		SetupDiGetClassDevs( &HidGuid, NULL, NULL,
							DIGCF_PRESENT | DIGCF_DEVICEINTERFACE );

	while( SetupDiEnumDeviceInterfaces( DeviceInfoSet, 0, &HidGuid, i++, &DevData ) ) {
		SetupDiGetDeviceInterfaceDetail( DeviceInfoSet, &DevData, NULL, 0, &Needed, 0 );
		l = Needed;
		DevDetail =
			(SP_DEVICE_INTERFACE_DETAIL_DATA *) GlobalAlloc( GPTR, l + 4 );
		DevDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
		SetupDiGetDeviceInterfaceDetail( DeviceInfoSet, &DevData, DevDetail,
										l, &Needed, 0 );

		hHID = CreateFile( DevDetail->DevicePath,
						   GENERIC_READ | GENERIC_WRITE,
						   FILE_SHARE_READ | FILE_SHARE_WRITE,
						   NULL, OPEN_EXISTING,
//						   FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING,
						   0, NULL );

		GlobalFree( DevDetail );

		if( hHID == INVALID_HANDLE_VALUE ) {	// Can't open a device
			continue;
		}
		HidD_GetAttributes( hHID, &DeviceAttributes );

		// HIDaspかどうか調べる.
		if( (DeviceAttributes.VendorID == MY_VID)
		 && (DeviceAttributes.ProductID == my_product_id)
		 && (check_product_string( hHID, my_manufacturer, my_product ) == 1)
		 ) {
			f = 1;				// 発見された.
			libhid_handle = malloc( sizeof(T_HID_HDL_LOCAL) );
			if( libhid_handle ) {
				libhid_handle->handle = hHID;
			}
			else {
				CloseHandle( hHID );
				hHID = NULL;
			}
			break;
		} else {
			// 違ったら閉じる
			CloseHandle( hHID );
			hHID = NULL;
		}
	}
	SetupDiDestroyDeviceInfoList( DeviceInfoSet );

	return (T_HID_HDL*)libhid_handle;
}
コード例 #2
0
ファイル: hiddata.c プロジェクト: mikejg/shinyPlayer
int usbhidOpenDevice(usbDevice_t **device, int vendor, char *vendorName, int product, char *productName, int usesReportIDs)
{
    GUID                                hidGuid;        /* GUID for HID driver */
    HDEVINFO                            deviceInfoList;
    SP_DEVICE_INTERFACE_DATA            deviceInfo;
    SP_DEVICE_INTERFACE_DETAIL_DATA     *deviceDetails = NULL;
    DWORD                               size;
    int                                 i, openFlag = 0;  /* may be FILE_FLAG_OVERLAPPED */
    int                                 errorCode = USBOPEN_ERR_NOTFOUND;
    HANDLE                              handle = INVALID_HANDLE_VALUE;
    HIDD_ATTRIBUTES                     deviceAttributes;

    HidD_GetHidGuid(&hidGuid);
    deviceInfoList = SetupDiGetClassDevs(&hidGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
    deviceInfo.cbSize = sizeof(deviceInfo);
    for(i=0;; i++) {
        if(handle != INVALID_HANDLE_VALUE) {
            CloseHandle(handle);
            handle = INVALID_HANDLE_VALUE;
        }
        if(!SetupDiEnumDeviceInterfaces(deviceInfoList, 0, &hidGuid, i, &deviceInfo))
            break;  /* no more entries */
        /* first do a dummy call just to determine the actual size required */
        SetupDiGetDeviceInterfaceDetail(deviceInfoList, &deviceInfo, NULL, 0, &size, NULL);
        if(deviceDetails != NULL)
            free(deviceDetails);
        deviceDetails = malloc(size);
        deviceDetails->cbSize = sizeof(*deviceDetails);
        /* this call is for real: */
        SetupDiGetDeviceInterfaceDetail(deviceInfoList, &deviceInfo, deviceDetails, size, &size, NULL);
        DEBUG_PRINT(("checking HID path \"%s\"\n", deviceDetails->DevicePath));
        /* attempt opening for R/W -- we don't care about devices which can't be accessed */
        handle = CreateFile(deviceDetails->DevicePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, openFlag, NULL);
        if(handle == INVALID_HANDLE_VALUE) {
            DEBUG_PRINT(("opening failed: %d\n", (int)GetLastError()));
            /* errorCode = USBOPEN_ERR_ACCESS; opening will always fail for mouse -- ignore */
            continue;
        }
        deviceAttributes.Size = sizeof(deviceAttributes);
        HidD_GetAttributes(handle, &deviceAttributes);
        DEBUG_PRINT(("device attributes: vid=%d pid=%d\n", deviceAttributes.VendorID, deviceAttributes.ProductID));
        if(deviceAttributes.VendorID != vendor || deviceAttributes.ProductID != product)
            continue;   /* ignore this device */
        errorCode = USBOPEN_ERR_NOTFOUND;
        if(vendorName != NULL && productName != NULL) {
            char    buffer[512];
            if(!HidD_GetManufacturerString(handle, buffer, sizeof(buffer))) {
                DEBUG_PRINT(("error obtaining vendor name\n"));
                errorCode = USBOPEN_ERR_IO;
                continue;
            }
            convertUniToAscii(buffer);
            DEBUG_PRINT(("vendorName = \"%s\"\n", buffer));
            if(strcmp(vendorName, buffer) != 0)
                continue;
            if(!HidD_GetProductString(handle, buffer, sizeof(buffer))) {
                DEBUG_PRINT(("error obtaining product name\n"));
                errorCode = USBOPEN_ERR_IO;
                continue;
            }
            convertUniToAscii(buffer);
            DEBUG_PRINT(("productName = \"%s\"\n", buffer));
            if(strcmp(productName, buffer) != 0)
                continue;
        }
        break;  /* we have found the device we are looking for! */
    }
    SetupDiDestroyDeviceInfoList(deviceInfoList);
    if(deviceDetails != NULL)
        free(deviceDetails);
    if(handle != INVALID_HANDLE_VALUE) {
        *device = (usbDevice_t *)handle;
        errorCode = 0;
    }
    return errorCode;
}
コード例 #3
0
ファイル: winutil.c プロジェクト: Eksmo/calibre
static DEVINST 
GetDrivesDevInstByDeviceNumber(long DeviceNumber,
          UINT DriveType, LPWSTR szDosDeviceName)
{
    GUID *guid;
    HDEVINFO hDevInfo;
    DWORD dwIndex, dwBytesReturned;
    BOOL bRet, IsFloppy;
    BYTE Buf[1024];
    PSP_DEVICE_INTERFACE_DETAIL_DATA pspdidd;
    long res;
    HANDLE hDrive;
    STORAGE_DEVICE_NUMBER sdn;
    SP_DEVICE_INTERFACE_DATA         spdid;
    SP_DEVINFO_DATA                  spdd;
    DWORD                            dwSize;


    IsFloppy = (wcsstr(szDosDeviceName, L"\\Floppy") != NULL); // is there a better way?

    switch (DriveType) {
    case DRIVE_REMOVABLE:
        if ( IsFloppy ) {
        guid = (GUID*)&GUID_DEVINTERFACE_FLOPPY;
        } else {
        guid = (GUID*)&GUID_DEVINTERFACE_DISK;
        }
        break;
    case DRIVE_FIXED:
        guid = (GUID*)&GUID_DEVINTERFACE_DISK;
        break;
    case DRIVE_CDROM:
        guid = (GUID*)&GUID_DEVINTERFACE_CDROM;
        break;
    default:
        PyErr_SetString(PyExc_ValueError, "Invalid drive type");
        return 0;
    }

    // Get device interface info set handle
    // for all devices attached to system
    hDevInfo = SetupDiGetClassDevs(guid, NULL, NULL,
                        DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

    if (hDevInfo == INVALID_HANDLE_VALUE)  {
        PyErr_SetString(PyExc_ValueError, "Invalid handle value");
        return 0;
    }

    // Retrieve a context structure for a device interface
    // of a device information set.
    dwIndex = 0;
    bRet = FALSE;

    
    pspdidd =  (PSP_DEVICE_INTERFACE_DETAIL_DATA)Buf;
    spdid.cbSize = sizeof(spdid);

    while ( TRUE )  {
        bRet = SetupDiEnumDeviceInterfaces(hDevInfo, NULL,
            guid, dwIndex, &spdid);
        if ( !bRet ) {
        break;
        }

        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);

        res =
            SetupDiGetDeviceInterfaceDetail(hDevInfo, &
                                            spdid, pspdidd,
                                            dwSize, &dwSize,
                                            &spdd);
        if ( res ) {
            hDrive = CreateFile(pspdidd->DevicePath,0,
                        FILE_SHARE_READ | FILE_SHARE_WRITE,
                        NULL, OPEN_EXISTING, 0, NULL);
            if ( hDrive != INVALID_HANDLE_VALUE ) {
            dwBytesReturned = 0;
            res = DeviceIoControl(hDrive,
                            IOCTL_STORAGE_GET_DEVICE_NUMBER,
                            NULL, 0, &sdn, sizeof(sdn),
                            &dwBytesReturned, NULL);
            if ( res ) {
                if ( DeviceNumber == (long)sdn.DeviceNumber ) {
                CloseHandle(hDrive);
                SetupDiDestroyDeviceInfoList(hDevInfo);
                return spdd.DevInst;
                }
            }
            CloseHandle(hDrive);
            }
        }
        }
        dwIndex++;
    }

    SetupDiDestroyDeviceInfoList(hDevInfo);
    PyErr_SetString(PyExc_ValueError, "Invalid device number");

    return 0;
}
コード例 #4
0
ファイル: qwinusb.cpp プロジェクト: ipalmer/QtUsb
bool QUsbDevice::getDeviceHandle(GUID guidDeviceInterface, PHANDLE hDeviceHandle)
{
    UsbPrintFuncName();
    if (guidDeviceInterface == GUID_NULL)
    {
        printUsbError("GUID_NULL");
        return false;
    }

    bool bResult = true;
    HDEVINFO hDeviceInfo;
    SP_DEVINFO_DATA DeviceInfoData;

    SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA pInterfaceDetailData = NULL;

    ulong requiredLength = 0;

    LPTSTR lpDevicePath = NULL;

    qint32 index = 0;

    // Get information about all the installed devices for the specified
    // device interface class.
    hDeviceInfo = SetupDiGetClassDevs(
        &guidDeviceInterface,
        NULL,
        NULL,
        DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

    if (hDeviceInfo == INVALID_HANDLE_VALUE)
    {
        // ERROR
        printUsbError("SetupDiGetClassDevs");
        goto done;
    }

    //Enumerate all the device interfaces in the device information set.
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

    for (index = 0; SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData); index++)
    {
        //Reset for this iteration
        if (lpDevicePath)
        {
            LocalFree(lpDevicePath);
        }
        if (pInterfaceDetailData)
        {
            LocalFree(pInterfaceDetailData);
        }

        deviceInterfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);

        //Get information about the device interface.
        bResult = SetupDiEnumDeviceInterfaces(
           hDeviceInfo,
           &DeviceInfoData,
           &guidDeviceInterface,
           0,
           &deviceInterfaceData);

        // Check if last item
        if (GetLastError () == ERROR_NO_MORE_ITEMS)
        {
            printUsbError("ERROR_NO_MORE_ITEMS");
            break;
        }

        //Check for some other error
        if (!bResult)
        {
            printUsbError("SetupDiEnumDeviceInterfaces");
            goto done;
        }

        //Interface data is returned in SP_DEVICE_INTERFACE_DETAIL_DATA
        //which we need to allocate, so we have to call this function twice.
        //First to get the size so that we know how much to allocate
        //Second, the actual call with the allocated buffer

        bResult = SetupDiGetDeviceInterfaceDetail(
            hDeviceInfo,
            &deviceInterfaceData,
            NULL, 0,
            &requiredLength,
            NULL);


        //Check for some other error
        if (!bResult)
        {
            if ((ERROR_INSUFFICIENT_BUFFER==GetLastError()) && (requiredLength>0))
            {
                //we got the size, allocate buffer
                pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, requiredLength);

                if (!pInterfaceDetailData)
                {
                    // ERROR
                    qWarning("Error allocating memory for the device detail buffer.\n");
                    goto done;
                }
            }
            else
            {
                printUsbError("SetupDiEnumDeviceInterfaces");
                goto done;
            }
        }

        //get the interface detailed data
        pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

        //Now call it with the correct size and allocated buffer
        bResult = SetupDiGetDeviceInterfaceDetail(
                hDeviceInfo,
                &deviceInterfaceData,
                pInterfaceDetailData,
                requiredLength,
                NULL,
                &DeviceInfoData);

        //Check for some other error
        if (!bResult)
        {
            printUsbError("SetupDiGetDeviceInterfaceDetail");
            goto done;
        }

        //copy device path

        size_t nLength = wcslen (pInterfaceDetailData->DevicePath) + 1;
        lpDevicePath = (TCHAR *) LocalAlloc (LPTR, nLength * sizeof(TCHAR));
        StringCchCopy(lpDevicePath, nLength, pInterfaceDetailData->DevicePath);
        lpDevicePath[nLength-1] = 0;

        if (mDebug) qDebug("Device path:  %ls", lpDevicePath);
    }

    if (!lpDevicePath)
    {
        //Error.
        qWarning("Error %d.", GetLastError());
        goto done;
    }

    //Open the device
    *hDeviceHandle = CreateFile (
        lpDevicePath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        FILE_FLAG_OVERLAPPED,
        NULL);

    if (*hDeviceHandle == INVALID_HANDLE_VALUE)
    {
        //Error.
        printUsbError("CreateFile");
        goto done;
    }

    done:
        LocalFree(lpDevicePath);
        LocalFree(pInterfaceDetailData);
        bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo);

    return bResult;
}
コード例 #5
0
ファイル: BtoIrRemocon.c プロジェクト: Velmy/BtoIrRemocon
// PC に接続ずみの「USB 接続赤外線リモコンキット」のデバイスパスを取得
DWORD GetDevicePath(OUT char *pszDevicePath, IN DWORD cchBuf)
{
    // USB IR REMOCON 固有の ID 文字列
    char *szIdStr1 = "vid_22ea&pid_001e";
    char *szIdStr2 = "mi_03";
    int i;
    char *pszProp;
    HDEVINFO DeviceInfoTable = NULL;
    SP_DEVICE_INTERFACE_DATA DeviceIfData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA pDeviceIfDetailData;
    SP_DEVINFO_DATA DevInfoData;
    DWORD InterfaceIndex, dwSize, dwError = ERROR_SUCCESS;
    HGLOBAL hMem = NULL;
    BOOL bFound;
    GUID InterfaceClassGuid;
    HMODULE hHidDLL;
    DEF_HidD_GetHidGuid pHidD_GetHidGuid;
    size_t len;

    //GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30};
    // HIDClass の GUID を取得
    hHidDLL = LoadLibrary("hid.dll");
    pHidD_GetHidGuid = (DEF_HidD_GetHidGuid)GetProcAddress(hHidDLL, "HidD_GetHidGuid");
    pHidD_GetHidGuid(&InterfaceClassGuid);
    FreeLibrary(hHidDLL);

    // HIDClass に属するデバイス群の含まれるデバイス情報セットを取得
    DeviceInfoTable = SetupDiGetClassDevs(&InterfaceClassGuid,
                            NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
    if(!DeviceInfoTable) {
        dwError = GetLastError();
        goto DONE;
    }
    // デバイス情報セットを走査し IR REMOCON デバイスを探す
    for (InterfaceIndex = 0; InterfaceIndex < 10000000; InterfaceIndex++) {
        DeviceIfData.cbSize = sizeof(DeviceIfData);
        if(SetupDiEnumDeviceInterfaces(DeviceInfoTable, NULL,
                            &InterfaceClassGuid, InterfaceIndex, &DeviceIfData)) {
            dwError = GetLastError();
            if (dwError == ERROR_NO_MORE_ITEMS) {
                goto DONE;
            }
        }
        else {
            dwError = GetLastError();
            goto DONE;
        }
        // 現在見ているデバイスの VID, PID の含まれるハードウェア ID 文字列を取得
        DevInfoData.cbSize = sizeof(DevInfoData);
        SetupDiEnumDeviceInfo(DeviceInfoTable, InterfaceIndex, &DevInfoData);
        SetupDiGetDeviceRegistryProperty(DeviceInfoTable, &DevInfoData,
                                    SPDRP_HARDWAREID, NULL, NULL, 0, &dwSize);
        hMem = GlobalAlloc(0, dwSize);
        if (!hMem) {
            dwError = GetLastError();
            goto DONE;
        }
        SetupDiGetDeviceRegistryProperty(DeviceInfoTable, &DevInfoData,
                            SPDRP_HARDWAREID, NULL, (PBYTE)hMem, dwSize, NULL);
        pszProp = strdup((char*)hMem);
        GlobalFree(hMem);
        hMem = NULL;
        
        // 取得したハードウェア ID 文字列に USB IR REMOCON 固有の VID, PID が含まれるか
        len = strlen(pszProp);
        for (i = 0; i < (int)len; i++) {
            pszProp[i] = tolower(pszProp[i]);
        }
        bFound = FALSE;
        if (strstr(pszProp, szIdStr1) != NULL && strstr(pszProp, szIdStr2) != NULL) {
            bFound = TRUE;
        }
        free(pszProp);

        // USB IR REMOCON 発見
        if (bFound) {
            // USB IR REMOCON のデバイスパスを得る
            SetupDiGetDeviceInterfaceDetail(DeviceInfoTable, &DeviceIfData,
                                                    NULL, 0, &dwSize, NULL);
            hMem = GlobalAlloc(0, dwSize);
            if (!hMem) {
                dwError = GetLastError();
                goto DONE;
            }
            pDeviceIfDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)hMem;
            pDeviceIfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
            if (SetupDiGetDeviceInterfaceDetail(DeviceInfoTable, &DeviceIfData,
                                        pDeviceIfDetailData, dwSize, NULL, NULL)) {
                if (cchBuf > dwSize - sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA)) {
                    // 成功
                    strcpy(pszDevicePath, pDeviceIfDetailData->DevicePath);
                    dwError = ERROR_SUCCESS;
                } else {
                    dwError = ERROR_NOT_ENOUGH_MEMORY;
                    goto DONE;
                }
                goto DONE;
            }
            else {
                dwError = GetLastError();
                goto DONE;
            }
        }
    }
DONE:
    if (hMem) {
        GlobalFree(hMem);
    }
    if (DeviceInfoTable) {
        SetupDiDestroyDeviceInfoList(DeviceInfoTable);
    }
    return dwError;
}
コード例 #6
0
ファイル: hid_WINDOWS.c プロジェクト: mamuesp/TeensyTransfer
//  rawhid_open - open 1 or more devices
//
//    Inputs:
//	max = maximum number of devices to open
//	vid = Vendor ID, or -1 if any
//	pid = Product ID, or -1 if any
//	usage_page = top level usage page, or -1 if any
//	usage = top level usage number, or -1 if any
//    Output:
//	actual number of devices opened
//
int rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
        GUID guid;
        HDEVINFO info;
        DWORD index=0, reqd_size;
        SP_DEVICE_INTERFACE_DATA iface;
        SP_DEVICE_INTERFACE_DETAIL_DATA *details;
        HIDD_ATTRIBUTES attrib;
        PHIDP_PREPARSED_DATA hid_data;
        HIDP_CAPS capabilities;
        HANDLE h;
        BOOL ret;
	hid_t *hid;
	int count=0;

	if (first_hid) free_all_hid();
	if (max < 1) return 0;
	if (!rx_event) {
		rx_event = CreateEvent(NULL, TRUE, TRUE, NULL);
		tx_event = CreateEvent(NULL, TRUE, TRUE, NULL);
		InitializeCriticalSection(&rx_mutex);
		InitializeCriticalSection(&tx_mutex);
	}
	HidD_GetHidGuid(&guid);
	info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if (info == INVALID_HANDLE_VALUE) return 0;
	for (index=0; 1 ;index++) {
		iface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
		ret = SetupDiEnumDeviceInterfaces(info, NULL, &guid, index, &iface);
		if (!ret) return count;
		SetupDiGetInterfaceDeviceDetail(info, &iface, NULL, 0, &reqd_size, NULL);
		details = (SP_DEVICE_INTERFACE_DETAIL_DATA *)malloc(reqd_size);
		if (details == NULL) continue;

		memset(details, 0, reqd_size);
		details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
		ret = SetupDiGetDeviceInterfaceDetail(info, &iface, details,
			reqd_size, NULL, NULL);
		if (!ret) {
			free(details);
			continue;
		}
		h = CreateFile(details->DevicePath, GENERIC_READ|GENERIC_WRITE,
			FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
			OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
		free(details);
		if (h == INVALID_HANDLE_VALUE) continue;
		attrib.Size = sizeof(HIDD_ATTRIBUTES);
		ret = HidD_GetAttributes(h, &attrib);
		//printf("vid: %4x\n", attrib.VendorID);
		if (!ret || (vid > 0 && attrib.VendorID != vid) ||
		  (pid > 0 && attrib.ProductID != pid) ||
		  !HidD_GetPreparsedData(h, &hid_data)) {
			CloseHandle(h);
			continue;
		}
		if (!HidP_GetCaps(hid_data, &capabilities) ||
		  (usage_page > 0 && capabilities.UsagePage != usage_page) ||
		  (usage > 0 && capabilities.Usage != usage)) {
			HidD_FreePreparsedData(hid_data);
			CloseHandle(h);
			continue;
		}
		HidD_FreePreparsedData(hid_data);
		hid = (struct hid_struct *)malloc(sizeof(struct hid_struct));
		if (!hid) {
			CloseHandle(h);
			continue;
		}
		hid->handle = h;
		hid->open = 1;
		add_hid(hid);
		count++;
		if (count >= max) return count;
	}
	return count;
}
コード例 #7
0
HANDLE OpenBleService(BLUETOOTH_ADDRESS *btha, GUID *guid)
{
    HDEVINFO                            hardwareDeviceInfo;
    SP_DEVICE_INTERFACE_DATA            deviceInterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA    deviceInterfaceDetailData = NULL;
    ULONG                               predictedLength = 0;
    ULONG                               requiredLength = 0, bytes=0;
	WCHAR								szBda[13] = {0};
	HANDLE								hService = INVALID_HANDLE_VALUE;
	DWORD								err;

    if ((hardwareDeviceInfo = SetupDiGetClassDevs ((LPGUID)guid,
			NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE))) == INVALID_HANDLE_VALUE)
    {
        ods("OpenBleServiceSetupDiGetClassDevs failed: %x\n", GetLastError());
        return hService;
    }

    deviceInterfaceData.cbSize = sizeof (SP_DEVICE_INTERFACE_DATA);

	// Enumerate devices of LE_DEVICE interface class
    for (int i = 0; ; i++) 
	{
        if (!SetupDiEnumDeviceInterfaces (hardwareDeviceInfo, 0, guid, i, &deviceInterfaceData)) 
		{
			if ((err = GetLastError()) == ERROR_NO_MORE_ITEMS) 
				ods("OpenBleService device not found\n");
			else
				ods ("OpenBleService:ERROR SetupDiEnumDeviceInterfaces failed:%d\n", err);
			break;
		}
        SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfo, &deviceInterfaceData,
				NULL, 0, &requiredLength, NULL);

		if ((err = GetLastError()) != ERROR_INSUFFICIENT_BUFFER) 
		{
            ods("OpenBleService:ERROR SetupDiGetDeviceInterfaceDetail failed %d\n", err);
            break;
        }

        predictedLength = requiredLength;

        deviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) new CHAR[predictedLength + 2];
        if (deviceInterfaceDetailData == NULL) 
		{
            ods("OpenBleService:ERROR Couldn't allocate %d bytes for device interface details.\n", predictedLength);
			break;
        }
		RtlZeroMemory (deviceInterfaceDetailData, predictedLength + 2);
        deviceInterfaceDetailData->cbSize = sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA);
        if (!SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfo, &deviceInterfaceData,
			deviceInterfaceDetailData, predictedLength, &requiredLength, NULL)) 
		{
            ods("OpenBleService :ERROR SetupDiGetDeviceInterfaceDetail\n");
			delete deviceInterfaceDetailData;
			break;
        }

		_wcsupr_s (deviceInterfaceDetailData->DevicePath, wcslen(deviceInterfaceDetailData->DevicePath) + 1);
		BdaToString (szBda, btha);
		if (wcsstr (deviceInterfaceDetailData->DevicePath, szBda) != NULL)
		{
			ods("OpenBleService Opening interface:%S\n", deviceInterfaceDetailData->DevicePath);

			hService = CreateFile ( deviceInterfaceDetailData->DevicePath,
                GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

			if(hService == INVALID_HANDLE_VALUE)
				ods("OpenBleService (hService == INVALID_HANDLE_VALUE) GetLastError() = %d\n", GetLastError());

			delete deviceInterfaceDetailData;
			break;
		}
		delete deviceInterfaceDetailData;
	}
    SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
	return hService;
}
コード例 #8
0
ファイル: pnp.c プロジェクト: uri247/wdk80
BOOLEAN
FindKnownHidDevices (
   OUT PHID_DEVICE * HidDevices, // A array of struct _HID_DEVICE
   OUT PULONG        NumberDevices // the length of this array.
   )
/*++
Routine Description:
   Do the required PnP things in order to find all the HID devices in
   the system at this time.
--*/
{
    HDEVINFO                            hardwareDeviceInfo;
    SP_DEVICE_INTERFACE_DATA            deviceInfoData;
    ULONG                               i;
    BOOLEAN                             done;
    PHID_DEVICE                         hidDeviceInst;
    GUID                                hidGuid;
    PSP_DEVICE_INTERFACE_DETAIL_DATA    functionClassDeviceData = NULL;
    ULONG                               predictedLength = 0;
    ULONG                               requiredLength = 0;
    PHID_DEVICE                         newHidDevices;


    HidD_GetHidGuid (&hidGuid);

    *HidDevices = NULL;
    *NumberDevices = 0;

    //
    // Open a handle to the plug and play dev node.
    //
    hardwareDeviceInfo = SetupDiGetClassDevs ( &hidGuid,
                                               NULL, // Define no enumerator (global)
                                               NULL, // Define no
                                               (DIGCF_PRESENT | // Only Devices present
                                                DIGCF_DEVICEINTERFACE)); // Function class devices.

    if (INVALID_HANDLE_VALUE == hardwareDeviceInfo)
    {
        return FALSE;
    }

    //
    // Take a wild guess to start
    //
    
    *NumberDevices = 4;
    done = FALSE;
    deviceInfoData.cbSize = sizeof (SP_DEVICE_INTERFACE_DATA);

    i=0;
    while (!done) 
    {
        *NumberDevices *= 2;

        if (*HidDevices) 
        {
            newHidDevices =
               realloc (*HidDevices, (*NumberDevices * sizeof (HID_DEVICE)));

            if (NULL == newHidDevices)
            {
                free(*HidDevices);
            }

            *HidDevices = newHidDevices;
        }
        else
        {
            *HidDevices = calloc (*NumberDevices, sizeof (HID_DEVICE));
        }

        if (NULL == *HidDevices) 
        {
            SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
            return FALSE;
        }

        hidDeviceInst = *HidDevices + i;

        for (; i < *NumberDevices; i++, hidDeviceInst++) 
        {
            if (SetupDiEnumDeviceInterfaces (hardwareDeviceInfo,
                                             0, // No care about specific PDOs
                                             &hidGuid,
                                             i,
                                             &deviceInfoData))
            {
                //
                // allocate a function class device data structure to receive the
                // goods about this particular device.
                //

                SetupDiGetDeviceInterfaceDetail (
                        hardwareDeviceInfo,
                        &deviceInfoData,
                        NULL, // probing so no output buffer yet
                        0, // probing so output buffer length of zero
                        &requiredLength,
                        NULL); // not interested in the specific dev-node


                predictedLength = requiredLength;

                functionClassDeviceData = malloc (predictedLength);
                if (functionClassDeviceData)
                {
                    functionClassDeviceData->cbSize = sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA);
                    ZeroMemory(functionClassDeviceData->DevicePath, sizeof(functionClassDeviceData->DevicePath));
                }
                else
                {
                    SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
                    return FALSE;
                }

                //
                // Retrieve the information from Plug and Play.
                //

                if (! SetupDiGetDeviceInterfaceDetail (
                           hardwareDeviceInfo,
                           &deviceInfoData,
                           functionClassDeviceData,
                           predictedLength,
                           &requiredLength,
                           NULL)) 
                {
                    SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
                    free(functionClassDeviceData);
                    return FALSE;
                }

                //
                // Open device with just generic query abilities to begin with
                //
                
                if (! OpenHidDevice (functionClassDeviceData -> DevicePath, 
                               FALSE,      // ReadAccess - none
                               FALSE,      // WriteAccess - none
                               FALSE,       // Overlapped - no
                               FALSE,       // Exclusive - no
                               hidDeviceInst))
                {
                    SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
                    free(functionClassDeviceData);
                    return FALSE;
                }

            } 
            else
            {
                if (ERROR_NO_MORE_ITEMS == GetLastError()) 
                {
                    done = TRUE;
                    break;
                }
            }
        }
    }

    *NumberDevices = i;

    SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
    free(functionClassDeviceData);
    return TRUE;
}
コード例 #9
0
ファイル: LeoninoUSB.cpp プロジェクト: rudarobson/Leonino
	__declspec(dllexport) BOOL  __stdcall GetDeviceHandle ( CONST GUID * guidDeviceInterface,PHANDLE hDeviceHandle)
	{	
		BOOL bResult = TRUE;
		HDEVINFO hDeviceInfo;
		SP_DEVINFO_DATA DeviceInfoData;

		SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
		PSP_DEVICE_INTERFACE_DETAIL_DATA pInterfaceDetailData = NULL;

		ULONG requiredLength=0;

		LPTSTR lpDevicePath = NULL;

		DWORD index = 0;

		// Get information about all the installed devices for the specified
		// device interface class.
		hDeviceInfo = SetupDiGetClassDevs( 
			guidDeviceInterface,
			NULL, 
			NULL,
			DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

		if (hDeviceInfo == INVALID_HANDLE_VALUE) 
		{ 
			// ERROR 
			printf("Error SetupDiGetClassDevs: %d.\n", GetLastError());
			goto done;
		}

		//Enumerate all the device interfaces in the device information set.
		DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

		//for (index = 0; SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData); index++)
		if(SetupDiEnumDeviceInfo(hDeviceInfo, 0, &DeviceInfoData))
		{
			//Reset for this iteration
			if (lpDevicePath)
			{
				LocalFree(lpDevicePath);
			}

			if (pInterfaceDetailData)
			{
				LocalFree(pInterfaceDetailData);
			}

			deviceInterfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);

			//Get information about the device interface.
			bResult = SetupDiEnumDeviceInterfaces( 
				hDeviceInfo,
				&DeviceInfoData,
				guidDeviceInterface,
				0, 
				&deviceInterfaceData);

			// Check if last item
			if (GetLastError () == ERROR_NO_MORE_ITEMS)
			{
				//break;
			}

			//Check for some other error
			if (!bResult) 
			{
				printf("Error SetupDiEnumDeviceInterfaces: %d.\n", GetLastError());
				goto done;
			}

			//Interface data is returned in SP_DEVICE_INTERFACE_DETAIL_DATA
			//which we need to allocate, so we have to call this function twice.
			//First to get the size so that we know how much to allocate
			//Second, the actual call with the allocated buffer

			bResult = SetupDiGetDeviceInterfaceDetail(
				hDeviceInfo,
				&deviceInterfaceData,
				NULL, 0,
				&requiredLength,
				NULL);


			//Check for some other error
			if (!bResult) 
			{
				if ((ERROR_INSUFFICIENT_BUFFER==GetLastError()) && (requiredLength>0))
				{
					//we got the size, allocate buffer
					pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, requiredLength);

					if (!pInterfaceDetailData) 
					{ 
						// ERROR 
						printf("Error allocating memory for the device detail buffer.\n");
						goto done;
					}
				}
				else
				{
					printf("Error SetupDiEnumDeviceInterfaces: %d.\n", GetLastError());
					goto done;
				}
			}

			//get the interface detailed data
			pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

			//Now call it with the correct size and allocated buffer
			bResult = SetupDiGetDeviceInterfaceDetail(
				hDeviceInfo,
				&deviceInterfaceData,
				pInterfaceDetailData,
				requiredLength,
				NULL,
				&DeviceInfoData);

			//Check for some other error
			if (!bResult) 
			{
				printf("Error SetupDiGetDeviceInterfaceDetail: %d.\n", GetLastError());
				goto done;
			}

			//copy device path

			size_t nLength = wcslen (pInterfaceDetailData->DevicePath) + 1;  
			lpDevicePath = (TCHAR *) LocalAlloc (LPTR, nLength * sizeof(TCHAR));
			StringCchCopy(lpDevicePath, nLength, pInterfaceDetailData->DevicePath);

			lpDevicePath[nLength-1] = 0;

			//printf("Device path:  %s\n", lpDevicePath);

		}

		if (!lpDevicePath)
		{
			//Error.
			printf("Error %d.", GetLastError());
			goto done;
		}

		//Open the device
		*hDeviceHandle = CreateFile (
			lpDevicePath,
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ | FILE_SHARE_WRITE,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL);

		if (*hDeviceHandle == INVALID_HANDLE_VALUE)
		{
			//Error.
			printf("Error %d.", GetLastError());
			goto done;
		}



done:
		LocalFree(lpDevicePath);
		LocalFree(pInterfaceDetailData);    
		bResult = SetupDiDestroyDeviceInfoList(hDeviceInfo);

		return bResult;
	}	
コード例 #10
0
ファイル: XnUSBWin32.cpp プロジェクト: 1170390/OpenNI2
XN_C_API XnStatus xnUSBEnumerateDevices(XnUInt16 nVendorID, XnUInt16 nProductID, const XnUSBConnectionString** pastrDevicePaths, XnUInt32* pnCount)
{
	// support up to 30 devices
	XnUSBConnectionString cpUSBID;
	XnUSBConnectionString cpUSBPathCmp;
	XnUSBConnectionString aNames[MAX_POTENTIAL_DEVICES];
	HDEVINFO hDevInfo = NULL;
	ULONG nDevices = 0;
	XnUInt32 nFoundDevices = 0;
	SP_DEVICE_INTERFACE_DATA devInterfaceData;
	XnBool bReachedEnd = FALSE;

	// Validate xnUSB
	XN_VALIDATE_USB_INIT();

	LPCGUID pInterfaceGuid = &GUID_CLASS_PSDRV_USB;

	// See if the driver is installed
	hDevInfo = SetupDiGetClassDevs (pInterfaceGuid, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
	if (hDevInfo == INVALID_HANDLE_VALUE)
	{
		// No devices are present...
		return (XN_STATUS_USB_DRIVER_NOT_FOUND);
	}

	// Scan the hardware for any devices that are attached to our driver.
	devInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

	while (nDevices < MAX_POTENTIAL_DEVICES)
	{
		// Get information about the device
		if (SetupDiEnumDeviceInterfaces(hDevInfo, 0, pInterfaceGuid, nDevices, &devInterfaceData))
		{
			PSP_DEVICE_INTERFACE_DETAIL_DATA pDevInterfaceDetailData = NULL;
			ULONG nPredictedLength = 0;
			ULONG nRequiredLength = 0;

			// Probe how much memory is needed to read the device info
			SetupDiGetDeviceInterfaceDetail(hDevInfo, &devInterfaceData, NULL, 0, &nRequiredLength, NULL);

			// Allocate memory for the device info
			nPredictedLength = nRequiredLength;

			pDevInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(nPredictedLength);
			if(pDevInterfaceDetailData == NULL)
			{
				// Not enough memory...
				return XN_STATUS_ALLOC_FAILED;
			}

			// Read the device info
			pDevInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
			if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, &devInterfaceData, pDevInterfaceDetailData, nPredictedLength, &nRequiredLength, NULL))
			{
				// Something bad has happened...
				free(pDevInterfaceDetailData);
				return XN_STATUS_ERROR;
			}

			// Make sure we have the right VID/PID
			cpUSBID[0] = 0;
			sprintf_s (cpUSBID, "vid_%04x&pid_%04x", nVendorID, nProductID);
			
			cpUSBPathCmp[0] = 0;
			StringCchCopy(cpUSBPathCmp, MAX_DEVICE_STR_LENGTH, pDevInterfaceDetailData->DevicePath);

			if (strstr(_strlwr(cpUSBPathCmp), cpUSBID) != 0)
			{
				StringCchCopy(aNames[nFoundDevices], MAX_DEVICE_STR_LENGTH, pDevInterfaceDetailData->DevicePath);

				++nFoundDevices;
			}

			++nDevices;
		}
		else if (ERROR_NO_MORE_ITEMS == GetLastError())
		{
			// no more devices
			bReachedEnd = TRUE;
			break;
		}
	}

	SetupDiDestroyDeviceInfoList(hDevInfo);

	if (!bReachedEnd)
	{
		// we probably passed our limit
		XN_LOG_ERROR_RETURN(XN_STATUS_ERROR, XN_MASK_USB, "Found more than %d devices! This is not supported.", MAX_POTENTIAL_DEVICES);
	}

	XnUSBConnectionString* pNames;
	XN_VALIDATE_CALLOC(pNames, XnUSBConnectionString, nFoundDevices);
	xnOSMemCopy(pNames, aNames, sizeof(XnUSBConnectionString) * nFoundDevices);

	*pastrDevicePaths = pNames;
	*pnCount = nFoundDevices;

	// All is good...
	return (XN_STATUS_OK);
}
コード例 #11
0
ファイル: Client.cpp プロジェクト: ShellzJewelz/CyberProject
void DetectAlreadyConnectedDevices(ThreadObject* tpThreads[])
{
	HDEVINFO hDevInfo = SetupDiGetClassDevs(
		&GUID_DEVINTERFACE_DISK,
		NULL,
		NULL,
		DIGCF_PRESENT |
		DIGCF_DEVICEINTERFACE
		);
	SP_DEVINFO_DATA spDeviceInfoData;
	ZeroMemory(&spDeviceInfoData, sizeof(SP_DEVINFO_DATA));
	spDeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
	LPTSTR pszPropertyBuffer[BUFFER];
	DWORD dwRequiredSize;
	DWORD dwRequiredBufferSize;
	DWORD dwProperyDatatype;
	BOOL bResult;

	for (DWORD dwDeviceInfoIndex = 0; SetupDiEnumDeviceInfo(
		hDevInfo,
		dwDeviceInfoIndex,
		&spDeviceInfoData
		);
	dwDeviceInfoIndex++)
	{
		bResult = SetupDiGetDeviceRegistryProperty(
			hDevInfo,
			&spDeviceInfoData,
			SPDRP_ENUMERATOR_NAME,
			&dwProperyDatatype,
			(LPBYTE)pszPropertyBuffer,
			BUFFER,
			&dwRequiredBufferSize);

		if (_tcscmp((LPTSTR)pszPropertyBuffer, TEXT("USBSTOR")) == 0)
		{
			SP_DEVICE_INTERFACE_DATA spDeviceInterfaceData;
			ZeroMemory(&spDeviceInterfaceData, sizeof(spDeviceInterfaceData));
			spDeviceInterfaceData.cbSize = sizeof(spDeviceInterfaceData);
			PSP_DEVICE_INTERFACE_DETAIL_DATA pspDeviceInterfaceDetailData = NULL;

			for (DWORD dwDeviceInterfacesIndex = 0; bResult = SetupDiEnumDeviceInterfaces(
				hDevInfo,
				&spDeviceInfoData,
				&GUID_DEVINTERFACE_DISK,
				dwDeviceInterfacesIndex++,
				&spDeviceInterfaceData
				);
			dwDeviceInterfacesIndex++)
			{
				DWORD dwError = GetLastError();
				if (!bResult)
				{
					if (dwError == ERROR_NO_MORE_DEVICES || dwError == ERROR_NO_MORE_ITEMS)
						break;
				}

				/*
				Get the required size for the
				PSP_DEVICE_INTERFACE_DETAIL_DATA
				structure
				*/
				bResult = SetupDiGetDeviceInterfaceDetail(
					hDevInfo,
					&spDeviceInterfaceData,
					NULL,
					0,
					&dwRequiredSize,
					NULL
					);

				/*
				Allocate that required size
				*/
				if (!bResult)
				{
					if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
					{
						pspDeviceInterfaceDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA[dwRequiredSize];//(PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, dwRequiredSize);
						pspDeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
					}
					else
						break;
				}

				/*
				Get the details on that device
				*/
				bResult = SetupDiGetDeviceInterfaceDetail(
					hDevInfo,
					&spDeviceInterfaceData,
					pspDeviceInterfaceDetailData,
					dwRequiredSize,
					NULL,
					NULL
					);
				if (bResult)
				{
					STORAGE_DEVICE_NUMBER storageDeviceNumber;
					ZeroMemory(&storageDeviceNumber, sizeof(STORAGE_DEVICE_NUMBER));
					storageDeviceNumber.DeviceNumber = 0;
					DWORD dwSize = 0;

					/*
					Get the device handle
					*/
					HANDLE hDrive = CreateFile(
						pspDeviceInterfaceDetailData->DevicePath,
						GENERIC_READ,
						FILE_SHARE_READ |
						FILE_SHARE_WRITE,
						NULL,
						OPEN_EXISTING,
						0,
						0
						);
					if (hDrive != INVALID_HANDLE_VALUE)
					{
						/*
						Get the device number
						*/
						bResult = DeviceIoControl(
							hDrive,
							IOCTL_STORAGE_GET_DEVICE_NUMBER,
							NULL,
							0,
							&storageDeviceNumber,
							sizeof(storageDeviceNumber),
							&dwSize,
							NULL
							);
						if (bResult)
						{
							char cDrive = GetVolumeLabelByDiskNumber(storageDeviceNumber.DeviceNumber);
							if (cDrive)
							{
								int iIndex = cDrive - 'A';
								printf("%c:\\ will be watched\n", cDrive);
								tpThreads[iIndex] = new ThreadObject(Inspection, (LPVOID)cDrive);
								tpThreads[iIndex]->Start();
							}
						}
					}
					CloseHandle(hDrive);
				}
				delete pspDeviceInterfaceDetailData;
			}
		}
	}
	SetupDiDestroyDeviceInfoList(hDevInfo);
}
コード例 #12
0
ファイル: niash_winusb.cpp プロジェクト: mkentie/3300c
void NiashLibUsbInit(TFnReportDevice* const pfnReportDevice)
{
	class HDEVINFODeleter //RAII wrapper
	{
	public:
		typedef HDEVINFO pointer;
		void operator()(HDEVINFO h) {::SetupDiDestroyDeviceInfoList(h);}
	};

	//Get device
	std::unique_ptr<HDEVINFO, HDEVINFODeleter> hDevInfo(SetupDiGetClassDevs(&s_NiashInterfaceClassGUID, NULL, NULL, DIGCF_PRESENT|DIGCF_PROFILE|DIGCF_DEVICEINTERFACE));
	if(hDevInfo.get() == INVALID_HANDLE_VALUE)
	{
		wprintf_s(L"SetupDiGetClassDevs: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}
	
	//Get device info for the devices
	SP_DEVINFO_DATA DeviceInfoData;
	DeviceInfoData.cbSize = sizeof(DeviceInfoData);
	SetupDiEnumDeviceInfo(hDevInfo.get(),0,&DeviceInfoData);
	if(GetLastError()==ERROR_NO_MORE_ITEMS)
	{
		puts("No devices with the driver installed found.");
	}
	else
	{
		wprintf_s(L"SetupDiEnumDeviceInfo: %s\n", _com_error(GetLastError()).ErrorMessage());
	}

	//Get the first matching device interface of that device
	SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
	DeviceInterfaceData.cbSize = sizeof(DeviceInterfaceData);	
	if(!SetupDiEnumDeviceInterfaces(hDevInfo.get(), &DeviceInfoData, &s_NiashInterfaceClassGUID, 0, &DeviceInterfaceData))
	{
		wprintf_s(L"SetupDiEnumDeviceInterfaces: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}

	//Get size of detailed device interface data
	DWORD dwRequiredSize;
	if(!SetupDiGetDeviceInterfaceDetail(hDevInfo.get(), &DeviceInterfaceData, nullptr, 0, &dwRequiredSize, nullptr) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
	{
		wprintf_s(L"SetupDiGetDeviceInterfaceDetail: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}

	//SP_DEVICE_INTERFACE_DETAIL_DATA's actual size isn't declared
	std::unique_ptr<SP_DEVICE_INTERFACE_DETAIL_DATA_A> pInterfaceDetailData(reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA_A*>(new BYTE[dwRequiredSize]));
	pInterfaceDetailData->cbSize = sizeof(*pInterfaceDetailData);
	if(!SetupDiGetDeviceInterfaceDetailA(hDevInfo.get(), &DeviceInterfaceData, pInterfaceDetailData.get(), dwRequiredSize, nullptr, nullptr))
	{
		wprintf_s(L"SetupDiGetDeviceInterfaceDetail: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}

	//Get name size
	ULONG ulPropType = DEVPROP_TYPE_STRING;
	if(!SetupDiGetDeviceProperty(hDevInfo.get(), &DeviceInfoData, &DEVPKEY_NAME, &ulPropType, nullptr, 0, &dwRequiredSize, 0) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
	{
		wprintf_s(L"SetupDiGetDeviceProperty: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}

	//Get device name
	std::vector<TCHAR> Buf(dwRequiredSize);
	if(!SetupDiGetDeviceProperty(hDevInfo.get(), &DeviceInfoData, &DEVPKEY_NAME, &ulPropType, reinterpret_cast<PBYTE>(Buf.data()), dwRequiredSize, 0, 0))
	{
		wprintf_s(L"SetupDiGetDeviceProperty: %s\n", _com_error(GetLastError()).ErrorMessage());
		return;
	}
	wprintf_s(L"Found device: %s ", Buf.data());
	printf_s("%s\n", pInterfaceDetailData->DevicePath);

	//Let driver recognize the device so it knows what parameters to use
	int vid = 0;
	int pid = 0;
	if(sscanf_s(pInterfaceDetailData->DevicePath,"\\\\?\\usb#vid_%x&pid_%x#", &vid, &pid) == 2 && MatchUsbDevice(vid,pid,&s_pScannerModel))
	{
		pfnReportDevice(s_pScannerModel, pInterfaceDetailData->DevicePath);
	}
}
コード例 #13
0
USBHIDDLL_API			 PSP_DEVICE_INTERFACE_DETAIL_DATA bOpenHidDevice(USHORT VID, USHORT PID){
				 GUID HidGuid;
				 HDEVINFO HidDevInfo;						/* handle to structure containing all attached HID Device information */
				 SP_DEVICE_INTERFACE_DATA devInfoData;		/* Information structure for HID devices */
				 BOOL Result = false;								/* result of getting next device information structure */
				 DWORD Index;								/* index of HidDevInfo array entry */
				 DWORD DataSize;								/* size of the DeviceInterfaceDetail structure */		
				 bool GotRequiredSize;					/* 1-shot got device info data structure size flag */
				 DWORD RequiredSize;							/* size of device info data structure */
				 bool DIDResult = false;							/* get device info data result */
				 HIDD_ATTRIBUTES HIDAttrib;					/* HID device attributes */

				 HANDLE HidDevHandle;

				 BOOLEAN bRet = false;

				 PSP_DEVICE_INTERFACE_DETAIL_DATA detailData = NULL;
				 /* initialize variables */
				 GotRequiredSize = FALSE;



				 /* 1) Get the HID Globally Unique ID from the OS */
				 HidD_GetHidGuid(&HidGuid);


				 /* 2) Get an array of structures containing information about
				 all attached and enumerated HIDs */
				 HidDevInfo = SetupDiGetClassDevs(	
					 &HidGuid,
					 NULL, 
					 NULL, 
					 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
				 //													DIGCF_INTERFACEDEVICE);

				 /* 3) Step through the attached device list 1 by 1 and examine
				 each of the attached devices.  When there are no more entries in
				 the array of structures, the function will return FALSE. */

				 Index = 0;									/* init to first index of array */
				 devInfoData.cbSize = sizeof(devInfoData);	/* set to the size of the structure
															that will contain the device info data */

				 do {
					 /* Get information about the HID device with the 'Index' array entry */
					 Result = SetupDiEnumDeviceInterfaces(	HidDevInfo, 
						 0, 
						 &HidGuid,
						 Index, 
						 &devInfoData);

					 /* If we run into this condition, then there are no more entries
					 to examine, we might as well return FALSE at point */
					 if(Result == FALSE)
					 {

						 /* free HID device info list resources */
						 SetupDiDestroyDeviceInfoList(HidDevInfo);

//						 return bRet;
						 return detailData;
					 }


					 if(GotRequiredSize == FALSE)
					 {
						 /* 3) Get the size of the DEVICE_INTERFACE_DETAIL_DATA
						 structure.  The first call will return an error condition, 
						 but we'll get the size of the strucure */
						 DIDResult = SetupDiGetDeviceInterfaceDetail(	HidDevInfo,
							 &devInfoData,
							 NULL,
							 0,
							 &DataSize,
							 NULL);
						 GotRequiredSize = TRUE;

						 /* allocate memory for the HidDevInfo structure */
						 detailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(DataSize);

						 /* set the size parameter of the structure */
						 detailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
					 }


					 /* 4) Now call the function with the correct size parameter.  This 
					 function will return data from one of the array members that 
					 Step #2 pointed to.  This way we can start to identify the
					 attributes of particular HID devices.  */
					 DIDResult = SetupDiGetDeviceInterfaceDetail(	HidDevInfo,
						 &devInfoData,
						 detailData,
						 DataSize,
						 &RequiredSize,
						 NULL);


					 /* 5) Open a file handle to the device.  Make sure the
					 attibutes specify overlapped transactions or the IN
					 transaction may block the input thread. */

					 HidDevHandle = CreateFile( detailData->DevicePath,
						 0,
						 FILE_SHARE_READ | FILE_SHARE_WRITE,
						 (LPSECURITY_ATTRIBUTES)NULL,
						 OPEN_EXISTING,
						 NULL,
						 NULL);


					 /* 6) Get the Device VID & PID to see if it's the device we want */
					 if(HidDevHandle != INVALID_HANDLE_VALUE)
					 {
						 HIDAttrib.Size = sizeof(HIDAttrib);
						 HidD_GetAttributes(	HidDevHandle, &HIDAttrib);						
						 if((HIDAttrib.VendorID == VID) && (HIDAttrib.ProductID == PID))
						 {		

							 /* free HID device info list resources */
							 SetupDiDestroyDeviceInfoList(HidDevInfo);

							 bRet = true;	/* found HID device */

						 }
						 else{

							 bRet = false;
						 }
						 /* 7) Close the Device Handle because we didn't find the device
						 with the correct VID and PID */
						 CloseHandle(HidDevHandle);
					 }

					 Index++;	/* increment the array index to search the next entry */

				 } while(Result == TRUE);
//				 return bRet;
				 return detailData;
			 }
コード例 #14
0
/* There are not words for how much I hate Microsoft APIs. -- vyhd */
bool USBDriver_Impl_WinUSB::Open( int iVendorID, int iProductID )
{
	// get a set of all the devices currently on the system
	HDEVINFO hDeviceInfo = SetupDiGetClassDevs( NULL, NULL, NULL, DIGCF_PRESENT );

	if( hDeviceInfo == INVALID_HANDLE_VALUE )
	{
		LOG->Trace( "WinUSB: SetupDiGetClassDevs failed (error %i)", GetLastError() );
		return false;
	}

	SP_DEVINFO_DATA DeviceInfoData;
	SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
	PSP_DEVICE_INTERFACE_DATA pInterfaceDetailData = NULL;

	LPTSTR lpDevicePath = NULL;

	for( int i = 0; SetupDiEnumDeviceInfo(hDeviceInfo, i, &DeviceInfoData); ++i )
	{
		if( lpDevicePath )
			LocalFree( lpDevicePath );
		if( pDeviceInterfaceData )
			LocalFree( pDeviceInterfaceData );

		DeviceInterfaceData.czSize = sizeof(SP_DEVICE_INTERFACE_DATA);

		bool bSuccess = SetupDiEnumDeviceInterfaces( hDeviceInfo, &DeviceInfoData, NULL, i, &DeviceInterfaceData );

		if( GetLastError() == ERROR_NO_MORE_ITEMS )
			break;

		if( !bSuccess )
		{
			LOG->Warn( "SetupDiEnumDeviceInterfaces failed with %d", GetLastError() );
			break;
		}

		int iRequiredLength = -1;

		bResult = SetupDiGetDeviceInterfaceDetail( hDeviceInfo, &DeviceInterfaceData, NULL, 0, &iRequiredLength, NULL );

		if( !bResult && GetLastError() == ERROR_INSUFFICIENT_BUFFER )
		{
			pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, iRequiredLength);

			if( !pInterfaceDetailData )
			{
				LOG->Warn( "Error allocating pInterfaceDetailData." );
				break;
			}
		}

		if( pInterfaceDetailSize )
			pInterfaceDetailSize->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
		else
			LOG->Warn( "XXX pInterfaceDetailSize is NULL, assumed not NULL" );

		bResult = SetupDiGetDeviceInterfaceDetail( hDeviceInfo, &DeviceInterfaceData, pInterfaceDetailData, iRequiredLength, NULL, &DeviceInfoData );

		if( !bResult )
		{
			LOG->Warn( "SetupDiGetDeviceInterfaceDetai: %d", GetLastError() );
			break;
		}

		
	return SetupDiDestroyDeviceInfoList( hDeviceInfo );
}

void USBDriver_Impl_WinUSB::Close()
{
}

int USBDriver_Impl_WinUSB::ControlMessage( int iType, int iRequest, int iValue, int iIndex, char *pData, int iSize, int iTimeout )
{
	// TODO: use WinUsb_SetPipePolicy to set timeout?
	WINUSB_SETUP_PACKET msg;
	msg.RequestType = iType;
	msg.Request = iRequest;
	msg.Value = iValue;
	msg.Index = iIndex;
	msg.Length = iSize;

	int iRet = -1;

	// TODO: are we sure that iRet will stay -1 when the call fails?
	WinUsb_ControlTransfer( m_pDevice, &msg, pData, iSize, &iRet );
	return iRet;
}
コード例 #15
0
ファイル: camac.cpp プロジェクト: skappert/mcp
ULONG GetSymbolicLink(void)
{		
	//OutputDebugString("GetSymbolicLink\r\n");
	int found_index = 0;
    HDEVINFO hDevInfo;

    // obtain a handle to device information set for all
    // kernel streaming audio devices present on the system
    hDevInfo = SetupDiGetClassDevs(
                        &CamacGuid,
                        NULL,
                        NULL,
                        DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

    if (hDevInfo == INVALID_HANDLE_VALUE)
    { // function returned 0
      // No audio devices are present on the system
        return 0;
    }
    else
    {
        TCHAR HardwareID[512];
        USHORT found_index = 0;
	
        // Enumerate first device of our class. 

        SP_DEVICE_INTERFACE_DATA ifdata;
		ifdata.cbSize = sizeof(ifdata);

		for ( DWORD devindex = 0;
				SetupDiEnumInterfaceDevice(hDevInfo, NULL,&CamacGuid, devindex, &ifdata);
				++devindex )
		{

			// Determine the symbolic link name for this device instance. Since
			// this is variable in length, make an initial call to determine
			// the required length.

			DWORD needed;
			SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifdata, NULL, 0, &needed, NULL);
				// this call determines the size of memory to allocate

			PSP_INTERFACE_DEVICE_DETAIL_DATA detail = (PSP_INTERFACE_DEVICE_DETAIL_DATA) malloc(needed);
				// zero the structure
				memset (detail,0,needed);

				// set the size of the structure without the string at the end
			detail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);

			SP_DEVINFO_DATA did = {sizeof(SP_DEVINFO_DATA)};
			SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifdata, detail, needed, NULL, &did);
			
			// Determine the device's link name
			SetupDiGetDeviceRegistryProperty(hDevInfo, &did,SPDRP_HARDWAREID, NULL, (PBYTE) HardwareID, sizeof(HardwareID), NULL);

			memset(symbolic_link, 0, sizeof(symbolic_link));
			strncpy(symbolic_link, detail->DevicePath, sizeof(symbolic_link));

			free((PVOID) detail);
			ifdata.cbSize = sizeof(ifdata); // reinitialize for next use
		}

		SetupDiDestroyDeviceInfoList(hDevInfo);
    }

    return found_index;
}
コード例 #16
0
int battery_init() {
	

	#define GBS_HASBATTERY 0x1
	#define GBS_ONBATTERY  0x2

	DWORD dwResult = GBS_ONBATTERY;
	HDEVINFO hdev = NULL;
	int idev = 0;
	BOOL b;
	DWORD cbRequired = 0;
	SP_DEVICE_INTERFACE_DATA did;

	hdev = SetupDiGetClassDevs(&GUID_DEVCLASS_BATTERY, 
                                0, 
                                0, 
                                DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if (INVALID_HANDLE_VALUE == hdev) {
		//return hdev;
		printf("GUID_DEVCLASS_BATTERY error\n");
		return -1;
	}

	for (idev = 0; idev < 100; idev++) {
		printf("for\n");
		
		memset(&did, 0, sizeof(did));
		did.cbSize = sizeof(did);

		b = SetupDiEnumDeviceInterfaces(hdev,
                                      0,
                                      &GUID_DEVCLASS_BATTERY,
                                      idev,
                                      &did);
		if (!b) {
			break;
		}

        SetupDiGetDeviceInterfaceDetail(hdev,
                                        &did,
                                        0,
                                        0,
                                        &cbRequired,
                                        0);

		if (ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
			PSP_DEVICE_INTERFACE_DETAIL_DATA pdidd =
			 (PSP_DEVICE_INTERFACE_DETAIL_DATA) LocalAlloc(LPTR, cbRequired);

			if (!pdidd) {
				log_err("battery_init: LocalAlloc failed, size %d", cbRequired);
				SetupDiDestroyDeviceInfoList(hdev);
				return -1;
			}

			pdidd->cbSize = sizeof(*pdidd);
            if (SetupDiGetDeviceInterfaceDetail(hdev,
                                                &did,
                                                pdidd,
                                                cbRequired,
                                                &cbRequired,
                                                0))
            {
				// Enumerated a battery.  Ask it for information.
				HANDLE hBattery = CreateFile(pdidd->DevicePath,
                                 GENERIC_READ | GENERIC_WRITE,
                                 FILE_SHARE_READ | FILE_SHARE_WRITE,
                                 NULL,
                                 OPEN_EXISTING,
                                 FILE_ATTRIBUTE_NORMAL,
                                 NULL);
				if (INVALID_HANDLE_VALUE != hBattery) {
					//printf("battery handle: %d\n", hBattery);
					//_bat[idev] = hBattery;
					_bathandle  = hBattery;
					LocalFree(pdidd);
					break;
				} else {
					log_warn("battery_init: failed to open device file: %s", pdidd->DevicePath);
				}
			} else {
					log_warn("battery_init:SetupDiGetDeviceInterfaceDetail failed");
			}

			LocalFree(pdidd);
		} // end if ERROR_INSUFFICIENT_BUFFER

	} // end for
      
	SetupDiDestroyDeviceInfoList(hdev);

	if (_bathandle != 0) {
		BATTERY_INFORMATION BatteryInfo;

		memset(&BatteryInfo, 0, sizeof(BATTERY_INFORMATION));
	
		if (BatteryQueryInformation(_bathandle,
									BatteryInformation,
									(LPVOID)&BatteryInfo,
									sizeof(BatteryInfo))) {
			_max_capacity = (float) BatteryInfo.FullChargedCapacity;
		} else {
			log_err("battery_info: failed to retrieve the maximum capacity of the battery");
			 CloseHandle(_bathandle);
			 _bathandle = 0;
			return -1;
		}

		battery_print_info(_bathandle);
	}
	printf("battery_init end \n");
	return 0;
}
コード例 #17
0
HRESULT RetrieveDevicePath(OUT LPTSTR DevicePath, IN ULONG BufLen, OUT PBOOL FailureDeviceNotFound) {
	HRESULT                          hr;
	ULONG                            length;
	HDEVINFO                         deviceInfo;
	SP_DEVICE_INTERFACE_DATA         interfaceData;
	ULONG                            requiredLength = 0;
	BOOL                             bResult		= FALSE;
	PSP_DEVICE_INTERFACE_DETAIL_DATA detailData		= NULL;

	if (NULL != FailureDeviceNotFound)
		*FailureDeviceNotFound = FALSE;

	// Enumerate all devices exposing the interface
	if (INVALID_HANDLE_VALUE == (deviceInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_iOS_USB_Capture, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE))) {
		hr = HRESULT_FROM_WIN32(GetLastError());
		return hr;
	}

	interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

	// Get the first interface (index 0) in the result set
	if (FALSE == (bResult = SetupDiEnumDeviceInterfaces(deviceInfo, NULL, &GUID_DEVINTERFACE_iOS_USB_Capture, 0, &interfaceData))) {
		// We would see this error if no devices were found
		if ((ERROR_NO_MORE_ITEMS == GetLastError()) && (NULL != FailureDeviceNotFound))
			*FailureDeviceNotFound = TRUE;

		hr = HRESULT_FROM_WIN32(GetLastError());
		SetupDiDestroyDeviceInfoList(deviceInfo);
		return hr;
	}

	// Get the size of the path string We expect to get a failure with insufficient buffer
	bResult = SetupDiGetDeviceInterfaceDetail(deviceInfo, &interfaceData, NULL, 0, &requiredLength, NULL);
	if (FALSE == bResult && ERROR_INSUFFICIENT_BUFFER != GetLastError()) {
		hr = HRESULT_FROM_WIN32(GetLastError());
		SetupDiDestroyDeviceInfoList(deviceInfo);
		return hr;
	}

	// Allocate temporary space for SetupDi structure
	if (NULL == (detailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LMEM_FIXED, requiredLength))) {
		hr = E_OUTOFMEMORY;
		SetupDiDestroyDeviceInfoList(deviceInfo);
		return hr;
	}

	detailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
	length = requiredLength;

	// Get the interface's path string
	if (FALSE == (bResult = SetupDiGetDeviceInterfaceDetail(deviceInfo, &interfaceData, detailData, length, &requiredLength, NULL))) {
		hr = HRESULT_FROM_WIN32(GetLastError());
		LocalFree(detailData);
		SetupDiDestroyDeviceInfoList(deviceInfo);
		return hr;
	}

	// Give path to the caller. SetupDiGetDeviceInterfaceDetail ensured DevicePath is NULL-terminated.
	hr = StringCbCopy(DevicePath, BufLen, detailData->DevicePath);
	LocalFree(detailData);
	SetupDiDestroyDeviceInfoList(deviceInfo);
	return hr;
}
コード例 #18
0
/// <summary>
/// Get physical device paths.
/// </summary>
/// <param name="drives">Found drives</param>
/// <returns>Error code</returns>
DWORD PhysicalDisk::GetPhysicalPaths( std::vector<std::wstring>& drives )
{
    HDEVINFO diskClassDevices = nullptr;
    GUID diskClassDeviceInterfaceGuid = GUID_DEVINTERFACE_DISK;
    SP_DEVICE_INTERFACE_DATA deviceInterfaceData = { 0 };
    PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = nullptr;
    DWORD requiredSize = 0;
    DWORD deviceIndex = 0;

    HANDLE disk = INVALID_HANDLE_VALUE;
    STORAGE_DEVICE_NUMBER diskNumber = { 0 };
    DWORD bytesReturned = 0;

    //
    // Get the handle to the device information set for installed
    // disk class devices. Returns only devices that are currently
    // present in the system and have an enabled disk device
    // interface.
    //
    diskClassDevices = SetupDiGetClassDevs( &diskClassDeviceInterfaceGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE );
    if (diskClassDevices == INVALID_HANDLE_VALUE)
        return GetLastError();

    ZeroMemory( &deviceInterfaceData, sizeof(SP_DEVICE_INTERFACE_DATA) );
    deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

    for (; SetupDiEnumDeviceInterfaces( diskClassDevices, NULL, &diskClassDeviceInterfaceGuid, deviceIndex, &deviceInterfaceData ); ++deviceIndex)
    {
        SetupDiGetDeviceInterfaceDetailW( diskClassDevices, &deviceInterfaceData, NULL, 0, &requiredSize, NULL );
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
            goto Exit;

        deviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc( requiredSize );

        ZeroMemory( deviceInterfaceDetailData, requiredSize );
        deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

        if (!SetupDiGetDeviceInterfaceDetail( diskClassDevices, &deviceInterfaceData, deviceInterfaceDetailData, requiredSize, NULL, NULL ))
            goto Exit;

        disk = CreateFile( deviceInterfaceDetailData->DevicePath,
                           GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
                           NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

        if (disk == INVALID_HANDLE_VALUE)
            goto Exit;

        if (!DeviceIoControl( disk, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &diskNumber, sizeof(STORAGE_DEVICE_NUMBER), &bytesReturned, NULL ))
            goto Exit;

        CloseHandle( disk );
        disk = INVALID_HANDLE_VALUE;

        drives.emplace_back( L"\\\\?\\PhysicalDrive" + std::to_wstring( diskNumber.DeviceNumber ) );

        if (deviceInterfaceDetailData)
        {
            free( deviceInterfaceDetailData );
            deviceInterfaceDetailData = nullptr;
        }
    }

Exit:

    if (INVALID_HANDLE_VALUE != diskClassDevices)
        SetupDiDestroyDeviceInfoList( diskClassDevices );

    if (INVALID_HANDLE_VALUE != disk)
        CloseHandle( disk );

    if (deviceInterfaceDetailData)
        free( deviceInterfaceDetailData );

    return GetLastError();
}
コード例 #19
0
ファイル: libirecovery.c プロジェクト: DJHartley/Ac1dSn0w
irecv_error_t mobiledevice_connect(irecv_client_t* client) {
	irecv_error_t ret;

	SP_DEVICE_INTERFACE_DATA currentInterface;
	HDEVINFO usbDevices;
	DWORD i;
	LPSTR path;
	irecv_client_t _client = (irecv_client_t) malloc(sizeof(struct irecv_client));
	memset(_client, 0, sizeof(struct irecv_client));

	// Get DFU paths
	usbDevices = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DFU, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if(!usbDevices) {
		return IRECV_E_UNABLE_TO_CONNECT;
	}
	currentInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
	for(i = 0; SetupDiEnumDeviceInterfaces(usbDevices, NULL, &GUID_DEVINTERFACE_DFU, i, &currentInterface); i++) {
		DWORD requiredSize = 0;
		PSP_DEVICE_INTERFACE_DETAIL_DATA details;
		SetupDiGetDeviceInterfaceDetail(usbDevices, &currentInterface, NULL, 0, &requiredSize, NULL);
		details = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(requiredSize);
		details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
		if(!SetupDiGetDeviceInterfaceDetail(usbDevices, &currentInterface, details, requiredSize, NULL, NULL)) {
			irecv_close(_client);
			free(details);
			SetupDiDestroyDeviceInfoList(usbDevices);
			return IRECV_E_UNABLE_TO_CONNECT;
		} else {
			LPSTR result = (LPSTR) malloc(requiredSize - sizeof(DWORD));
			memcpy((void*) result, details->DevicePath, requiredSize - sizeof(DWORD));
			free(details);
			path = (LPSTR) malloc(requiredSize - sizeof(DWORD));
			memcpy((void*) path, (void*) result, requiredSize - sizeof(DWORD));
			TCHAR* pathEnd = strstr(path, "#{");
			*pathEnd = '\0';
			_client->DfuPath = result;
			break;
		}
	}
	SetupDiDestroyDeviceInfoList(usbDevices);
	// Get iBoot path
	usbDevices = SetupDiGetClassDevs(&GUID_DEVINTERFACE_IBOOT, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if(!usbDevices) {
		irecv_close(_client);
		return IRECV_E_UNABLE_TO_CONNECT;
	}
	currentInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
	for(i = 0; SetupDiEnumDeviceInterfaces(usbDevices, NULL, &GUID_DEVINTERFACE_IBOOT, i, &currentInterface); i++) {
		DWORD requiredSize = 0;
		PSP_DEVICE_INTERFACE_DETAIL_DATA details;
		SetupDiGetDeviceInterfaceDetail(usbDevices, &currentInterface, NULL, 0, &requiredSize, NULL);
		details = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(requiredSize);
		details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
		if(!SetupDiGetDeviceInterfaceDetail(usbDevices, &currentInterface, details, requiredSize, NULL, NULL)) {
			irecv_close(_client);
			free(details);
			SetupDiDestroyDeviceInfoList(usbDevices);
			return IRECV_E_UNABLE_TO_CONNECT;
		} else {
			LPSTR result = (LPSTR) malloc(requiredSize - sizeof(DWORD));
			memcpy((void*) result, details->DevicePath, requiredSize - sizeof(DWORD));
			free(details);

			if(strstr(result, path) == NULL) {
				free(result);
				continue;
			}
			
			_client->iBootPath = result;
			break;
		}
	}
	SetupDiDestroyDeviceInfoList(usbDevices);
	free(path);
	
	ret = mobiledevice_openpipes(_client);
	if (ret != IRECV_E_SUCCESS) return ret;
	
	*client = _client;
	return IRECV_E_SUCCESS;
}
コード例 #20
0
DEVINST GetDrivesDevInstByDeviceNumber(long DeviceNumber, UINT DriveType, char* szDosDeviceName)
{
	bool IsFloppy = (strstr(szDosDeviceName, "\\Floppy") != NULL); // who knows a better way?

	GUID* guid;

	switch (DriveType) {
	case DRIVE_REMOVABLE:
		if ( IsFloppy ) {
			guid = (GUID*)&GUID_DEVINTERFACE_FLOPPY;
		} else {
			guid = (GUID*)&GUID_DEVINTERFACE_DISK;
		}
		break;
	case DRIVE_FIXED:
		guid = (GUID*)&GUID_DEVINTERFACE_DISK;
		break;
	case DRIVE_CDROM:
		guid = (GUID*)&GUID_DEVINTERFACE_CDROM;
		break;
	default:
		return 0;
	}

	// Get device interface info set handle for all devices attached to system
	HDEVINFO hDevInfo = SetupDiGetClassDevs(guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

	if (hDevInfo == INVALID_HANDLE_VALUE)	{
		return 0;
	}

	// Retrieve a context structure for a device interface of a device information set
	DWORD dwIndex = 0;
	long res;

	BYTE Buf[1024];
	PSP_DEVICE_INTERFACE_DETAIL_DATA pspdidd = (PSP_DEVICE_INTERFACE_DETAIL_DATA)Buf;
	SP_DEVICE_INTERFACE_DATA         spdid;
	SP_DEVINFO_DATA                  spdd;
	DWORD                            dwSize;
	
	spdid.cbSize = sizeof(spdid);

	while ( true )	{
		res = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guid, dwIndex, &spdid);
		if ( !res ) {
			break;
		}

		dwSize = 0;
		SetupDiGetDeviceInterfaceDetail(hDevInfo, &spdid, NULL, 0, &dwSize, NULL); // check the buffer size

		if ( dwSize!=0 && dwSize<=sizeof(Buf) ) {

			pspdidd->cbSize = sizeof(*pspdidd); // 5 Bytes!

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

			long res = SetupDiGetDeviceInterfaceDetail(hDevInfo, &spdid, pspdidd, dwSize, &dwSize, &spdd);
			if ( res ) {
				// open the disk or cdrom or floppy
				HANDLE hDrive = CreateFile(pspdidd->DevicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
				if ( hDrive != INVALID_HANDLE_VALUE ) {
					// get its device number
					STORAGE_DEVICE_NUMBER sdn;
					DWORD dwBytesReturned = 0;
					res = DeviceIoControl(hDrive, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &dwBytesReturned, NULL);
					if ( res ) {
						if ( DeviceNumber == (long)sdn.DeviceNumber ) {  // match the given device number with the one of the current device
							CloseHandle(hDrive);
							SetupDiDestroyDeviceInfoList(hDevInfo);
							return spdd.DevInst;
						}
					}
					CloseHandle(hDrive);
				}
			}
		}
		dwIndex++;
	}

	SetupDiDestroyDeviceInfoList(hDevInfo);

	return 0;
}
コード例 #21
0
ファイル: qwinusb.cpp プロジェクト: ipalmer/QtUsb
QtUsb::FilterList QUsbDevice::getAvailableDevices()
{
    QList<QtUsb::DeviceFilter> list;

    HDEVINFO                         hDevInfo;
    SP_DEVICE_INTERFACE_DATA         devIntfData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA devIntfDetailData;
    SP_DEVINFO_DATA                  devData;

    DWORD dwSize, dwMemberIdx;

    hDevInfo = SetupDiGetClassDevs(
            &QtUsb::WINUSB_DEV_GUID, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);


    if (hDevInfo != INVALID_HANDLE_VALUE)
        {
            devIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
            dwMemberIdx = 0;

            SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &QtUsb::WINUSB_DEV_GUID,
                dwMemberIdx, &devIntfData);

            while(GetLastError() != ERROR_NO_MORE_ITEMS)
            {
                devData.cbSize = sizeof(devData);
                SetupDiGetDeviceInterfaceDetail(
                      hDevInfo, &devIntfData, NULL, 0, &dwSize, NULL);

                devIntfDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
                devIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

                if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &devIntfData,
                    devIntfDetailData, dwSize, &dwSize, &devData))
                {
                    QString pathStr = QString::fromWCharArray(devIntfDetailData->DevicePath);
                    QtUsb::DeviceFilter filter;

                    int vidFrom = pathStr.indexOf("vid_")+4;
                    QString vidStr = pathStr.mid(vidFrom, 4);

                    int pidFrom = pathStr.indexOf("pid_")+4;
                    QString pidStr = pathStr.mid(pidFrom, 4);

                    bool ok[2];
                    uint vid = vidStr.toUInt(&ok[0], 16);
                    uint pid = pidStr.toUInt(&ok[1], 16);

                    if (ok[0] && ok[1])
                    {
                        filter.pid = pid;
                        filter.vid = vid;
                        list.append(filter);
                    }
                }

                HeapFree(GetProcessHeap(), 0, devIntfDetailData);

                // Continue looping
                SetupDiEnumDeviceInterfaces(
                    hDevInfo, NULL, &QtUsb::WINUSB_DEV_GUID, ++dwMemberIdx, &devIntfData);
            }

            SetupDiDestroyDeviceInfoList(hDevInfo);
        }

    return list;
}
コード例 #22
0
void * _ykusb_open_device(int vendor_id, int *product_ids, size_t pids_len)
{
	HDEVINFO hi;
	SP_DEVICE_INTERFACE_DATA di;
	PSP_DEVICE_INTERFACE_DETAIL_DATA pi;
	int i, numDev = 0;
	LPTSTR path = 0;
	DWORD len, rc;
	HANDLE ret_handle = NULL;

	yk_errno = YK_EUSBERR;

	hi = SetupDiGetClassDevs(&GUID_DEVINTERFACE_KEYBOARD, 0, 0,
				 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if (hi == INVALID_HANDLE_VALUE)
		return NULL;

	di.cbSize = sizeof (SP_DEVICE_INTERFACE_DATA);

	for (i = 0; i < 1000; i++) {
		if (!SetupDiEnumDeviceInterfaces(hi, 0, &GUID_DEVINTERFACE_KEYBOARD, i, &di))
			break;

		if (SetupDiGetDeviceInterfaceDetail(hi, &di, 0, 0, &len, 0) || GetLastError() != ERROR_INSUFFICIENT_BUFFER)
			break;

		pi = malloc (len);
		if (!pi) {
			yk_errno = YK_ENOMEM;
			goto done;
		}
		pi->cbSize = sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA);

		rc = SetupDiGetDeviceInterfaceDetail(hi, &di, pi, len, &len, 0);
		if (rc) {
			HANDLE m_handle;

			m_handle = CreateFile(pi->DevicePath, GENERIC_WRITE,
					      FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
			if (m_handle != INVALID_HANDLE_VALUE) {
				HIDD_ATTRIBUTES devInfo;

				if (HidD_GetAttributes(m_handle, &devInfo)) {
					if (devInfo.VendorID == vendor_id) {
						size_t j;
						for (j = 0; j < pids_len; j++) {
							if (devInfo.ProductID == product_ids[j]) {
								if(ret_handle == NULL) {
									ret_handle = m_handle;
									break;
								} else {
									yk_errno = YK_EMORETHANONE;
									ret_handle = NULL;
									CloseHandle (m_handle);
									goto done;
								}
							}
						}
					}
				}
			}
			if(ret_handle == NULL) {
				CloseHandle (m_handle);
			}
		}

		free (pi);
	}
	if(ret_handle != NULL) {
		goto done;
	}

	yk_errno = YK_ENOKEY;

done:
	SetupDiDestroyDeviceInfoList(hi);
	return ret_handle;
}
コード例 #23
0
ファイル: wht_dongle.cpp プロジェクト: nodep/wht
bool WHTDongle::Open()
{
	Close();

	hDevice = NULL;

	GUID guid;
	HDEVINFO info;
	DWORD index, required_size;
	std::vector<char> buff;

	HidD_GetHidGuid(&guid);
	info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if (info == INVALID_HANDLE_VALUE)
		return false;

	for (index = 0; 1; index++)
	{
		// get the next HID device
		SP_DEVICE_INTERFACE_DATA iface;
		iface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
		if (!SetupDiEnumDeviceInterfaces(info, NULL, &guid, index, &iface))
		{
			SetupDiDestroyDeviceInfoList(info);
			break;
		}

		// get the required size for details 
		SetupDiGetDeviceInterfaceDetail(info, &iface, NULL, 0, &required_size, NULL);

		// allocate and clear
		buff.clear();
		buff.insert(buff.end(), required_size, '\0');

		SP_DEVICE_INTERFACE_DETAIL_DATA* details = (SP_DEVICE_INTERFACE_DETAIL_DATA*) &buff.front();

		// now get the details
		details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
		if (!SetupDiGetDeviceInterfaceDetail(info, &iface, details, required_size, NULL, NULL))
			continue;

		// open the HID device
		HANDLE h = CreateFile(details->DevicePath, GENERIC_READ|GENERIC_WRITE,
						FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
						FILE_FLAG_OVERLAPPED, NULL);

		if (h == INVALID_HANDLE_VALUE)
			continue;

		// get the device's attributes
		HIDD_ATTRIBUTES attrib;
		attrib.Size = sizeof(HIDD_ATTRIBUTES);
		if (!HidD_GetAttributes(h, &attrib))
		{
			CloseHandle(h);
			continue;
		}
		
		// is this the device we need?
		if (attrib.VendorID != VENDOR_ID  ||  attrib.ProductID != PRODUCT_ID)
		{
			CloseHandle(h);
			continue;
		}

		SetupDiDestroyDeviceInfoList(info);
		hDevice = h;
	}

	if (!hDevice)
		return false;

	return true;
}
コード例 #24
0
ファイル: UsbEx.cpp プロジェクト: naorlss/dev-samples
////////////////////////////////////////////////////////////////////////////////
//	O p e n U S B D e v i c e
////////////////////////////////////////////////////////////////////////////////
HANDLE OpenUSBDevice( LPCSTR lpMfg, LPCSTR lpPdt, USB_ERROR_INFO *lpUsbErrorInfo )
{	
	int									ii;
	DWORD								dwBytes;
	BOOL								bFoundMfg;
	BOOL								bFoundPdt;
	LPTSTR								lpToken, lpWorkToken;
	int									nDeviceIndex;
	HDEVINFO							hDevInfo;
	HANDLE								hUsbPrinter;
	char								szUsb1284[1024];
	GUID								guidUSBDeviceSupport;
	SP_DEVICE_INTERFACE_DATA			deviceInterfaceData;
	PSP_DEVICE_INTERFACE_DETAIL_DATA	deviceInterfaceDetailData;
	HINSTANCE							pSetupAPI					= NULL;

	FAR HDEVINFO ( FAR WINAPI *SetupDiGetClassDevs )(CONST GUID *, PCTSTR, HWND, DWORD);
	FAR BOOL ( FAR WINAPI *SetupDiEnumDeviceInterfaces )(HDEVINFO, PSP_DEVINFO_DATA, CONST GUID *,DWORD, PSP_DEVICE_INTERFACE_DATA);
	FAR BOOL ( FAR WINAPI *SetupDiGetDeviceInterfaceDetail )(HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA);
	FAR BOOL ( FAR WINAPI *SetupDiDestroyDeviceInfoList )(HDEVINFO);



	//
	// The functions SetupDiGetClassDevs, SetupDiEnumDeviceInterfaces , 
	// SetupDiGetDeviceInterfaceDetail, SetupDiDestroyDeviceInfoList
	// are supported only on Windows 2000 and above and Windows 98 and above.
	// So link them dynamically to avoid windows errors.
	//
	pSetupAPI = LoadLibrary( "Setupapi" );

	if ( pSetupAPI != NULL )
	{

		SetupDiGetClassDevs = ( HDEVINFO ( WINAPI * )(CONST GUID *, PCTSTR, HWND, DWORD)) GetProcAddress( pSetupAPI, "SetupDiGetClassDevsA" );

		if ( SetupDiGetClassDevs == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiGetClassDevs");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiEnumDeviceInterfaces = ( BOOL ( WINAPI * )(HDEVINFO, PSP_DEVINFO_DATA, CONST GUID *,DWORD, PSP_DEVICE_INTERFACE_DATA)) GetProcAddress( pSetupAPI, "SetupDiEnumDeviceInterfaces" );

		if ( SetupDiEnumDeviceInterfaces == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiEnumDeviceInterfaces");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiGetDeviceInterfaceDetail = ( BOOL ( WINAPI * )(HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA)) GetProcAddress( pSetupAPI, "SetupDiGetDeviceInterfaceDetailA" );

		if ( SetupDiGetDeviceInterfaceDetail == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiGetDeviceInterfaceDetailA");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiDestroyDeviceInfoList = ( BOOL ( WINAPI * )(HDEVINFO)) GetProcAddress( pSetupAPI, "SetupDiDestroyDeviceInfoList" );

		if ( SetupDiDestroyDeviceInfoList == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiDestroyDeviceInfoList");
		    FreeLibrary( pSetupAPI );
			return 0;
		}
	}
	else
	{
		lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_HANDLE;
		strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to load Setupapi!");
		return 0;
	}


	//
	// get a handle to the set of device information returned by the Win32 API
	// functions.  This handle points to an object that is then operated on 
	// by the SetupDiEnumDeviceInterfaces function.
	//
	InitError( lpUsbErrorInfo );
	guidUSBDeviceSupport = GUID_CLASS_USB_DEVICE;
	hDevInfo = SetupDiGetClassDevs(	&guidUSBDeviceSupport,
									NULL,
									NULL,
									0x12 );	// TODO : Determine the constant
	if ( INVALID_HANDLE_VALUE == hDevInfo )
	{
		if ( NULL != lpUsbErrorInfo )
		{
			// get the last error from system
			lpUsbErrorInfo->dwSysLastError = GetLastError();

			// get the system defined message
			FormatMessage(	FORMAT_MESSAGE_FROM_SYSTEM			|
								FORMAT_MESSAGE_IGNORE_INSERTS,
							NULL,
							lpUsbErrorInfo->dwSysLastError,
							MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
							lpUsbErrorInfo->szSysErrorMsg,
							sizeof(lpUsbErrorInfo->szSysErrorMsg) / sizeof(lpUsbErrorInfo->szSysErrorMsg[0]),
							NULL );
		}
	}


	//
	//
	//	
	nDeviceIndex = 0;
	bFoundMfg = bFoundPdt = FALSE;
	hUsbPrinter = INVALID_HANDLE_VALUE;
	deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
	for ( nDeviceIndex = 0; SetupDiEnumDeviceInterfaces(	hDevInfo,
											NULL,
											&guidUSBDeviceSupport,
											nDeviceIndex,
											&deviceInterfaceData ); 
		nDeviceIndex++ ) 
	{




		//
		// determine the amout of memory we need to allocate for the next
		// call to this function
		//
		dwBytes= 0;
		ii = SetupDiGetDeviceInterfaceDetail(	hDevInfo,
												&deviceInterfaceData,
												NULL,
												0,
												&dwBytes,
												NULL );
		if ( 0 == dwBytes )
		{
			//
			// Reinitialize the data for next pass
			// through this loop.
			//
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}


		
		deviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(dwBytes);
		deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);


		//
		// get the device path for the current device we are enumerating over.
		//
		ii = SetupDiGetDeviceInterfaceDetail(	hDevInfo,
												&deviceInterfaceData,
												deviceInterfaceDetailData,
												dwBytes,
												&dwBytes,
												NULL );
		if ( 0 == ii )
		{
			//
			// Free DetailData struct and reinitialize the data for next pass
			//through this loop.
			//
			free(deviceInterfaceDetailData);
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}


		//
		// get handle to the device so that we can 
		//
		hUsbPrinter = CreateFile(	deviceInterfaceDetailData->DevicePath,
									GENERIC_READ		| 
										GENERIC_WRITE,
									FILE_SHARE_WRITE	|
										FILE_SHARE_READ,
									NULL,
									OPEN_EXISTING,
									0,
									NULL );


		//
		//
		//
		if ( INVALID_HANDLE_VALUE == hUsbPrinter )
		{
			//
			// Free DetailData struct and reinitialize the data for next pass
			// through this loop.
			//
			free(deviceInterfaceDetailData);
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}



		//
		//
		//
		dwBytes = 0;
		memset( szUsb1284, 0, sizeof(szUsb1284) );
		ii = DeviceIoControl(	hUsbPrinter,
								IOCTL_USBPRINT_GET_1284_ID,
								NULL,
								0,
								szUsb1284,
								sizeof(szUsb1284),
								&dwBytes,
								NULL );

		//
		// parse the PNP string returned from the device.
		//		
		lpToken = strtok( szUsb1284, PNP_DELIMITOR );
		while ( NULL != lpToken )
		{
			// have the manfacturer.
			lpWorkToken = strstr(lpToken,MFG_TOKEN);
			if ( lpWorkToken != NULL )
			{
				RTrim(lpWorkToken);
				if ( strcmp( lpMfg, lpWorkToken + MFG_TOKEN_LEN ) == 0 )
					bFoundMfg = TRUE;
			}

			//	model of the printer
			lpWorkToken = strstr(lpToken,MDL_TOKEN);
			if ( lpWorkToken != NULL )
			{
				RTrim(lpWorkToken);
				if ( strcmp( lpPdt, lpWorkToken + MDL_TOKEN_LEN ) == 0 )
					bFoundPdt = TRUE;
			}

			// next token
			lpToken = strtok( NULL, PNP_DELIMITOR );
		}


	
		//
		//
		//
		if ( bFoundMfg && bFoundPdt )
		{
	        free(deviceInterfaceDetailData);
			break;
		}
	

		//
		//
		//
		CloseHandle( hUsbPrinter );
		hUsbPrinter = INVALID_HANDLE_VALUE;


		
		//
		// Free DetailData struct and reinitialize the data for next pass
		// through this loop.
		//
		free(deviceInterfaceDetailData);
		deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);

	}

	//
	//Destroy device information set and free all associated memory. 
	//
	SetupDiDestroyDeviceInfoList(hDevInfo);

	//
	//Free setupapi library
	//
    FreeLibrary( pSetupAPI );

	//
	//
	//
	return hUsbPrinter;
}
コード例 #25
0
/*----------------------------------------------------------------------------*
*  NAME
*      IsDeviceBusy
*
*  DESCRIPTION
*      This method checks if the radio device is busy. Returns true or false
*---------------------------------------------------------------------------*/
bool CUSBTransport::IsDeviceBusy(void)
{
    // Check whether we can exclusively CreateFile(). If yes, then the device is
    // free. Otherwise, it's being used by some other process.
    //
    bool isTheDongleBusy = false;
    bool bIsDriverLoaded = false;
    SP_DEVINFO_DATA deviceOfInterest;
    SP_DEVICE_INTERFACE_DATA devInterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA pDevDetailData = NULL;
    HANDLE hAppHandle;
    DWORD requiredSize;

    HDEVINFO hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, 
                                            NULL,
                                            NULL, 
                                            DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

    if (hDevInfo != INVALID_HANDLE_VALUE) // Some USB device is connected.
    {
        // As this function will be called once it has been made sure that the
        // USB device is present and the driver is loaded, these values will not
        // be of importance here.

        ParseDeviceList(hDevInfo, bIsDriverLoaded, deviceOfInterest);

        if(bIsDriverLoaded)
        {
            devInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

            SetupDiEnumDeviceInterfaces(hDevInfo, 
                                        &deviceOfInterest,
                                        &GUID_DEVINTERFACE_USB_DEVICE, 
                                        DWORD(0), 
                                        &devInterfaceData);

            // Because the size of the SP_DEVICE_INTERFACE_DETAIL_DATA
            // structure varies, you need to call
            // SetupDiGetDeviceInterfaceDetail two times. The first call
            // gets the buffer size to allocate for the
            // SP_DEVICE_INTERFACE_DETAIL_DATA structure. The second call
            // fills the allocated buffer with detailed information about
            // the interface.
            //
            
            SetupDiGetDeviceInterfaceDetail(hDevInfo, 
                                            &devInterfaceData, 
                                            NULL,
                                            0, 
                                            &requiredSize, 
                                            NULL);

            pDevDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, requiredSize);

            pDevDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

            if(SetupDiGetDeviceInterfaceDetail(hDevInfo, 
                                               &devInterfaceData,
                                               pDevDetailData, 
                                               requiredSize, 
                                               NULL, NULL))
            {
                hAppHandle = CreateFile(pDevDetailData->DevicePath,
                                        GENERIC_READ | GENERIC_WRITE, 
                                        0, 
                                        NULL,
                                        OPEN_EXISTING, 
                                        FILE_FLAG_OVERLAPPED, 
                                        NULL);

                if(GetLastError() == ERROR_BUSY)
                {
                    isTheDongleBusy = true;
                }
                else
                {
                    CloseHandle(hAppHandle);
                }
            }

            LocalFree(pDevDetailData);
            pDevDetailData = NULL;
        }
        SetupDiDestroyDeviceInfoList(hDevInfo);
    }

    return isTheDongleBusy;
}
コード例 #26
0
ファイル: UsbEx.cpp プロジェクト: naorlss/dev-samples
////////////////////////////////////////////////////////////////////////////////
//	G e t U S B D e v i c e s
////////////////////////////////////////////////////////////////////////////////
INT GetUSBDevices( INT nMaxDevices, USB_DEVICE_NAME *lpUsbDevices, USB_ERROR_INFO *lpUsbErrorInfo )
{
	int									ii;
	DWORD								dwBytes;
	INT									nDeviceFound;
	HDEVINFO							hDevInfo;
	LPTSTR								lpToken, lpWorkToken;
	GUID								guidUSBDeviceSupport;
	HANDLE								hUsbPrinter;
	SP_DEVICE_INTERFACE_DATA			deviceInterfaceData;
	PSP_DEVICE_INTERFACE_DETAIL_DATA	deviceInterfaceDetailData;
	char								szUsb1284[1024];
	int									nDeviceIndex;
	HINSTANCE							pSetupAPI					= NULL;

	FAR HDEVINFO ( FAR WINAPI *SetupDiGetClassDevs )(CONST GUID *, PCTSTR, HWND, DWORD);
	FAR BOOL ( FAR WINAPI *SetupDiEnumDeviceInterfaces )(HDEVINFO, PSP_DEVINFO_DATA, CONST GUID *,DWORD, PSP_DEVICE_INTERFACE_DATA);
	FAR BOOL ( FAR WINAPI *SetupDiGetDeviceInterfaceDetail )(HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA);
	FAR BOOL ( FAR WINAPI *SetupDiDestroyDeviceInfoList )(HDEVINFO);



	//
	// The functions SetupDiGetClassDevs, SetupDiEnumDeviceInterfaces , 
	// SetupDiGetDeviceInterfaceDetail, SetupDiDestroyDeviceInfoList
	// are supported only on Windows 2000 and above and Windows 98 and above.
	// So link them dynamically to avoid windows errors.
	//
	pSetupAPI = LoadLibrary( "Setupapi" );

	if ( pSetupAPI != NULL )
	{

		SetupDiGetClassDevs = ( HDEVINFO ( WINAPI * )(CONST GUID *, PCTSTR, HWND, DWORD)) GetProcAddress( pSetupAPI, "SetupDiGetClassDevsA" );

		if ( SetupDiGetClassDevs == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiGetClassDevs");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiEnumDeviceInterfaces = ( BOOL ( WINAPI * )(HDEVINFO, PSP_DEVINFO_DATA, CONST GUID *,DWORD, PSP_DEVICE_INTERFACE_DATA)) GetProcAddress( pSetupAPI, "SetupDiEnumDeviceInterfaces" );

		if ( SetupDiEnumDeviceInterfaces == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiEnumDeviceInterfaces");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiGetDeviceInterfaceDetail = ( BOOL ( WINAPI * )(HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA)) GetProcAddress( pSetupAPI, "SetupDiGetDeviceInterfaceDetailA" );

		if ( SetupDiGetDeviceInterfaceDetail == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiGetDeviceInterfaceDetailA");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiDestroyDeviceInfoList = ( BOOL ( WINAPI * )(HDEVINFO)) GetProcAddress( pSetupAPI, "SetupDiDestroyDeviceInfoList" );

		if ( SetupDiDestroyDeviceInfoList == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiDestroyDeviceInfoList");
		    FreeLibrary( pSetupAPI );
			return 0;
		}
	}
	else
	{
		lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_HANDLE;
		strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to load Setupapi!");
		return 0;
	}



	//
	// initialize local variables and initialize error
	// struct if a non NULL pointer was passed.
	// 
	nDeviceFound = 0;
	if ( NULL != lpUsbErrorInfo )
		InitError( lpUsbErrorInfo );


	//
	// validate that the user passed in the number of
	// available USE_DEVICE_NAMES to fill with inofrmation.
	//
	if ( 0 == nMaxDevices )
	{	
		if ( NULL != lpUsbErrorInfo )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_DATA;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : nMaxDevices has a value of zero!");
		}
		return 0;
	};

	
	
	//
	// check that we can pass information back to the calling application!
	//
	if ( NULL == lpUsbDevices )
	{
		if ( NULL != lpUsbErrorInfo )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_DATA;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : lpUsbDevices is NULL!" );
		}
		return 0;
	}



	//
	// get a handle to the set of device information returned by the Win32 API
	// functions.  This handle points to an object that is then operated on 
	// by the SetupDiEnumDeviceInterfaces function.
	//
	guidUSBDeviceSupport = GUID_CLASS_USB_DEVICE;
	hDevInfo = SetupDiGetClassDevs(	&guidUSBDeviceSupport,
									0,
									0,
									0x12);	// TODO : Determine the constant
	if ( INVALID_HANDLE_VALUE == hDevInfo )
	{
		if ( NULL != lpUsbErrorInfo )
		{
			// get the last error from system
			lpUsbErrorInfo->dwSysLastError = GetLastError();

			// get the system defined message
			FormatMessage(	FORMAT_MESSAGE_FROM_SYSTEM			|
							FORMAT_MESSAGE_IGNORE_INSERTS,
							NULL,
							lpUsbErrorInfo->dwSysLastError,
							MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
							lpUsbErrorInfo->szSysErrorMsg,
							sizeof(lpUsbErrorInfo->szSysErrorMsg) / sizeof(lpUsbErrorInfo->szSysErrorMsg[0]),
							NULL );
		}
	}


	//
	//
	//
	nDeviceFound = nDeviceIndex = 0;	
	deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
	for (nDeviceIndex = 0; SetupDiEnumDeviceInterfaces( hDevInfo,
									  NULL,
									  &guidUSBDeviceSupport,
									  nDeviceIndex,
									  &deviceInterfaceData );
		nDeviceIndex++) 
	{



		//
		// determine the amout of memory we need to allocate for the next
		// call to this function
		//
		dwBytes= 0;
		ii = SetupDiGetDeviceInterfaceDetail(	hDevInfo,
												&deviceInterfaceData,
												NULL,
												0,
												&dwBytes,
												NULL );
		if ( 0 == dwBytes )
		{
			//
			// Reinitialize the data for next pass
			// through this loop.
			//
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}


		
		//Set cbSize in the detailData structure.
		deviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc (dwBytes);
		deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

			
		//
		// get the device path for the current device we are enumerating over.
		//
		ii = SetupDiGetDeviceInterfaceDetail(	hDevInfo,
												&deviceInterfaceData,
												deviceInterfaceDetailData,
												dwBytes, 
												&dwBytes,
												NULL );
		if ( 0 == ii )
		{
			//
			// Free DetailData struct and reinitialize the data for next pass
			//	through this loop.
			//
			free(deviceInterfaceDetailData);
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}


		//
		// get handle to the device so that we can 
		//
		hUsbPrinter = CreateFile(	deviceInterfaceDetailData->DevicePath,
									GENERIC_READ		| 
										GENERIC_WRITE,
									FILE_SHARE_WRITE	|
										FILE_SHARE_READ,
									NULL,
									OPEN_EXISTING,
									0,
									NULL );


		//
		//
		//
		if ( INVALID_HANDLE_VALUE == hUsbPrinter )
		{
			//
			// Free DetailData struct and reinitialize the data for next pass
			// through this loop.
			//
			free(deviceInterfaceDetailData);
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}



		//
		//
		//
		dwBytes = 0;
		memset( szUsb1284, 0, sizeof(szUsb1284) );
		ii = DeviceIoControl(	hUsbPrinter,
								IOCTL_USBPRINT_GET_1284_ID,
								NULL,
								0,
								szUsb1284,
								sizeof(szUsb1284),
								&dwBytes,
								NULL );

		//
		//
		//
		CloseHandle( hUsbPrinter );



		//
		// parse the PNP string returned from the device.
		//		
		lpToken = strtok( szUsb1284, PNP_DELIMITOR );
		while ( NULL != lpToken )
		{
			// have the manfacturer.
			lpWorkToken = strstr(lpToken, MFG_TOKEN);
			if (lpWorkToken != NULL)
			{
				strcpy(	lpUsbDevices[nDeviceFound].szDeviceMfg, lpWorkToken + MFG_TOKEN_LEN);
				RTrim( lpUsbDevices[nDeviceFound].szDeviceMfg );
			}

			//	model of the printer
			lpWorkToken = strstr(lpToken, MDL_TOKEN);
			if (lpWorkToken != NULL)
			{
				strcpy(	lpUsbDevices[nDeviceFound].szDevicePdt, lpWorkToken + MDL_TOKEN_LEN );
				RTrim( lpUsbDevices[nDeviceFound].szDevicePdt );
			}


			// next token
			lpToken = strtok( NULL, PNP_DELIMITOR );
		}



		//
		//  if the we don't manage to get BOTH the manufacturer and the product
		// of the USB printer then don't return information back the calling code.
		//
		if (	strlen(lpUsbDevices[nDeviceFound].szDeviceMfg) + 
				strlen(lpUsbDevices[nDeviceFound].szDevicePdt) > 1 )
		{
			nDeviceFound++;
			
			//break after getting the number of devices requested.
			if (nMaxDevices == nDeviceFound)
			{
		        free(deviceInterfaceDetailData);
				break;

			}

		}
		else
		{
			lpUsbDevices[nDeviceFound].szDeviceMfg[0] = 
			lpUsbDevices[nDeviceFound].szDevicePdt[0] = 0;
		}



		//
		// Free DetailData struct and reinitialize the data for next pass
		// through this loop.
		//
        free(deviceInterfaceDetailData);
		deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);

	}

	//
	//Destroy device information set and free all associated memory. 
	//
	SetupDiDestroyDeviceInfoList(hDevInfo);

	//
	//Free setupapi library
	//
    FreeLibrary( pSetupAPI );

	return nDeviceFound;

}
コード例 #27
0
PTCHAR CDevice::GetDevicePath( IN  LPGUID InterfaceGuid )
{
    HDEVINFO HardwareDeviceInfo;
    SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = NULL;
    ULONG Length, RequiredLength = 0;
    BOOL bResult;

    HardwareDeviceInfo = SetupDiGetClassDevs(
                             InterfaceGuid,
                             NULL,
                             NULL,
                             (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)
                             );

    if (HardwareDeviceInfo == INVALID_HANDLE_VALUE) {
        PrintMessage("Cannot get class devices");
        return NULL;
    }

    DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

    bResult = SetupDiEnumDeviceInterfaces(
                             HardwareDeviceInfo,
                             0,
                             InterfaceGuid,
                             0,
                             &DeviceInterfaceData
                             );

    if (bResult == FALSE) {
        PrintMessage("Cannot get enumerate device interfaces");
        SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
        return NULL;
    }

    SetupDiGetDeviceInterfaceDetail(
                             HardwareDeviceInfo,
                             &DeviceInterfaceData,
                             NULL,
                             0,
                             &RequiredLength,
                             NULL
                             );

    DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) LocalAlloc(LMEM_FIXED, RequiredLength);

    if (DeviceInterfaceDetailData == NULL) {
        PrintMessage("Cannot allocate memory");
        SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
        return NULL;
    }

    DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

    Length = RequiredLength;

    bResult = SetupDiGetDeviceInterfaceDetail(
                             HardwareDeviceInfo,
                             &DeviceInterfaceData,
                             DeviceInterfaceDetailData,
                             Length,
                             &RequiredLength,
                             NULL
                             );

    if (bResult == FALSE) {
        PrintMessage("Cannot get device interface details");
        SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
        LocalFree(DeviceInterfaceDetailData);
        return NULL;
    }

    return DeviceInterfaceDetailData->DevicePath;
}
コード例 #28
0
ファイル: IOWin.cpp プロジェクト: Asmodean-/dolphin
// Find and connect wiimotes.
// Does not replace already found wiimotes even if they are disconnected.
// wm is an array of max_wiimotes wiimotes
// Returns the total number of found and connected wiimotes.
void WiimoteScanner::FindWiimotes(std::vector<Wiimote*> & found_wiimotes, Wiimote* & found_board)
{
	if (!s_loaded_ok)
		return;

	ProcessWiimotes(true, [](HANDLE hRadio, const BLUETOOTH_RADIO_INFO& rinfo, BLUETOOTH_DEVICE_INFO_STRUCT& btdi)
	{
		ForgetWiimote(btdi);
		AttachWiimote(hRadio, rinfo, btdi);
	});

	// Get the device id
	GUID device_id;
	pHidD_GetHidGuid(&device_id);

	// Get all hid devices connected
	HDEVINFO const device_info = SetupDiGetClassDevs(&device_id, nullptr, nullptr, (DIGCF_DEVICEINTERFACE | DIGCF_PRESENT));

	SP_DEVICE_INTERFACE_DATA device_data;
	device_data.cbSize = sizeof(device_data);
	PSP_DEVICE_INTERFACE_DETAIL_DATA detail_data = nullptr;

	for (int index = 0; SetupDiEnumDeviceInterfaces(device_info, nullptr, &device_id, index, &device_data); ++index)
	{
		// Get the size of the data block required
		DWORD len;
		SetupDiGetDeviceInterfaceDetail(device_info, &device_data, nullptr, 0, &len, nullptr);
		detail_data = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(len);
		detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

		// Query the data for this device
		if (SetupDiGetDeviceInterfaceDetail(device_info, &device_data, detail_data, len, nullptr, nullptr))
		{
			auto const wm = new Wiimote;
			wm->devicepath = detail_data->DevicePath;
			bool real_wiimote = false, is_bb = false;

			CheckDeviceType(wm->devicepath, real_wiimote, is_bb);
			if (is_bb)
			{
				found_board = wm;
			}
			else if (real_wiimote)
			{
				found_wiimotes.push_back(wm);
			}
			else
			{
				delete wm;
			}
		}

		free(detail_data);
	}

	SetupDiDestroyDeviceInfoList(device_info);

	// Don't mind me, just a random sleep to fix stuff on Windows
	//if (!wiimotes.empty())
	//    SLEEP(2000);

}
コード例 #29
0
ファイル: winutil.c プロジェクト: Eksmo/calibre
PSP_DEVICE_INTERFACE_DETAIL_DATA
get_device_ancestors(HDEVINFO hDevInfo, DWORD index, PyObject *candidates, BOOL *iterate, BOOL ddebug) {
    SP_DEVICE_INTERFACE_DATA            interfaceData;
    SP_DEVINFO_DATA						devInfoData;
    BOOL                                status;
    PSP_DEVICE_INTERFACE_DETAIL_DATA    interfaceDetailData;
    DWORD                               interfaceDetailDataSize,
                                        reqSize;
    DEVINST                             parent, pos;
    wchar_t                             temp[BUFSIZE];
    int                                 i;
    PyObject                            *devid;

    interfaceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);
    devInfoData.cbSize   = sizeof (SP_DEVINFO_DATA);

    status = SetupDiEnumDeviceInterfaces (
                hDevInfo,               // Interface Device Info handle
                NULL,                   // Device Info data
                (LPGUID)&GUID_DEVINTERFACE_VOLUME, // Interface registered by driver
                index,                  // Member
                &interfaceData          // Device Interface Data
                );
    if ( status == FALSE ) {
        *iterate = FALSE;
        return NULL;
    }
    SetupDiGetDeviceInterfaceDetail (
                hDevInfo,           // Interface Device info handle
                &interfaceData,     // Interface data for the event class
                NULL,               // Checking for buffer size
                0,                  // Checking for buffer size
                &reqSize,           // Buffer size required to get the detail data
                NULL                // Checking for buffer size
    );

    interfaceDetailDataSize = reqSize;
    interfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)PyMem_Malloc(interfaceDetailDataSize+50);
    if ( interfaceDetailData == NULL ) {
        PyErr_NoMemory();
        return NULL;
    }
    interfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);
    devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

    status = SetupDiGetDeviceInterfaceDetail (
                  hDevInfo,                 // Interface Device info handle
                  &interfaceData,           // Interface data for the event class
                  interfaceDetailData,      // Interface detail data
                  interfaceDetailDataSize,  // Interface detail data size
                  &reqSize,                 // Buffer size required to get the detail data
                  &devInfoData);            // Interface device info
    if (ddebug) printf("Getting ancestors\n"); fflush(stdout);

    if ( status == FALSE ) {PyErr_SetFromWindowsErr(0); PyMem_Free(interfaceDetailData); return NULL;}

    pos = devInfoData.DevInst;

    for(i = 0; i < 10; i++) {
        // Get the device instance of parent.
        if (CM_Get_Parent(&parent, pos, 0) != CR_SUCCESS) break;
        if (CM_Get_Device_ID(parent, temp, BUFSIZE, 0) == CR_SUCCESS) {
            if (ddebug) wprintf(L"device id: %s\n", temp); fflush(stdout);
            devid = PyUnicode_FromWideChar(temp, wcslen(temp));
            if (devid) {
                PyList_Append(candidates, devid);
                Py_DECREF(devid);
            }
        }
        pos = parent;
    }

    return interfaceDetailData;
}
コード例 #30
0
ファイル: usb.cpp プロジェクト: shoupydad/CCDAuto
HANDLE CUSBDevice::ConnectToIthDevice (DWORD deviceIndex)
{
    GUID hidGUID;
    HDEVINFO hardwareDeviceInfoSet;
    SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
    PSP_INTERFACE_DEVICE_DETAIL_DATA deviceDetail;
    ULONG requiredSize;
    HANDLE deviceHandle = INVALID_HANDLE_VALUE;
    DWORD result;

    //Get the HID GUID value - used as mask to get list of devices
    HidD_GetHidGuid (&hidGUID);

    //Get a list of devices matching the criteria (hid interface, present)
    hardwareDeviceInfoSet = SetupDiGetClassDevs (&hidGUID,
                                                 NULL, // Define no enumerator (global)
                                                 NULL, // Define no
                                                 (DIGCF_PRESENT | // Only Devices present
                                                 DIGCF_DEVICEINTERFACE)); // Function class devices.

    deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

    //Go through the list and get the interface data
    result = SetupDiEnumDeviceInterfaces (hardwareDeviceInfoSet,
                                          NULL, //infoData,
                                          &hidGUID, //interfaceClassGuid,
                                          deviceIndex, 
                                          &deviceInterfaceData);

    /* Failed to get a device - possibly the index is larger than the number of devices */
    if (result == FALSE)
    {
        SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet);
        return INVALID_HANDLE_VALUE;
    }

    //Get the details with null values to get the required size of the buffer
    SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfoSet,
                                     &deviceInterfaceData,
                                     NULL, //interfaceDetail,
                                     0, //interfaceDetailSize,
                                     &requiredSize,
                                     0); //infoData))

    //Allocate the buffer
    deviceDetail = (PSP_INTERFACE_DEVICE_DETAIL_DATA)malloc(requiredSize);
    deviceDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
	
    //Fill the buffer with the device details
    if (!SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfoSet,
		&deviceInterfaceData,
		deviceDetail,
		requiredSize,
		&requiredSize,
		NULL)) 
    {
        SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet);
        free (deviceDetail);
        return INVALID_HANDLE_VALUE;
    }
	
    //Open file on the device
    deviceHandle = CreateFile (deviceDetail->DevicePath,
		GENERIC_READ | GENERIC_WRITE,
		FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL,        // no SECURITY_ATTRIBUTES structure
		OPEN_EXISTING, // No special create flags
		FILE_FLAG_OVERLAPPED, 
		NULL);       // No template file

	
    SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet);
    free (deviceDetail);
    return deviceHandle;
}