vector WmiQuery::GetDevicesForAdapters()

in library/src/WmiQuery.cpp [119:193]


vector<Device> WmiQuery::GetDevicesForAdapters(const map<int64_t, Adapter>& adapters)
{
	// If we don't have any adapters then don't query WMI
	if (adapters.empty())
	{
		LOG(L"Empty adapter list provided, skipping WMI query");
		return {};
	}
	
	// Gather the unique PnP hardware IDs from the DirectX adapters for use in our WQL query string
	set<wstring> hardwareIDs;
	for (auto const& adapter : adapters) {
		hardwareIDs.insert(FormatHardwareID(adapter.second.HardwareID));
	}
	
	// Build the WQL query string to retrieve the PnP devices associated with the adapters
	wstring query = L"SELECT * FROM Win32_PnPEntity WHERE Present = TRUE AND (";
	int index = 0;
	int last = hardwareIDs.size() - 1;
	for (auto const& id : hardwareIDs)
	{
		query += L"DeviceID LIKE \"" + id + L"\"" + ((index < last) ? L" OR " : L"");
		index++;
	}
	query += L")";
	
	// Log the query string
	LOG(L"Executing WQL query: {}", query);
	
	// Execute the query
	com_ptr<IEnumWbemClassObject> enumerator;
	auto error = CheckHresult(wbemServices->ExecQuery(
		wil::make_bstr(L"WQL").get(),
		wil::make_bstr(query.c_str()).get(),
		0,
		nullptr,
		enumerator.put()
	));
	if (error) {
		throw error.Wrap(L"WQL query execution failed");
	}
	
	// Iterate over the retrieved PnP devices and match them to their corresponding DirectX adapters
	vector<Device> devices;
	for (int index = 0; ; index++)
	{
		// Retrieve the device for the current loop iteration
		ULONG numReturned = 0;
		com_ptr<IWbemClassObject> device;
		auto error = CheckHresult(enumerator->Next(WBEM_INFINITE, 1, device.put(), &numReturned));
		if (error) {
			throw error.Wrap(L"enumerating PnP devices failed");
		}
		if (numReturned == 0) {
			break;
		}
		
		// Extract the details for the device and determine whether it matches any of our adapters
		Device details = this->ExtractDeviceDetails(device);
		auto matchingAdapter = adapters.find(details.DeviceAdapter.InstanceLuid);
		if (matchingAdapter != adapters.end())
		{
			// Log the match
			LOG(L"Matched adapter LUID {} to PnP device {}", details.DeviceAdapter.InstanceLuid, details.ID);
			
			// Replace the device's adapter details with the matching adapter
			details.DeviceAdapter = matchingAdapter->second;
			
			// Include the device in our results
			devices.push_back(details);
		}
	}
	
	return devices;
}