废话不多说,在此记录一个实时检测串口链接状态的操作。
struct SerialPortInfo
{
std::string portName;
std::string description;
};
std::string wstringToString(const std::wstring& wstr)
{
if (wstr.empty())
{
return std::string();
}
int size = WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string ret = std::string(size, 0);
WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), &ret[0], size, NULL, NULL); // CP_UTF8
return ret;
}
bool enumDetailsSerialPorts(vector<SerialPortInfo>& portInfoList)
{
bool bRet = false;
std::string strPortName;
HANDLE m_handle;
TCHAR portName[2048] = { 0 };
SerialPortInfo m_serialPortInfo;
for (int i = 1; i <= 255; i++)
{
bRet = false;
_sntprintf(portName, sizeof(portName), _T("COM%d"), i);
m_handle = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (m_handle == INVALID_HANDLE_VALUE)
{
if (ERROR_ACCESS_DENIED == GetLastError())
{
bRet = true;
}
}
else
{
bRet = true;
}
if (bRet)
{
#ifdef UNICODE
strPortName = wstringToString(portName);
#else
strPortName = std::string(portName);
#endif
m_serialPortInfo.portName = strPortName;
portInfoList.push_back(m_serialPortInfo);
}
CloseHandle(m_handle);
}
return bRet;
}
int main() {
vector<SerialPortInfo> spInfo;
enumDetailsSerialPorts(spInfo);
for (int i = 0; i < spInfo.size(); i++)
{
std::cout << i << " - " << spInfo[i].portName << " " << spInfo[i].description << std::endl;
}
return 0;
}
上面是核心函数,剩下的仅需要写一个线程去实时调用该函数即可,或者在qt中设置一个定时器,做一个实时扫描工作。
|