Exemplo n.º 1
0
BOOL OpenPort(int nCom)
{
    TCHAR szPortName[32];
    _stprintf_s(szPortName, 32, _T("\\\\.\\COM%d"), nCom);
    g_hCom = CreateFile(szPortName,
                        GENERIC_WRITE | GENERIC_READ,
                        0,
                        NULL,
                        OPEN_EXISTING,
                        0,
                        NULL);

    if ( (g_hCom == NULL) || (g_hCom == INVALID_HANDLE_VALUE) )
    {
        // port is not valid
        TRACE(_T("(COM%d): Invalid COM port\n"), nCom);
        return FALSE;
    }

    TRACE(_T("(COM%d): Testing COM state\n"), nCom);
    if ( ! ConfigureComPort() )
    {
        if ( g_hCom )
        {
            CloseHandle(g_hCom);
            g_hCom = NULL;
        }
        TRACE(_T("(COM%d): Failed to test COM port\n"), nCom);
        return FALSE;
    }
    TRACE(_T("(COM%d): Opened\n"), nCom);
    return TRUE;
}
Exemplo n.º 2
0
void CComThreadBasic::ReconnectCom(const char *ComName)
{
	LPTSTR lpMsgBuf;

	m_CsReconnect.Lock();
	
	if(m_hComPort!=INVALID_HANDLE_VALUE)
	{
		CloseHandle(m_hComPort);
		m_hComPort=INVALID_HANDLE_VALUE;
	}
	m_hComPort=CreateFile(ComName, GENERIC_WRITE|GENERIC_READ, 0, NULL, OPEN_EXISTING , 
	FILE_ATTRIBUTE_NORMAL, NULL);
	if(m_hComPort==INVALID_HANDLE_VALUE)
	{

		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM| 
		FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPTSTR) &lpMsgBuf, 0, NULL);
		Msg("Ошибка открытия порта %s.\n%s", &ComName[0],(LPCTSTR)lpMsgBuf);
		LocalFree(lpMsgBuf);
		m_CsReconnect.Unlock();
		return;
	}
	ConfigureComPort(m_hComPort, m_BaudRate);
	
	if(m_hComThread!=NULL)
	{
		DWORD ExitCode=0;
		GetExitCodeThread(m_hComThread,&ExitCode);
		if(ExitCode!=STILL_ACTIVE) //Поток вышел по ошибке
		{
			DWORD Unused;
			m_hComThread=CreateThread(NULL,NULL, &CComThreadBasic::ComThread,this,0,&Unused);
		}
	}
	else //Начальное создание потока
	{
		DWORD Unused;
		m_hComThread=CreateThread(NULL,NULL, &CComThreadBasic::ComThread,this,0,&Unused);
	}
	m_CsReconnect.Unlock();
}