int getPortPathFromSerial()

in src/main/c/Windows/WindowsHelperFunctions.c [302:345]


int getPortPathFromSerial(wchar_t* portPath, int portPathLength, const char* ftdiSerialNumber)
{
	// Search for this port in all FTDI enumerated ports
	int found = 0;
	HKEY key, paramKey;
	DWORD maxSubkeySize;
	if ((RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Enum\\FTDIBUS", 0, KEY_READ, &key) == ERROR_SUCCESS) &&
			(RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL, &maxSubkeySize, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS))
	{
		maxSubkeySize += 32;
		DWORD index = 0, subkeySize = maxSubkeySize;
		wchar_t *subkey = (wchar_t*)malloc(maxSubkeySize * sizeof(wchar_t));
		while (subkey && (RegEnumKeyExW(key, index++, subkey, &subkeySize, NULL, NULL, NULL, NULL) == ERROR_SUCCESS))
		{
			// Convert this string from wchar* to char*
			size_t convertedSize;
			subkeySize = maxSubkeySize;
			if ((wcstombs_s(&convertedSize, NULL, 0, subkey, 0) == 0) && (convertedSize < 255))
			{
				char *subkeyString = (char*)malloc(convertedSize);
				if (subkeyString && (wcstombs_s(NULL, subkeyString, convertedSize, subkey, convertedSize - 1) == 0))
				{
					// Determine if this device matches the specified serial number
					if (ftdiSerialNumber && strstr(subkeyString, ftdiSerialNumber) && (wcscat_s(subkey, maxSubkeySize, L"\\0000\\Device Parameters") == 0))
					{
						DWORD portNameSize = portPathLength;
						if ((RegOpenKeyExW(key, subkey, 0, KEY_QUERY_VALUE, &paramKey) == ERROR_SUCCESS) &&
								(RegQueryValueExW(paramKey, L"PortName", NULL, NULL, (LPBYTE)portPath, &portNameSize) == ERROR_SUCCESS))
						{
							found = 1;
							RegCloseKey(paramKey);
						}
					}
				}
				if (subkeyString)
					free(subkeyString);
			}
		}
		RegCloseKey(key);
		if (subkey)
			free(subkey);
	}
	return found;
}