int usb_install_needs_restart_np(void) { HDEVINFO dev_info; SP_DEVINFO_DATA dev_info_data; int dev_index = 0; SP_DEVINSTALL_PARAMS install_params; int ret = FALSE; dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA); dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT); SetEnvironmentVariable("LIBUSB_NEEDS_REBOOT", "1"); if(dev_info == INVALID_HANDLE_VALUE) { usb_error("usb_install_needs_restart_np(): getting " "device info set failed"); return ret; } while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data)) { memset(&install_params, 0, sizeof(SP_PROPCHANGE_PARAMS)); install_params.cbSize = sizeof(SP_DEVINSTALL_PARAMS); if(SetupDiGetDeviceInstallParams(dev_info, &dev_info_data, &install_params)) { if(install_params.Flags & (DI_NEEDRESTART | DI_NEEDREBOOT)) { usb_message("usb_install_needs_restart_np(): restart needed"); ret = TRUE; } } dev_index++; } SetupDiDestroyDeviceInfoList(dev_info); return ret; }
void AddRmForAllDevice(DWORD AffinityMask, BOOL fAdd, int targetIndex) { HDEVINFO hDevInfo = INVALID_HANDLE_VALUE; int deviceIndex; SP_DEVINFO_DATA devInfoData; devInfoData.cbSize = sizeof(SP_DEVINFO_DATA); //API required. do { hDevInfo = SetupDiGetClassDevs( NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT | DIGCF_PROFILE ); if (hDevInfo == INVALID_HANDLE_VALUE) { Warn("unable to get a list of devices.\n"); break; } for ( deviceIndex = 0; SetupDiEnumDeviceInfo(hDevInfo, deviceIndex, &devInfoData); deviceIndex++) { if ((targetIndex < 0) || (targetIndex == deviceIndex)) { if (fAdd) AddFilterForDevice(hDevInfo, &devInfoData, AffinityMask); else RmFilterForDevice(hDevInfo, &devInfoData); } } } while (FALSE); if (hDevInfo != INVALID_HANDLE_VALUE) { SetupDiDestroyDeviceInfoList(hDevInfo); hDevInfo = INVALID_HANDLE_VALUE; } }
void vm_sys_info_get_vga_card(vm_char *vga_card) { SP_DEVINFO_DATA sp_dev_info; HDEVINFO DeviceInfoSet; vm_char string1[] = VM_STRING("Display"); Ipp32u dwIndex = 0; vm_char data[_MAX_LEN] = {0,}; /* check error(s) */ if (NULL == vga_card) return; ZeroMemory(&sp_dev_info, sizeof(SP_DEVINFO_DATA)); ZeroMemory(&DeviceInfoSet, sizeof(HDEVINFO)); DeviceInfoSet = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT); sp_dev_info.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); while (SetupDiEnumDeviceInfo(DeviceInfoSet, dwIndex, &sp_dev_info)) { SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &sp_dev_info, SPDRP_CLASS, NULL, (Ipp8u *) data, _MAX_LEN, NULL); if (!vm_string_strcmp((vm_char*)data, string1)) { SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &sp_dev_info, SPDRP_DEVICEDESC, NULL, (PBYTE) vga_card, _MAX_LEN, NULL); break; } dwIndex++; } SetupDiDestroyDeviceInfoList(DeviceInfoSet); } /* void vm_sys_info_get_vga_card(vm_char *vga_card) */
void enum_mobile_devices(pfc::list_t<device_instance_info_t> & p_out) { HDEVINFO di = SetupDiGetClassDevs(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE); if (di != INVALID_HANDLE_VALUE) { SP_DEVINFO_DATA did; memset(&did, 0, sizeof(did)); did.cbSize = sizeof(did); DWORD i; for (i=0; SetupDiEnumDeviceInfo(di, i, &did); i++) { //if (did.ClassGuid == GUID_DEVCLASS_USB) { ULONG DevDiskLen=0; pfc::array_t<WCHAR> DevDisk; if (CR_SUCCESS == CM_Get_Device_ID_Size(&DevDiskLen, did.DevInst, NULL)) { DevDisk.set_size(DevDiskLen+1); DevDisk.fill_null(); if (CR_SUCCESS == CM_Get_Device_ID(did.DevInst, DevDisk.get_ptr(), DevDisk.get_size(), NULL)) { if (g_check_devid_is_mobile_device(DevDisk.get_ptr())) { device_instance_info_t temp; temp.m_handle = did.DevInst; temp.m_path = DevDisk.get_ptr(); p_out.add_item(temp); console::formatter() << "iPod manager: USB AMD enumerator: Found " << Tu(DevDisk.get_ptr()); } } } } } SetupDiDestroyDeviceInfoList(di); } if (!p_out.get_count()) console::formatter() << "iPod manager: USB AMD enumerator: No devices found!"; }
static int rescan (void) { int idx, idx2; for (idx2 = 0; guids[idx2]; idx2++) { HDEVINFO hDevInfo = SetupDiGetClassDevs( guids[idx2], NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE); if (hDevInfo != INVALID_HANDLE_VALUE) { for (idx = 0; ; idx++) { if (!getCDROMProperty (idx, hDevInfo, guids[idx2])) break; } SetupDiDestroyDeviceInfoList (hDevInfo); } } for (idx2 = 0; scsinames[idx2]; idx2++) { int max = 10; for (idx = 0; idx < max; idx++) { TCHAR tmp[100]; HANDLE h; _stprintf (tmp, L"\\\\.\\%s%d", scsinames[idx2], idx); h = CreateFile (tmp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (h != INVALID_HANDLE_VALUE) { adddrive (tmp, -1, -1, -1, -1, 2); CloseHandle (h); if (idx == max - 1) max++; } } } if (currprefs.win32_uaescsimode == UAESCSI_SPTISCAN) { write_log (L"SCSI adapter enumeration..\n"); scanscsi (); write_log (L"SCSI adapter enumeration ends\n"); } return 1; }
QStringList QPCSC::drivers() const { #ifdef Q_OS_WIN HDEVINFO h = SetupDiGetClassDevs( 0, 0, 0, DIGCF_ALLCLASSES | DIGCF_PRESENT ); if( !h ) return QStringList(); SP_DEVINFO_DATA info = { sizeof(SP_DEVINFO_DATA) }; QStringList list; for( DWORD i = 0; SetupDiEnumDeviceInfo( h, i, &info ); i++ ) { DWORD size = 0; WCHAR data[1024]; SetupDiGetDeviceRegistryPropertyW( h, &info, SPDRP_CLASS, 0, LPBYTE(data), sizeof(data), &size ); if( _wcsicmp( data, L"SmartCardReader" ) != 0 ) continue; DWORD conf = 0; SetupDiGetDeviceRegistryPropertyW( h, &info, SPDRP_CONFIGFLAGS, 0, LPBYTE(&conf), sizeof(conf), &size ); if( conf & CONFIGFLAG_DISABLED ) continue; SetupDiGetDeviceRegistryPropertyW( h, &info, SPDRP_DEVICEDESC, 0, LPBYTE(data), sizeof(data), &size ); QString name( (QChar*)data ); SetupDiGetDeviceRegistryPropertyW( h, &info, SPDRP_HARDWAREID, 0, LPBYTE(data), sizeof(data), &size ); list << QString( "%1 (%2)").arg( name, QString( (QChar*)data ) ); } SetupDiDestroyDeviceInfoList( h ); return list; #else return readers(); #endif }
int _tmain(int argc, _TCHAR* argv[]) { WCHAR *wDeviceName = L"TAP-Win32 Adapter V9"; SP_DEVINFO_DATA deviceInfoData; HDEVINFO hDevHandle; deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); hDevHandle = SetupDiGetClassDevs(&GUID_DEVCLASS_NET, NULL, NULL, DIGCF_PRESENT); wcscpy_s(wDeviceInstanceId, MAX_PATH, L"NULL"); FillDeviceInstanceId(hDevHandle, deviceInfoData, wDeviceName); SetupDiDestroyDeviceInfoList(hDevHandle); if (wcscmp(wDeviceInstanceId, L"NULL") == 0) { wprintf(L"An error occurred.\n"); return 1; } WCHAR wBind[1024]; RtlZeroMemory(wBind, 1024); // Prepend 'ms_tcpip->' to the device instance ID wcscpy_s(wBind, L"ms_tcpip->"); wcscat_s(wBind, wDeviceInstanceId); RtlZeroMemory(wDeviceInstanceId, MAX_PATH); wcscpy_s(wDeviceInstanceId, MAX_PATH, wBind); wprintf(L"Changing binding order for %s...\n", wDeviceInstanceId); ChangeNicBindingOrder(); return 0; }
static void test_SetupDiGetClassDevsA(void) { HDEVINFO device_info; SetLastError( 0xdeadbeef ); device_info = SetupDiGetClassDevs( NULL, NULL, NULL, 0 ); ok( device_info == INVALID_HANDLE_VALUE, "Fail expected\n" ); ok_lasterr( ERROR_INVALID_PARAMETER ); SetLastError( 0xdeadbeef ); device_info = SetupDiGetClassDevs( NULL, NULL, NULL, DIGCF_ALLCLASSES ); ok( device_info != INVALID_HANDLE_VALUE, "Error reported %lx\n", GetLastError() ); SetLastError( 0xdeadbeef ); ok( SetupDiDestroyDeviceInfoList( device_info ), "Error reported %lx\n", GetLastError() ); SetLastError( 0xdeadbeef ); device_info = SetupDiGetClassDevs( NULL, NULL, NULL, DIGCF_DEVICEINTERFACE ); ok( device_info == INVALID_HANDLE_VALUE, "Fail expected\n" ); ok_lasterr( ERROR_INVALID_PARAMETER ); SetLastError( 0xdeadbeef ); device_info = SetupDiGetClassDevs( &test_class_guid, NULL, NULL, 0 ); ok( device_info != INVALID_HANDLE_VALUE, "Error reported %lx\n", GetLastError() ); SetLastError( 0xdeadbeef ); ok( SetupDiDestroyDeviceInfoList( device_info ), "Error reported %lx\n", GetLastError() ); SetLastError( 0xdeadbeef ); device_info = SetupDiGetClassDevs( NULL, "(invalid enumerator)", NULL, DIGCF_ALLCLASSES ); ok( device_info == INVALID_HANDLE_VALUE, "Fail expected\n" ); ok_lasterr( ERROR_INVALID_DATA ); SetLastError( 0xdeadbeef ); device_info = SetupDiGetClassDevs( NULL, "Root", NULL, DIGCF_ALLCLASSES ); ok( device_info != INVALID_HANDLE_VALUE, "Error reported %lx\n", GetLastError() ); SetLastError( 0xdeadbeef ); ok( SetupDiDestroyDeviceInfoList( device_info ), "Error reported %lx\n", GetLastError() ); }
// //////////////////////////////////////////////////////////////////////////////// // ÉèÖÃÍø¿¨×´Ì¬ // 1 - ÆôÓà // 0 - ½ûÓà // BOOL NetTools::SetMacState(BOOL bState) { HDEVINFO hDevInfo = SetupDiGetClassDevs( NULL, NULL, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES ); if ( INVALID_HANDLE_VALUE == hDevInfo ) { DebugTools::OutputDebugPrintf(L"[NetTools] [SetMacState] SetupDiGetClassDevs Failed.\r\n"); return FALSE; } SP_DEVINFO_DATA DeviceInfoData = {sizeof(SP_DEVINFO_DATA)}; for (int i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++) { if ( NetToolsInternal::IsClassNet(&DeviceInfoData.ClassGuid) ) { DWORD dwStatus = bState ? DICS_ENABLE : DICS_DISABLE; if ( !NetToolsInternal::StateChange(dwStatus, i, hDevInfo) ) { DebugTools::OutputDebugPrintf(L"[NetTools] [SetMacState] StateChange Failed.\r\n"); } else { return TRUE; } } } return TRUE; }
//------------------------------------------------------------------------ // GetNumDevices() // // Counts the number of Silabs USB devices listed in the registry. //------------------------------------------------------------------------ DWORD CUsbIF::GetNumDevices() { DWORD numDevices = 0; // Retrieve device list for GUID that has been specified. HDEVINFO hDevInfoList = SetupDiGetClassDevs (&m_GUID, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)); if (hDevInfoList != NULL) { SP_DEVICE_INTERFACE_DATA deviceInfoData; for (int index = 0; index < 127;index++) { // Clear data structure ZeroMemory(&deviceInfoData, sizeof(deviceInfoData)); deviceInfoData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); // retrieves a context structure for a device interface of a device information set. if (SetupDiEnumDeviceInterfaces (hDevInfoList, 0, &m_GUID, index, &deviceInfoData)) { numDevices++; } else { if ( GetLastError() == ERROR_NO_MORE_ITEMS ) break; } } } // SetupDiDestroyDeviceInfoList() destroys a device information set // and frees all associated memory. SetupDiDestroyDeviceInfoList (hDevInfoList); return numDevices; }
DWORD OpenDeviceList( IN LPGUID InterfaceGuid, OUT HDEVINFO * OutHandle) { HDEVINFO DeviceHandle; DeviceHandle = SetupDiGetClassDevs(InterfaceGuid, NULL, NULL, DIGCF_DEVICEINTERFACE); //DIGCF_PRESENT /* check for success */ if (DeviceHandle == INVALID_HANDLE_VALUE) { /* failed to create device list */ return GetLastError(); } /* store result */ *OutHandle = DeviceHandle; return ERROR_SUCCESS; }
/*! \brief Enumerate Xsens USB devices If the OS already has drivers running for a device, the device should already have been found by xsEnumerateSerialPorts(). \param[in,out] ports The list of serial ports to append to */ bool xsEnumerateUsbDevices(XsPortInfoList& ports) { XsPortInfo current; #ifdef USE_WINUSB BOOL bResult = FALSE; ULONG length; ULONG requiredLength=0; // {FD51225C-700A-47e5-9999-B2D9031B88ED} GUID guid = { 0xfd51225c, 0x700a, 0x47e5, { 0x99, 0x99, 0xb2, 0xd9, 0x3, 0x1b, 0x88, 0xed } }; HDEVINFO deviceInfo; SP_DEVICE_INTERFACE_DATA interfaceData; PSP_DEVICE_INTERFACE_DETAIL_DATA_A detailData = NULL; deviceInfo = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); // Initialize variables. interfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA); int port = 0; for (DWORD dwIndex = 0; port == 0; ++dwIndex) { BOOL bRet = SetupDiEnumDeviceInterfaces( deviceInfo, NULL, &guid, dwIndex, &interfaceData); if (!bRet) { if (GetLastError() == ERROR_NO_MORE_ITEMS) break; } else { if (!SetupDiGetDeviceInterfaceDetail(deviceInfo, &interfaceData, NULL, 0, &requiredLength, NULL)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { SetupDiDestroyDeviceInfoList(deviceInfo); return false; } } detailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA_A)LocalAlloc(LMEM_FIXED, requiredLength); if (NULL == detailData) { SetupDiDestroyDeviceInfoList(deviceInfo); return false; } detailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A); length = requiredLength; SP_DEVINFO_DATA DevInfoData; DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA); bResult = SetupDiGetDeviceInterfaceDetailA(deviceInfo, &interfaceData, detailData, length, &requiredLength, &DevInfoData); if (!bResult) { LocalFree(detailData); SetupDiDestroyDeviceInfoList(deviceInfo); return false; } unsigned char serialNumber[256]; char* ptrEnd, *ptrStart = strchr(detailData->DevicePath, '#'); if (!ptrStart) continue; ptrStart = strchr(ptrStart+1, '#'); if (!ptrStart) continue; ptrEnd = strchr(ptrStart+1, '#'); if (!ptrEnd) continue; strncpy((char*)serialNumber, ptrStart+1, ptrEnd-ptrStart-1); serialNumber[ptrEnd-ptrStart-1] = '\0'; current.setPortName(detailData->DevicePath); int id = 0; sscanf((const char *)serialNumber, "%X", &id); current.setDeviceId((uint32_t) id); ports.push_back(current); } } SetupDiDestroyDeviceInfoList(deviceInfo); return true; #elif defined(HAVE_LIBUSB) XsLibUsb libUsb; libusb_context *context; int result = libUsb.init(&context); if (result != LIBUSB_SUCCESS) return true; libusb_device **deviceList; ssize_t deviceCount = libUsb.get_device_list(context, &deviceList); for (ssize_t i = 0; i < deviceCount; i++) { libusb_device *device = deviceList[i]; libusb_device_descriptor desc; result = libUsb.get_device_descriptor(device, &desc); if (result != LIBUSB_SUCCESS) continue; if (desc.idVendor != XSENS_VENDOR_ID && desc.idVendor != ATMEL_VENDOR_ID) continue; libusb_device_handle *handle; result = libUsb.open(device, &handle); if (result != LIBUSB_SUCCESS) continue; unsigned char serialNumber[256]; result = libUsb.get_string_descriptor_ascii(handle, desc.iSerialNumber, serialNumber, 256); if (desc.idVendor == ATMEL_VENDOR_ID && desc.idProduct == ATMEL_BORROWED_PRODUCT_ID) { unsigned char productName[256]; result = libUsb.get_string_descriptor_ascii(handle, desc.iProduct, productName, 256); if (strcmp("Xsens COM port", (const char *)productName) != 0) { libUsb.close(handle); continue; } } libusb_config_descriptor *configDesc; result = libUsb.get_active_config_descriptor(device, &configDesc); if (result != LIBUSB_SUCCESS) { libUsb.close(handle); continue; } bool kernelActive = false; for (uint8_t ifCount = 0; ifCount < configDesc->bNumInterfaces; ++ifCount) { int res = libUsb.kernel_driver_active(handle, ifCount); kernelActive |= (res == 1); } libUsb.free_config_descriptor(configDesc); if (!kernelActive) { char name[256]; sprintf(name, "USB%03u:%03u", libUsb.get_bus_number(device), libUsb.get_device_address(device)); current.setPortName(name); int id = 0; sscanf((const char *)serialNumber, "%X", &id); current.setDeviceId((uint32_t) id); ports.push_back(current); } else { JLDEBUG(gJournal, "Kernel driver active on USB" << libUsb.get_bus_number(device) << ":" << libUsb.get_device_address(device) << " device " << serialNumber); } libUsb.close(handle); } libUsb.free_device_list(deviceList, 1); libUsb.exit(context); return true; #else (void)ports; return false; #endif }
int usbOpenDevice(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 = USB_ERROR_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 = USB_ERROR_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 = USB_ERROR_NOTFOUND; if(vendorName != NULL && productName != NULL){ char buffer[512]; if(!HidD_GetManufacturerString(handle, buffer, sizeof(buffer))){ DEBUG_PRINT(("error obtaining vendor name\n")); errorCode = USB_ERROR_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 = USB_ERROR_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; }
int iKX::init(int device,int ignore_winmm) { int i=0; char string[1024]; int ret=-1; if(device_num!=-1) // double init { strcpy(error_name,"interface already initialized"); debug("iKX init(): already initialized\n"); return -7; } strcpy(error_name,"no error"); // asio init asio_inited=0; last_asio_voice=-1; asio_method=0; asio_iks_property=NULL; asio_secondary_buffer=NULL; asio_prim_buffer=NULL; asio_ds=NULL; pRenderEnumerator=0; pRenderFilter=0; pRenderPin=0; memset(asio_mem_table,0,sizeof(asio_mem_table)); memset(&guid_,0,sizeof(guid_)); device_num=device; HDEVINFO hInfo=SetupDiGetClassDevs((GUID *)&KSCATEGORY_AUDIO,NULL,NULL,DIGCF_DEVICEINTERFACE |DIGCF_PRESENT); if(hInfo==INVALID_HANDLE_VALUE) { debug("iKX init(): setupdigetclassdevs failed [%x]\n",GetLastError()); strcpy(error_name,"error enumerating devices"); return ret; } SP_DEVINFO_DATA devinfo; devinfo.cbSize=sizeof(devinfo); while(SetupDiEnumDeviceInfo(hInfo,i,&devinfo)) { i++; if(SetupDiGetDeviceInstanceId(hInfo,&devinfo,string,sizeof(string),NULL)) { if( (strstr(string,"VEN_1102&DEV_0002")==NULL) && (strstr(string,"VEN_1102&DEV_0004")==NULL) && (strstr(string,"VEN_1102&DEV_0008")==NULL) ) // FIXME: bad test, actually :( { continue; } } else { continue; } SP_DEVICE_INTERFACE_DATA data; data.cbSize=sizeof(data); int j=0; while(SetupDiEnumDeviceInterfaces(hInfo,&devinfo,(GUID *)&KSCATEGORY_AUDIO,j++,&data)==TRUE) { DWORD ReqLen=0; SetupDiGetInterfaceDeviceDetail ( hInfo, &data, NULL, 0, &ReqLen, NULL ); PSP_INTERFACE_DEVICE_DETAIL_DATA m_Detail = PSP_INTERFACE_DEVICE_DETAIL_DATA(new char[ReqLen]); if ( m_Detail ) { m_Detail->cbSize = sizeof SP_INTERFACE_DEVICE_DETAIL_DATA; if(SetupDiGetInterfaceDeviceDetail ( hInfo, &data, m_Detail, ReqLen, &ReqLen, NULL )==TRUE) { if(strstr(m_Detail->DevicePath,"kx_topo1")!=NULL) { HKEY key=SetupDiOpenDeviceInterfaceRegKey(hInfo,&data,0,KEY_ALL_ACCESS); if(key!=INVALID_HANDLE_VALUE) { DWORD type; type=REG_SZ; char tmp_str[256]; DWORD len; len=(DWORD)sizeof(tmp_str); if(RegQueryValueEx(key,"FriendlyName",NULL,&type,(unsigned char *)tmp_str,&len)==ERROR_SUCCESS) { strncpy(mixer_name,tmp_str,sizeof(mixer_name)); } RegCloseKey(key); } strncpy(topo_path,m_Detail->DevicePath,sizeof(topo_path)); } else if(strstr(m_Detail->DevicePath,"kx_wave0")!=NULL) { HKEY key=SetupDiOpenDeviceInterfaceRegKey(hInfo,&data,0,KEY_ALL_ACCESS); if(key!=INVALID_HANDLE_VALUE) { DWORD type; type=REG_SZ; char tmp_str[256]; DWORD len; len=(DWORD)sizeof(tmp_str); if(RegQueryValueEx(key,"FriendlyName",NULL,&type,(unsigned char *)tmp_str,&len)==ERROR_SUCCESS) { strncpy(wave_name,tmp_str,sizeof(wave_name)); strncpy(wave23_name,tmp_str,sizeof(wave_name)); char *p=strstr(wave23_name," 0/1"); if(p) { *p=0; strcpy(wave45_name,wave23_name); strcpy(wave67_name,wave23_name); strcpy(waveHQ_name,wave23_name); strcat(wave23_name," 2/3"); strcat(wave45_name," 4/5"); strcat(wave67_name," 6/7"); strcat(waveHQ_name," HQ"); } else { wave23_name[0]=0; debug("ikX API: not all the 4 wave devices were found... strange\n"); } } RegCloseKey(key); } strncpy(wave_path,m_Detail->DevicePath,sizeof(wave_path)); } else if(strstr(m_Detail->DevicePath,"kx_uart2")!=NULL) { //strncpy(uart2_path,m_Detail->DevicePath,sizeof(uart2_path)); HKEY key=SetupDiOpenDeviceInterfaceRegKey(hInfo,&data,0,KEY_ALL_ACCESS); if(key!=INVALID_HANDLE_VALUE) { DWORD type; type=REG_SZ; char tmp_str[256]; DWORD len; len=(DWORD)sizeof(tmp_str); if(RegQueryValueEx(key,"FriendlyName",NULL,&type,(unsigned char *)tmp_str,&len)==ERROR_SUCCESS) { strncpy(uart2_name,tmp_str,sizeof(uart2_name)); } RegCloseKey(key); } } else if(strstr(m_Detail->DevicePath,"kx_uart1")!=NULL) { //strncpy(uart_path,m_Detail->DevicePath,sizeof(uart_path)); HKEY key=SetupDiOpenDeviceInterfaceRegKey(hInfo,&data,0,KEY_ALL_ACCESS); if(key!=INVALID_HANDLE_VALUE) { DWORD type; type=REG_SZ; char tmp_str[256]; DWORD len; len=(DWORD)sizeof(tmp_str); if(RegQueryValueEx(key,"FriendlyName",NULL,&type,(unsigned char *)tmp_str,&len)==ERROR_SUCCESS) { strncpy(uart_name,tmp_str,sizeof(uart_name)); } RegCloseKey(key); } } else if(strstr(m_Detail->DevicePath,"kx_ctrl")!=NULL) { //strncpy(ctrl_path,m_Detail->DevicePath,sizeof(ctrl_path)); HKEY key=SetupDiOpenDeviceInterfaceRegKey(hInfo,&data,0,KEY_ALL_ACCESS); if(key!=INVALID_HANDLE_VALUE) { DWORD type; type=REG_SZ; char tmp_str[256]; DWORD len; len=(DWORD)sizeof(tmp_str); if(RegQueryValueEx(key,"FriendlyName",NULL,&type,(unsigned char *)tmp_str,&len)==ERROR_SUCCESS) { strncpy(ctrl_name,tmp_str,sizeof(ctrl_name)); } RegCloseKey(key); } } else if(strstr(m_Detail->DevicePath,"kx_synth2")!=NULL) { //strncpy(synth2_path,m_Detail->DevicePath,sizeof(synth2_path)); HKEY key=SetupDiOpenDeviceInterfaceRegKey(hInfo,&data,0,KEY_ALL_ACCESS); if(key!=INVALID_HANDLE_VALUE) { DWORD type; type=REG_SZ; char tmp_str[256]; DWORD len; len=(DWORD)sizeof(tmp_str); if(RegQueryValueEx(key,"FriendlyName",NULL,&type,(unsigned char *)tmp_str,&len)==ERROR_SUCCESS) { strncpy(synth2_name,tmp_str,sizeof(synth2_name)); } RegCloseKey(key); } } else if(strstr(m_Detail->DevicePath,"kx_synth1")!=NULL) { //strncpy(synth_path,m_Detail->DevicePath,sizeof(synth_path)); HKEY key=SetupDiOpenDeviceInterfaceRegKey(hInfo,&data,0,KEY_ALL_ACCESS); if(key!=INVALID_HANDLE_VALUE) { DWORD type; type=REG_SZ; char tmp_str[256]; DWORD len; len=(DWORD)sizeof(tmp_str); if(RegQueryValueEx(key,"FriendlyName",NULL,&type,(unsigned char *)tmp_str,&len)==ERROR_SUCCESS) { strncpy(synth_name,tmp_str,sizeof(synth_name)); } RegCloseKey(key); } } } // if(SetupDiGetInterfaceDeviceDetail) delete m_Detail; } // if detail -- SetupDiGetInterfaceDeviceDetail } // while enum interfaces if(wave_path[0] && topo_path[0]) // have necessary interfaces: { if(device!=0) { device--; // clean-up: mixer_name[0]=0; topo_path[0]=0; wave_name[0]=0; wave23_name[0]=0; wave45_name[0]=0; wave67_name[0]=0; waveHQ_name[0]=0; wave_path[0]=0; synth_name[0]=0; synth2_name[0]=0; uart_name[0]=0; uart2_name[0]=0; ctrl_name[0]=0; continue; } // right device with correct # found: break; } } // enum dev info SetupDiDestroyDeviceInfoList(hInfo); if(wave_path[0]) { hWave = (void *)CreateFile( wave_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); if((HANDLE)hWave == INVALID_HANDLE_VALUE) { debug("iKX init(): error opening wave device [%x]\n",GetLastError()); strcpy(error_name,"error opening wave device"); return GetLastError(); } } if(topo_path[0]) { hTopo = (void *)CreateFile( topo_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); if((HANDLE)hTopo == INVALID_HANDLE_VALUE) { debug("iKX init() error opening topology device [%x]\n",GetLastError()); strcpy(error_name,"error opening topology device"); return GetLastError(); } } if(hTopo && hWave) { char card_name[KX_MAX_STRING]; get_string(KX_STR_CARD_NAME,card_name); if(!mixer_name[0]) sprintf(mixer_name,"kX Mixer %s 0/1",card_name); if(!wave_name[0]) sprintf(wave_name,"kX Wave %s 0/1",card_name); if(!wave23_name[0]) sprintf(wave23_name,"kX Wave %s 2/3",card_name); if(!wave45_name[0]) sprintf(wave45_name,"kX Wave %s 4/5",card_name); if(!wave67_name[0]) sprintf(wave67_name,"kX Wave %s 6/7",card_name); if(!waveHQ_name[0]) sprintf(waveHQ_name,"kX Wave %s HQ",card_name); if(!uart2_name[0]) sprintf(uart2_name,"kX Uart2 %s",card_name); if(!uart_name[0]) sprintf(uart_name,"kX Uart %s",card_name); if(!synth_name[0]) sprintf(synth_name,"kX Synth %s",card_name); if(!synth2_name[0]) sprintf(synth2_name,"kX Synth2 %s",card_name); if(!ctrl_name[0]) sprintf(ctrl_name,"kX Control %s",card_name); ret=init_winmm(); if(!ignore_winmm) { if(ret) { debug("iKX init() error initializing WinMM subsystem [%x]\n",GetLastError()); strcpy(error_name,"error initializing WinMM subsystem"); } } else { debug("iKX init(): ignore_winmm=1; btw, result was: %d [mixer_num=%d %d %d %d]\n",ret,mixer_handler[0],mixer_handler[1],mixer_handler[2],mixer_handler[3]); // if(mixer_handler[0]==-1) // mixer_num[0]=0; } } else { strcpy(error_name,"kX device not found"); } if(ret==0) { // set emulation is_10k2=0; if(get_dword(KX_DWORD_IS_10K2,(dword *)&is_10k2)) { debug("iKX init(): incorrect driver version\n"); strcpy(error_name,"incorrect driver version"); ret=-100; } // set device name if(get_string(KX_STR_CARD_NAME,device_name)) ret=-200; } return ret; }
// CDeviceSelect message handlers BOOL CDeviceSelect::OnInitDialog() { CDialogEx::OnInitDialog(); HDEVINFO hardwareDeviceInfo; PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = NULL; ULONG predictedLength = 0; ULONG requiredLength = 0, bytes=0; WCHAR szBda[13] = {0}; HANDLE hDevice = INVALID_HANDLE_VALUE; // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon m_numDevices = 0; if ((hardwareDeviceInfo = SetupDiGetClassDevs (NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT)) != INVALID_HANDLE_VALUE) { SP_DEVINFO_DATA DeviceInfoData; memset(&DeviceInfoData, 0, sizeof(DeviceInfoData)); DeviceInfoData.cbSize = sizeof(DeviceInfoData); WCHAR szService[80]; GUID guid; if (m_bWin8) guid = GUID_LONG_CHAR_SERVICE; else { guid.Data1 = (GUID_LONG_CHAR_SERVICE.Data4[4] ) + (GUID_LONG_CHAR_SERVICE.Data4[5] << 8) + (GUID_LONG_CHAR_SERVICE.Data4[6] << 16) + (GUID_LONG_CHAR_SERVICE.Data4[7] << 24); guid.Data2 = (GUID_LONG_CHAR_SERVICE.Data4[2] ) + (GUID_LONG_CHAR_SERVICE.Data4[3] << 8); guid.Data3 = (GUID_LONG_CHAR_SERVICE.Data4[0] ) + (GUID_LONG_CHAR_SERVICE.Data4[1] << 8); guid.Data4[0] = (GUID_LONG_CHAR_SERVICE.Data3 ) & 0xff; guid.Data4[1] = (GUID_LONG_CHAR_SERVICE.Data3 >> 8 ) & 0xff; guid.Data4[2] = (GUID_LONG_CHAR_SERVICE.Data2 ) & 0xff; guid.Data4[3] = (GUID_LONG_CHAR_SERVICE.Data2 >> 8 ) & 0xff; guid.Data4[4] = (GUID_LONG_CHAR_SERVICE.Data1 ) & 0xff; guid.Data4[5] = (GUID_LONG_CHAR_SERVICE.Data1 >> 8 ) & 0xff; guid.Data4[6] = (GUID_LONG_CHAR_SERVICE.Data1 >> 16) & 0xff; guid.Data4[7] = (GUID_LONG_CHAR_SERVICE.Data1 >> 24) & 0xff; } UuidToString(szService, 80, &guid); ods ("%S\n", szService); for (DWORD n = 0; SetupDiEnumDeviceInfo(hardwareDeviceInfo, n, &DeviceInfoData); n++) { DWORD dwBytes = 0; SetupDiGetDeviceInstanceId(hardwareDeviceInfo, &DeviceInfoData, NULL, 0, &dwBytes); PWSTR szInstanceId = new WCHAR [dwBytes]; if (szInstanceId) { if (SetupDiGetDeviceInstanceId(hardwareDeviceInfo, &DeviceInfoData, szInstanceId, dwBytes, &dwBytes)) { _wcsupr_s (szInstanceId, dwBytes); // if (wcsstr(szInstanceId, L"BTHENUM")) // { // OutputDebugStringW(szInstanceId); // OutputDebugStringW(L"\n"); if (wcsstr(szInstanceId, szService)) { OutputDebugStringW(szInstanceId); WCHAR buf[13]; wchar_t* pStart; wchar_t* pEnd; if (m_bWin8) { pStart = wcsrchr(szInstanceId, '_'); pEnd = wcsrchr(szInstanceId, '\\'); } else { pStart = wcsrchr(szInstanceId, '&'); pEnd = wcsrchr(szInstanceId, '_'); } if (pStart && pEnd) { *pEnd = 0; wcscpy_s(buf, pStart + 1); m_lbDevices.AddString(buf); m_numDevices++; } // } } } delete[] szInstanceId; } } SetupDiDestroyDeviceInfoList(hardwareDeviceInfo); }
bool cmtScanPorts(List<CmtPortInfo>& ports,uint32_t baudrate, uint32_t singleScanTimeout, uint32_t scanTries) { CmtPortInfo current = {0,0,0}; ports.clear(); // clear the list #ifdef _WIN32 HDEVINFO hDevInfo; SP_DEVINFO_DATA DeviceInfoData; DWORD i; // Create a HDEVINFO with all present devices. // GUID for Ports: 4D36E978-E325-11CE-BFC1-08002BE10318 GUID portGuid = {0x4D36E978,0xE325,0x11CE,{0xBF,0xC1,0x08,0x00,0x2B,0xE1,0x03,0x18}}; // "4D36E978-E325-11CE-BFC1-08002BE10318" hDevInfo = SetupDiGetClassDevs(&portGuid, 0, 0, DIGCF_PRESENT | DIGCF_PROFILE); if (hDevInfo == INVALID_HANDLE_VALUE) return false; // Enumerate through all devices in Set. DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); for (i=0;!abortScan && SetupDiEnumDeviceInfo(hDevInfo,i,&DeviceInfoData);++i) { DWORD DataT; char buffer[256]; bool isBT = false; // // Call function with null to begin with, // then use the returned buffer size // to Alloc the buffer. Keep calling until // success or an unknown failure. // #if 1 if (SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData, SPDRP_MFG, &DataT, (PBYTE)buffer, 256, NULL)) { // on failure, this is not an Xsens Device // on success, we need to check if the device is an Xsens Device //if (_strnicmp(buffer,"xsens",5)) // scan = true; //else if (!_strnicmp(buffer,"(Standard port types)",20)) continue; if (_strnicmp(buffer,"xsens",5)) // if this is NOT an xsens device, treat it as a BT device { isBT = true; if (_strnicmp(buffer,"WIDCOMM",7)) // if this is NOT a WIDCOMM (Ezureo / TDK stack), skip it continue; } } #endif // we found an Xsens Device, add its port nr to the list //Get the registry key which stores the ports settings HKEY hDeviceKey = SetupDiOpenDevRegKey(hDevInfo, &DeviceInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE); if (hDeviceKey != INVALID_HANDLE_VALUE) { //Read in the name of the port char pszPortName[256]; DWORD dwSize = 256; DWORD dwType = 0; if ((RegQueryValueEx(hDeviceKey, "PortName", NULL, &dwType, (LPBYTE) pszPortName, &dwSize) == ERROR_SUCCESS) && (dwType == REG_SZ)) { //If it looks like "COMX" then //add it to the array which will be returned int32_t nLen = (int32_t) strlen(pszPortName); if (nLen > 3) { if (_strnicmp(pszPortName, "COM", 3)) continue; int32_t nPort = atoi(&pszPortName[3]); if (nPort) { current.m_portNr = (uint16_t) nPort; if (isBT) current.m_baudrate = CMT_BAUD_RATE_460K8; else current.m_baudrate = baudrate; ports.append(current); } } } } //Close the key now that we are finished with it RegCloseKey(hDeviceKey); } // Cleanup SetupDiDestroyDeviceInfoList(hDevInfo); // Now sort the list by ascending port nr ports.sortAscending(); // Add the standard com ports 1 and 2 unless they are already in the list bool add1 = true, add2 = true; if ((ports.length() > 0) && (ports[0].m_portNr == 1)) add1 = false; if (ports.length() > 0) { if (ports[0].m_portNr == 2) add2 = false; else if (ports.length() > 1) if (ports[1].m_portNr == 2) add2 = false; } if (add1) { current.m_portNr = 1; current.m_baudrate = baudrate; ports.append(current); } if (add2) { current.m_portNr = 2; current.m_baudrate = baudrate; ports.append(current); } #else DIR *dir; struct dirent *entry; if ((dir = opendir("/dev/")) == NULL) return false; while ((entry = readdir(dir))) if (strncmp("ttyS", entry->d_name, 4) == 0 || strncmp("ttyUSB", entry->d_name, 6) == 0) { sprintf(current.m_portName, "/dev/%s", entry->d_name); current.m_baudrate = baudrate; ports.append(current); } closedir(dir); ports.sortAscending(); #endif // try to connect so we can detect if there really is an MT / XM attached unsigned p = 0; while (!abortScan && p < ports.length()) { if (cmtScanPort(ports[p],ports[p].m_baudrate,singleScanTimeout,scanTries)) ++p; else ports.remove(p); } if (abortScan) return abortScan = false; // Now sort the final list by ascending port nr ports.sortAscending(); abortScan = false; return true; }
bool CLCDConnectionLogitech::HIDInit() { if (GetConnectionState() != CONNECTED || m_pConnectedDevice->GetIndex() != LGLCD_DEVICE_BW) //LGLCD_DEVICE_FAMILY_KEYBOARD_G15) return false; // Logitech G15 int VendorID = 0x046d; int ProductID = 0xc222; //Use a series of API calls to find a HID with a specified Vendor IF and Product ID. HIDD_ATTRIBUTES Attributes; SP_DEVICE_INTERFACE_DATA devInfoData; bool LastDevice = FALSE; int MemberIndex = 0; LONG Result; DWORD Length = 0; PSP_DEVICE_INTERFACE_DETAIL_DATA detailData = NULL; HANDLE hDevInfo = NULL; GUID HidGuid; ULONG Required = 0; bool MyDeviceDetected = false; /* API function: HidD_GetHidGuid Get the GUID for all system HIDs. Returns: the GUID in HidGuid. */ HidD_GetHidGuid(&HidGuid); /* API function: SetupDiGetClassDevs Returns: a handle to a device information set for all installed devices. Requires: the GUID returned by GetHidGuid. */ hDevInfo = SetupDiGetClassDevs (&HidGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE); devInfoData.cbSize = sizeof(devInfoData); //Step through the available devices looking for the one we want. //Quit on detecting the desired device or checking all available devices without success. MemberIndex = 0; LastDevice = FALSE; do { /* API function: SetupDiEnumDeviceInterfaces On return, MyDeviceInterfaceData contains the handle to a SP_DEVICE_INTERFACE_DATA structure for a detected device. Requires: The DeviceInfoSet returned in SetupDiGetClassDevs. The HidGuid returned in GetHidGuid. An index to specify a device. */ Result = SetupDiEnumDeviceInterfaces (hDevInfo, 0, &HidGuid, MemberIndex, &devInfoData); if (Result != 0) { //A device has been detected, so get more information about it. /* API function: SetupDiGetDeviceInterfaceDetail Returns: an SP_DEVICE_INTERFACE_DETAIL_DATA structure containing information about a device. To retrieve the information, call this function twice. The first time returns the size of the structure in Length. The second time returns a pointer to the data in DeviceInfoSet. Requires: A DeviceInfoSet returned by SetupDiGetClassDevs The SP_DEVICE_INTERFACE_DATA structure returned by SetupDiEnumDeviceInterfaces. The final parameter is an optional pointer to an SP_DEV_INFO_DATA structure. This application doesn't retrieve or use the structure. If retrieving the structure, set MyDeviceInfoData.cbSize = length of MyDeviceInfoData. and pass the structure's address. */ //Get the Length value. //The call will return with a "buffer too small" error which can be ignored. Result = SetupDiGetDeviceInterfaceDetail (hDevInfo, &devInfoData, NULL, 0, &Length, NULL); //Allocate memory for the hDevInfo structure, using the returned Length. detailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(Length); //Set cbSize in the detailData structure. detailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); //Call the function again, this time passing it the returned buffer size. Result = SetupDiGetDeviceInterfaceDetail (hDevInfo, &devInfoData, detailData, Length, &Required, NULL); // Open a handle to the device. // To enable retrieving information about a system mouse or keyboard, // don't request Read or Write access for this handle. /* API function: CreateFile Returns: a handle that enables reading and writing to the device. Requires: The DevicePath in the detailData structure returned by SetupDiGetDeviceInterfaceDetail. */ m_hHIDDeviceHandle = CreateFile (detailData->DevicePath, FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); /* API function: HidD_GetAttributes Requests information from the device. Requires: the handle returned by CreateFile. Returns: a HIDD_ATTRIBUTES structure containing the Vendor ID, Product ID, and Product Version Number. Use this information to decide if the detected device is the one we're looking for. */ //Set the Size to the number of bytes in the structure. Attributes.Size = sizeof(Attributes); Result = HidD_GetAttributes (m_hHIDDeviceHandle, &Attributes); //Is it the desired device? MyDeviceDetected = FALSE; if (Attributes.VendorID == VendorID) { if (Attributes.ProductID == ProductID) { //Both the Vendor ID and Product ID match. MyDeviceDetected = TRUE; } else CloseHandle(m_hHIDDeviceHandle); } else CloseHandle(m_hHIDDeviceHandle); //Free the memory used by the detailData structure (no longer needed). free(detailData); } else LastDevice = TRUE; MemberIndex = MemberIndex + 1; } //do while ((LastDevice == FALSE) && (MyDeviceDetected == FALSE)); if (MyDeviceDetected) { PHIDP_PREPARSED_DATA PreparsedData; HidD_GetPreparsedData (m_hHIDDeviceHandle, &PreparsedData); HidP_GetCaps (PreparsedData, &m_HIDCapabilities); HidD_FreePreparsedData(PreparsedData); } //Free the memory reserved for hDevInfo by SetupDiClassDevs. SetupDiDestroyDeviceInfoList(hDevInfo); return MyDeviceDetected; }
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, ¤tInterface); i++) { DWORD requiredSize = 0; PSP_DEVICE_INTERFACE_DETAIL_DATA details; SetupDiGetDeviceInterfaceDetail(usbDevices, ¤tInterface, NULL, 0, &requiredSize, NULL); details = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(requiredSize); details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); if(!SetupDiGetDeviceInterfaceDetail(usbDevices, ¤tInterface, 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, ¤tInterface); i++) { DWORD requiredSize = 0; PSP_DEVICE_INTERFACE_DETAIL_DATA details; SetupDiGetDeviceInterfaceDetail(usbDevices, ¤tInterface, NULL, 0, &requiredSize, NULL); details = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(requiredSize); details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); if(!SetupDiGetDeviceInterfaceDetail(usbDevices, ¤tInterface, 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; }
int serial_find(const char* prefix, int (*check)(const char* port, void* data), void* data) { GUID *guidDev = (GUID *) &GUID_CLASS_COMPORT; HDEVINFO hDevInfo = INVALID_HANDLE_VALUE; SP_DEVICE_INTERFACE_DETAIL_DATA *pDetData = NULL; SP_DEVICE_INTERFACE_DATA ifcData; DWORD dwDetDataSize; int rc = -1; BOOL bOk; DWORD i; hDevInfo = SetupDiGetClassDevs( guidDev, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE ); if(hDevInfo == INVALID_HANDLE_VALUE) { printf("error: SetupDiGetClassDevs failed. (err=%lx)\n", GetLastError()); goto done; } // Enumerate the serial ports dwDetDataSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + 256; pDetData = (SP_DEVICE_INTERFACE_DETAIL_DATA *)malloc(dwDetDataSize); ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); pDetData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); for (i = 0, bOk = TRUE; bOk; ++i) { // get the next device bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, i, &ifcData); if (bOk) { // get the device details SP_DEVINFO_DATA devdata = {sizeof(SP_DEVINFO_DATA)}; bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifcData, pDetData, dwDetDataSize, NULL, &devdata); if (bOk) { TCHAR fname[256], desc[256]; // get some additional info BOOL bSuccess = SetupDiGetDeviceRegistryProperty(hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname, sizeof(fname), NULL) && SetupDiGetDeviceRegistryProperty(hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL, (PBYTE)desc, sizeof(desc), NULL); if (bSuccess) { char *comx, *p; //printf("Device path: %s\n", pDetData->DevicePath); //printf("Friendly name: %s\n", fname); //printf("Description: %s\n", desc); if ((comx = strchr(fname, '(')) != NULL) ++comx; else comx = fname; if ((p = strchr(comx, ')')) != NULL) *p = '\0'; if ((*check)(comx, data) == 0) { rc = 0; goto done; } } } else { printf("error: SetupDiGetDeviceInterfaceDetail failed. (err=%lx)\n", GetLastError()); return 1; } } else { DWORD err = GetLastError(); if (err != ERROR_NO_MORE_ITEMS) { printf("error: SetupDiEnumDeviceInterfaces failed. (err=%lx)\n", err); goto done; } } } done: if (pDetData != NULL) free(pDetData); if (hDevInfo != INVALID_HANDLE_VALUE) SetupDiDestroyDeviceInfoList(hDevInfo); return rc; }
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. // // 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); } 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; }
bool SarClient::openControlDevice() { HDEVINFO devinfo; SP_DEVICE_INTERFACE_DATA interfaceData; PSP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetail; DWORD requiredSize; interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); devinfo = SetupDiGetClassDevs( &GUID_DEVINTERFACE_SYNCHRONOUSAUDIOROUTER, nullptr, nullptr, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); if (devinfo == INVALID_HANDLE_VALUE) { return false; } if (!SetupDiEnumDeviceInterfaces(devinfo, NULL, &GUID_DEVINTERFACE_SYNCHRONOUSAUDIOROUTER, 0, &interfaceData)) { return false; } SetLastError(0); SetupDiGetDeviceInterfaceDetail( devinfo, &interfaceData, nullptr, 0, &requiredSize, nullptr); if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { return false; } interfaceDetail = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(requiredSize); interfaceDetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); if (!SetupDiGetDeviceInterfaceDetail( devinfo, &interfaceData, interfaceDetail, requiredSize, nullptr, nullptr)) { free(interfaceDetail); return false; } _device = CreateFile(interfaceDetail->DevicePath, GENERIC_ALL, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr); if (_device == INVALID_HANDLE_VALUE) { free(interfaceDetail); return false; } _completionPort = CreateIoCompletionPort(_device, nullptr, 0, 0); if (!_completionPort) { CloseHandle(_device); _device = nullptr; free(interfaceDetail); return false; } _notificationHandles.clear(); _notificationHandles.resize(_driverConfig.endpoints.size()); free(interfaceDetail); return true; }
// // If succeeded, returns the device file of the LANSCSI Bus Enumerator // If failed, return INVALID_HANDLE_VALUE // static HANDLE OpenBusInterface(VOID) { BOOL fSuccess = FALSE; DWORD err = ERROR_SUCCESS; HANDLE hDevice = INVALID_HANDLE_VALUE; HDEVINFO hDevInfoSet = INVALID_HANDLE_VALUE; SP_INTERFACE_DEVICE_DATA devIntfData = {0}; PSP_INTERFACE_DEVICE_DETAIL_DATA devIntfDetailData = NULL; ULONG predictedLength = 0; ULONG requiredLength = 0; hDevInfoSet = SetupDiGetClassDevs ( (LPGUID)&GUID_NDAS_BUS_ENUMERATOR_INTERFACE_CLASS, NULL, // Define no enumerator (global) NULL, // Define no (DIGCF_PRESENT | // Only Devices present DIGCF_INTERFACEDEVICE)); // Function class devices. if (INVALID_HANDLE_VALUE == hDevInfoSet) { DebugPrintErrEx(_T("OpenBusInterface: SetupDiGetClassDevs failed: ")); goto cleanup; } devIntfData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA); fSuccess = SetupDiEnumDeviceInterfaces ( hDevInfoSet, 0, // No care about specific PDOs (LPGUID)&GUID_NDAS_BUS_ENUMERATOR_INTERFACE_CLASS, 0, // &devIntfData); if (!fSuccess) { DebugPrintErrEx(_T("OpenBusInterface: SetupDiEnumDeviceInterfaces failed: ")); if (ERROR_NO_MORE_ITEMS == GetLastError()) { DebugPrint(1, _T("OpenBusInterface: Interface") _T(" GUID_NDAS_BUS_ENUMERATOR_INTERFACE_CLASS is not registered.\n")); } goto cleanup; } fSuccess = SetupDiGetInterfaceDeviceDetail ( hDevInfoSet, &devIntfData, NULL, // probing so no output buffer yet 0, // probing so output buffer length of zero &requiredLength, NULL // not interested in the specific dev-node ); if (!fSuccess && ERROR_INSUFFICIENT_BUFFER != GetLastError()) { DebugPrintErrEx(_T("OpenBusInterface: SetupDiGetInterfaceDeviceDetail failed: ")); goto cleanup; } predictedLength = requiredLength; devIntfDetailData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, predictedLength); devIntfDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA); fSuccess = SetupDiGetInterfaceDeviceDetail( hDevInfoSet, &devIntfData, devIntfDetailData, predictedLength, &requiredLength, NULL); if (!fSuccess) { DebugPrintErrEx(_T("OpenBusInterface: SetupDiGetInterfaceDeviceDetail failed: ")); goto cleanup; } DebugPrint(3, _T("OpenBusInterface: Opening %s\n"), devIntfDetailData->DevicePath); hDevice = CreateFile ( devIntfDetailData->DevicePath, GENERIC_READ | GENERIC_WRITE, 0, // FILE_SHARE_READ | FILE_SHARE_WRITE NULL, // no SECURITY_ATTRIBUTES structure OPEN_EXISTING, // No special create flags 0, // No special attributes NULL); // No template file if (INVALID_HANDLE_VALUE == hDevice) { DebugPrintErrEx(_T("OpenBusInterface: Device not ready: ")); goto cleanup; } DebugPrint(3, _T("OpenBusInterface: Device file %s opened successfully.\n"), devIntfDetailData->DevicePath); cleanup: err = GetLastError(); if (INVALID_HANDLE_VALUE != hDevInfoSet) { SetupDiDestroyDeviceInfoList(hDevInfoSet); } if (NULL != devIntfDetailData) { HeapFree(GetProcessHeap(), 0, devIntfDetailData); } SetLastError(err); return hDevice; }
void PCUtils::GetPhysicalDisks( std::vector<PCUtils::DISK_DRIVE_INFORMATION>& OutVector ) { #ifdef _WIN32 unsigned i; DWORD dwSize, dwPropertyRegDataType = SPDRP_PHYSICAL_DEVICE_OBJECT_NAME; CONFIGRET r; HDEVINFO hDevInfo; SP_DEVINFO_DATA DeviceInfoData; SP_DEVICE_INTERFACE_DATA interfaceData; TCHAR szDeviceInstanceID [MAX_DEVICE_ID_LEN]; TCHAR szDesc[1024]; GUID HddClass; HddClass = GUID_DEVINTERFACE_DISK;//GUID_DEVCLASS_DISKDRIVE; // List all connected disk drives hDevInfo = SetupDiGetClassDevs (&HddClass, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (hDevInfo == INVALID_HANDLE_VALUE) return; // Find the ones that are driverless for (i = 0; ; i++) { DeviceInfoData.cbSize = sizeof (DeviceInfoData); // Get the next device info if (!SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData)) break; interfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA); // Get the next device interface if (!SetupDiEnumInterfaceDevice(hDevInfo, NULL, &HddClass, i, &interfaceData)) { break; } // Get the device ID r = CM_Get_Device_ID(DeviceInfoData.DevInst, szDeviceInstanceID , MAX_PATH, 0); if (r != CR_SUCCESS) continue; // To add to the vector DISK_DRIVE_INFORMATION AddToVector; DWORD requiredSize = 0; // Get the path SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, NULL, NULL, &requiredSize, NULL); SP_INTERFACE_DEVICE_DETAIL_DATA* data = (SP_INTERFACE_DEVICE_DETAIL_DATA*) malloc(requiredSize); data->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA); if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, data, requiredSize, NULL, NULL)) { continue; } AddToVector.Path = nowide::convert(std::wstring(data->DevicePath)); qDebug("Disk path: %s", AddToVector.Path.c_str()); // Friendly name (e.g. SanDisk Cruzer USB...) SetupDiGetDeviceRegistryProperty (hDevInfo, &DeviceInfoData, SPDRP_FRIENDLYNAME, &dwPropertyRegDataType, (BYTE*)szDesc, sizeof(szDesc), // The size, in bytes &dwSize); AddToVector.FriendlyName = nowide::convert(std::wstring((TCHAR*)szDesc)); qDebug("Friendly name: %s", AddToVector.FriendlyName.c_str()); OutVector.push_back(AddToVector); delete data; } #else DIR *dir = NULL; dirent *ent = NULL; dir = opendir("/dev/"); if (dir != NULL) { // Read the shit while ((ent = readdir(dir)) != NULL) { // Check the directory name, and if it starts with "disk" then keep it! QRegExp exp("disk*"); exp.setPatternSyntax(QRegExp::Wildcard); exp.setCaseSensitivity(Qt::CaseInsensitive); if (exp.exactMatch(ent->d_name)) { DISK_DRIVE_INFORMATION curdir; std::ostringstream ss; ss << "/dev/r"; ss << ent->d_name; std::string diskPath = ss.str(); curdir.Path = diskPath; int device; if ((device = open(diskPath.c_str(), O_RDONLY)) > 0) { #ifdef __linux hd_driveid hd; if (!ioctl(device, HDIO_GET_IDENTITY, &hd)) { curdir.FriendlyName = hd.model; } #elif defined __APPLE__ curdir.FriendlyName = ent->d_name; #endif OutVector.push_back(curdir); } } } } if (dir) closedir(dir); if (ent) delete ent; #endif }
static unsigned int GetSSAGDriverVersion() { // check to see if the SSAG driver is v2 ("1.2.0.0") or v4 ("3.0.0.0") Debug.AddLine("Checking SSAG driver version"); bool found = false; unsigned int driverVersion = 2; // assume v2 HDEVINFO h = SetupDiGetClassDevs(NULL, L"USB", NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT); if (h != INVALID_HANDLE_VALUE) { DWORD idx = 0; SP_DEVINFO_DATA data; memset(&data, 0, sizeof(data)); data.cbSize = sizeof(data); while (SetupDiEnumDeviceInfo(h, idx, &data)) { #if DONE_SUPPORTING_XP WCHAR buf[4096]; if (GetDiPropStr(h, &data, DEVPKEY_Device_InstanceId, buf, sizeof(buf)) && (wcsncmp(buf, L"USB\\VID_1856&PID_0012\\", 22) == 0) || (wcsncmp(buf, L"USB\\VID_1856&PID_0011\\", 22) == 0)) { Debug.AddLine(wxString::Format("Found SSAG device %s", buf)); if (GetDiPropStr(h, &data, DEVPKEY_Device_DriverVersion, buf, sizeof(buf))) { Debug.AddLine(wxString::Format("SSAG driver version is %s", wxString(buf))); int v; if (swscanf(buf, L"%d", &v) == 1 && v >= 3) { driverVersion = 4; } } found = true; break; } #else WCHAR buf[4096]; DWORD size = sizeof(buf); DWORD proptype; if (SetupDiGetDeviceRegistryProperty(h, &data, SPDRP_HARDWAREID, &proptype, (PBYTE)&buf[0], size, &size) && (wcsncmp(buf, L"USB\\VID_1856&PID_0012", 21) == 0 || wcsncmp(buf, L"USB\\VID_1856&PID_0011", 21) == 0)) { Debug.AddLine(wxString::Format("Found SSAG device %s", buf)); wxString ver = GetDiPropStr(h, &data, "DriverVersion"); if (ver.Length()) { Debug.AddLine(wxString::Format("SSAG driver version is %s", ver)); int v; if (wxSscanf(ver, "%d", &v) == 1 && v >= 3) { driverVersion = 4; } } found = true; break; } #endif // XP ++idx; } SetupDiDestroyDeviceInfoList(h); } if (!found) Debug.AddLine("No SSAG device was found"); return driverVersion; }
void * _ykusb_open_device(int vendor_id, int product_id) { 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 && devInfo.ProductID == product_id) { ret_handle = m_handle; free (pi); goto done; } } } CloseHandle (m_handle); } free (pi); if (!rc) break; } yk_errno = YK_ENOKEY; done: SetupDiDestroyDeviceInfoList(hi); return ret_handle; }
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); }
unsigned int USBDeviceFactory_DiscoverDevices( LPSKYETEK_DEVICE** lpDevices ) { GUID hidGuid; HDEVINFO deviceInfo; BOOL isSuccess = FALSE; unsigned long bytes = 0; SP_INTERFACE_DEVICE_DATA deviceData; PSP_INTERFACE_DEVICE_DETAIL_DATA deviceInterfaceData = 0; unsigned int ix, deviceCount = 0; size_t size = 0; SKYETEK_STATUS status; if((lpDevices == NULL) || (*lpDevices != NULL)) return 0; g_usbDevCount = 0; HidD_GetHidGuid (&hidGuid); deviceInfo = SetupDiGetClassDevs ( &hidGuid, 0, 0, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE )); if ( deviceInfo == INVALID_HANDLE_VALUE ) return 0; *lpDevices = (LPSKYETEK_DEVICE*)malloc(20 * sizeof(LPSKYETEK_DEVICE)); memset(*lpDevices,0,(20*sizeof(LPSKYETEK_DEVICE))); size = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA); for ( ix = 0; ix < 20; ix++ ) { memset( &deviceData, 0, sizeof(SP_INTERFACE_DEVICE_DATA) ); deviceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA); isSuccess = SetupDiEnumDeviceInterfaces ( deviceInfo, 0, &hidGuid, ix, &deviceData); if ( !isSuccess ) { if ( ERROR_NO_MORE_ITEMS == GetLastError() ) break; else continue; } SetupDiGetInterfaceDeviceDetail( deviceInfo, &deviceData, 0, 0, &bytes, 0); deviceInterfaceData = (PSP_INTERFACE_DEVICE_DETAIL_DATA)malloc(bytes * sizeof(BYTE)); if ( !deviceInterfaceData ) { SetupDiDestroyDeviceInfoList( deviceInfo ); return deviceCount; } memset( deviceInterfaceData, 0, bytes ); deviceInterfaceData->cbSize = size; isSuccess = SetupDiGetInterfaceDeviceDetail( deviceInfo, &deviceData, deviceInterfaceData, bytes, &bytes, 0); if ( !isSuccess ) { free(deviceInterfaceData); SetupDiDestroyDeviceInfoList( deviceInfo ); return deviceCount; } if((_tcsstr(deviceInterfaceData->DevicePath, _T("vid_afef")) != NULL) && (_tcsstr(deviceInterfaceData->DevicePath, _T("pid_0f01")) != NULL)) { /*printf("DevicePath = %s\r\n", deviceInterfaceData->DevicePath);*/ status = USBDeviceFactory_CreateDevice(deviceInterfaceData->DevicePath, &((*lpDevices)[deviceCount])); if( status != SKYETEK_SUCCESS ) { free(deviceInterfaceData); continue; } deviceCount++; } free(deviceInterfaceData); } return deviceCount; }
XnStatus xnUSBOpenDeviceImpl(const XnChar* strDevicePath, XN_USB_DEV_HANDLE* pDevHandlePtr) { // Local variables XnStatus nRetVal = XN_STATUS_OK; LPCGUID pInterfaceGuid = NULL; XN_USB_DEV_HANDLE pDevHandle = NULL; ULONG nNumberDevices = 0; HDEVINFO hDevInfo = NULL; BOOLEAN bDone = FALSE; SP_DEVICE_INTERFACE_DATA devInterfaceData; PUSB_DEVICE_DESCRIPTOR pUsbDeviceInst = NULL; PUSB_DEVICE_DESCRIPTOR* ppUsbDevices = &pUsbDeviceInst; PUSB_DEVICE_DESCRIPTOR pTempDevDesc = NULL; ULONG nIdx = 0; HANDLE hSelectedDevice = INVALID_HANDLE_VALUE; PSUSBDRV_DRIVER_VERSION UsbDriverVersion; PSUSBDRV_INTERFACE_PROPERTY pInterfaceProp; // Validate xnUSB XN_VALIDATE_USB_INIT(); // Validate the input/output pointers XN_VALIDATE_OUTPUT_PTR(pDevHandlePtr); // Allocate a new xnUSB Device handle XN_VALIDATE_ALIGNED_CALLOC(*pDevHandlePtr, XnUSBDeviceHandle, 1, XN_DEFAULT_MEM_ALIGN); pDevHandle = *pDevHandlePtr; // Get Device Path 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... XN_ALIGNED_FREE_AND_NULL(pDevHandle); return (XN_STATUS_USB_DRIVER_NOT_FOUND); } // Guess how much devices we're going to have. If it's too little, we'll realloc it soon. nNumberDevices = 4; // Scan the hardware for any devices that are attached to our driver. Stop only after we have successfully opened a device. devInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); nIdx = 0; bDone = FALSE; while (!bDone) { // Allocate enough memory for all the devices that are attached to the driver nNumberDevices *= 2; if (*ppUsbDevices) { pTempDevDesc = (USB_DEVICE_DESCRIPTOR*)realloc(*ppUsbDevices, (nNumberDevices * sizeof (USB_DEVICE_DESCRIPTOR))); if(pTempDevDesc) { // We have enough memory! *ppUsbDevices = pTempDevDesc; pTempDevDesc = NULL; } else { // Out of memory... realloc failed... free(*ppUsbDevices); *ppUsbDevices = NULL; } } else { *ppUsbDevices = (USB_DEVICE_DESCRIPTOR*)calloc (nNumberDevices, sizeof (USB_DEVICE_DESCRIPTOR)); } // Make sure we have found some devices if (NULL == *ppUsbDevices) { SetupDiDestroyDeviceInfoList(hDevInfo); XN_ALIGNED_FREE_AND_NULL(pDevHandle); return (XN_STATUS_USB_DEVICE_GETINFO_FAILED); } pUsbDeviceInst = *ppUsbDevices + nIdx; // Scan all the devices that are attached to the driver. Stop when one of them open successfully. for (; nIdx < nNumberDevices; nIdx++) { // Get information about the device if (SetupDiEnumDeviceInterfaces (hDevInfo, 0, pInterfaceGuid, nIdx, &devInterfaceData)) { // Try to open this device hSelectedDevice = xnUSBOpenOneDevice(hDevInfo, &devInterfaceData, pDevHandle->cpDeviceName, strDevicePath); if (hSelectedDevice != INVALID_HANDLE_VALUE) { // Success! We have a valid device handle. bDone = TRUE; break; } } else { // Did we reach the end? if (ERROR_NO_MORE_ITEMS == GetLastError()) { // Yup... and we didn't find any devices... bDone = TRUE; break; } } } } // Save the number of devices nNumberDevices = nIdx; // Cleanup memory SetupDiDestroyDeviceInfoList (hDevInfo); free (*ppUsbDevices); // Do we have a valid device? if (hSelectedDevice == INVALID_HANDLE_VALUE) { // Nope... XN_ALIGNED_FREE_AND_NULL(pDevHandle); return (XN_STATUS_USB_DEVICE_NOT_FOUND); } // Save the device handle pDevHandle->hUSBDevHandle = hSelectedDevice; // Get the device speed nRetVal = xnUSBGetDeviceSpeedInternal(pDevHandle, &pDevHandle->nDevSpeed); if (nRetVal != XN_STATUS_OK) { XN_ALIGNED_FREE_AND_NULL(pDevHandle); return (nRetVal); } // Get the driver version nRetVal = xnUSBGetDriverVersion(pDevHandle, &UsbDriverVersion); if (nRetVal != XN_STATUS_OK) { XN_ALIGNED_FREE_AND_NULL(pDevHandle); return (nRetVal); } xnLogVerbose(XN_MASK_USB, "USB Driver Version is: %d.%d.%d.%d", UsbDriverVersion.nMajor, UsbDriverVersion.nMinor, UsbDriverVersion.nMaintenance, UsbDriverVersion.nBuild); // Mark the device handle as valid pDevHandle->bValid = TRUE; // Read the current alt-if settings nRetVal = xnUSBGetInterface(pDevHandle, &pInterfaceProp.nIF, &pInterfaceProp.nAltIF); if (nRetVal != XN_STATUS_OK) { XN_ALIGNED_FREE_AND_NULL(pDevHandle); return (nRetVal); } pDevHandle->nAltInterface = pInterfaceProp.nAltIF; xnLogVerbose(XN_MASK_USB, "USB Driver Current Alt Setting is: %d", pDevHandle->nAltInterface); // All is good... return (XN_STATUS_OK); }
int InstallPnPDriver( IN HWND hWnd, PTSTR HardwareId, PTSTR Inf, BOOL DelayInstall, BOOL ForceUpdateDriver ) { DWORD Err = NO_ERROR; SP_DEVINFO_DATA DeviceInfoData; HDEVINFO DeviceInfoSet = INVALID_HANDLE_VALUE; TCHAR DeviceIds[REGSTR_VAL_MAX_HCID_LEN]; DWORD memberIndex; PTSTR singleDeviceId; DeviceInfoSet = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES); if (DeviceInfoSet == INVALID_HANDLE_VALUE) { Err = GetLastError(); goto clean; } memberIndex = 0; DeviceInfoData.cbSize = sizeof(DeviceInfoData); while (SetupDiEnumDeviceInfo(DeviceInfoSet, memberIndex++, &DeviceInfoData)) { if (SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &DeviceInfoData, SPDRP_HARDWAREID, NULL, (PBYTE)DeviceIds, sizeof(DeviceIds), NULL)) { for (singleDeviceId = DeviceIds; *singleDeviceId; singleDeviceId += lstrlen(singleDeviceId) + 1) { if (!lstrcmpi(HardwareId, singleDeviceId)) { // // Found a match. Check if it is a phantom if PhantomOnly is // TRUE // if (InstallInfOnDevice(hWnd, DeviceInfoSet, &DeviceInfoData, Inf, DelayInstall) != NO_ERROR) { MessageBox(hWnd, "Failed to install drivers on one of the devices", "Install Error", MB_OK); } if (ForceUpdateDriver) { BOOL reboot; if (!UpdateDriverForPlugAndPlayDevices( hWnd, HardwareId, Inf, INSTALLFLAG_FORCE, &reboot)) MessageBox(hWnd, "Failed to force update driver for one of the devices", "Install Error", MB_OK); } } } } } clean: if (DeviceInfoSet != INVALID_HANDLE_VALUE) { SetupDiDestroyDeviceInfoList(DeviceInfoSet); } if (Err == NO_ERROR) { return 0; } return 1; }
HRESULT CNdasServiceDeviceEventHandler::pEnumerateNdasStoragePorts() { HRESULT hr = S_OK; HDEVINFO hDevInfoSet = SetupDiGetClassDevs( &GUID_DEVINTERFACE_STORAGEPORT, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); if (static_cast<HDEVINFO>(INVALID_HANDLE_VALUE) == hDevInfoSet) { hr = HRESULT_FROM_WIN32(GetLastError()); XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_ERROR, "SetupDiCreateDeviceInfoList failed, hr=%x\n", hr); return hr; } for (DWORD index = 0; ; ++index) { SP_DEVICE_INTERFACE_DATA deviceInterfaceData = { sizeof(SP_DEVICE_INTERFACE_DATA) }; BOOL success = SetupDiEnumDeviceInterfaces( hDevInfoSet, NULL, &GUID_DEVINTERFACE_STORAGEPORT, index, &deviceInterfaceData); if (!success) { if (ERROR_NO_MORE_ITEMS != GetLastError()) { hr = HRESULT_FROM_WIN32(GetLastError()); XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_ERROR, "SetupDiEnumDeviceInterfaces failed, hr=%X\n", hr); } break; } DWORD requiredSize = 0; success = SetupDiGetDeviceInterfaceDetail( hDevInfoSet, &deviceInterfaceData, NULL, 0, &requiredSize, NULL); if (success || ERROR_INSUFFICIENT_BUFFER != GetLastError()) { if (success) { XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_ERROR, "SetupDiGetDeviceInterfaceDetail failed, no interface details\n"); } else { XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_ERROR, "SetupDiGetDeviceInterfaceDetail failed, error=0x%X\n", GetLastError()); } continue; } PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA>(malloc(requiredSize)); if (NULL == deviceInterfaceDetailData) { XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_ERROR, "malloc failed, bytes=%d\n", requiredSize); continue; } ZeroMemory(deviceInterfaceDetailData, requiredSize); deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); success = SetupDiGetDeviceInterfaceDetail( hDevInfoSet, &deviceInterfaceData, deviceInterfaceDetailData, requiredSize, NULL, NULL); if (!success) { XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_ERROR, "SetupDiGetDeviceInterfaceDetail failed, error=0x%X\n", GetLastError()); free(deviceInterfaceDetailData); continue; } XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_INFORMATION, "StoragePort found, device=%ls\n", deviceInterfaceDetailData->DevicePath); HANDLE hDevice = CreateFile( deviceInterfaceDetailData->DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_DEVICE, NULL); if (INVALID_HANDLE_VALUE == hDevice) { XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_ERROR, "CreateFile failed, device=%ls, error=0x%X\n", deviceInterfaceDetailData->DevicePath, GetLastError()); free(deviceInterfaceDetailData); continue; } DWORD slotNo = 0; HRESULT hr2 = pGetNdasSlotNumberFromDeviceHandle(hDevice, &slotNo); if (S_OK != hr2) { XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_WARNING, "StoragePort is not an NDAS Storage Port, hr=%x\n", hr2); XTLVERIFY( CloseHandle(hDevice) ); free(deviceInterfaceDetailData); continue; } XTLTRACE2(NDASSVC_PNP, TRACE_LEVEL_INFORMATION, "NdasSlotNumber=%d\n", slotNo); // // As the ownership of the handler goes to the vector, // do not close the device handle here // AddDeviceNotificationHandle( hDevice, CDeviceHandleNotifyData( DNT_STORAGE_PORT, slotNo, deviceInterfaceDetailData->DevicePath)); XTLVERIFY( CloseHandle(hDevice) ); free(deviceInterfaceDetailData); } XTLVERIFY( SetupDiDestroyDeviceInfoList(hDevInfoSet) ); return hr; }