⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 comport.cpp

📁 pelco D protocol 的一个简单实现
💻 CPP
字号:
// ComPort.cpp: implementation of the CComPort class.
//
// By: John Homppi&Vladimir Shishkov March 11, 1999
// This is a sample class. Production versions will require
// additional exception handling code.

// This sample was developed using Visual C++ V5.0 with MFC.
// It has been tested using Windows NT and Windows 95
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include "stdafx.h"
#include "string.h"
#include "ComPort.h"
//#include "Vars.h"


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CComPort::CComPort()
{
	m_bPortReady = FALSE;

} // end constructor CComPort


DCB	CComPort::GetDCB(void)
{
	return  m_dcb;	
}

CComPort::CComPort(char* cnfData)
{
	m_bPortReady = FALSE;
	ParseSerialPortString(cnfData);
	if(!Open())
		m_hCom = NULL; 

} // end constructor CComPort

BOOL CComPort::ParseSerialPortString(char*   m_s_config)
{

	//4 values for serial port settings COM1:;19200;2;0;8;0 - flow
	char* str;
	strcpy(m_tmp_buffer, m_s_config);	
	str = strtok(m_tmp_buffer, ";");
	if (strlen(str)== 0)
		return false;
	m_comPort = str;

	//Baud rate
//	strcpy(tmpChar, m_s_config);	
	str = strtok(NULL, ";");
	if (strlen(str)== 0)
	{
		return false;  //Should not happen
	}
	m_baudRate = atol(str);

	//Parity
	str = strtok(NULL, ";");
	if (strlen(str)== 0)
	{
		return false;  //Should not happen
	}
	m_parity = atoi(str);

	//StopBit
	str = strtok(NULL, ";");
	if (strlen(str)== 0)
	{
		return false;  //Should not happen
	}
	m_stopBit = atoi(str);

	//Parity

	//ByteSize
	str = strtok(NULL, ";");
	if (strlen(str)== 0)
	{
		return false;  //Should not happen
	}
	m_byteSize = atoi(str);

	str = strtok(NULL, ";");
	if (strlen(str)== 0)
	{
		return false;  //Should not happen
	}
		m_OutxDsrFlow = atoi(str);
		m_OutxCtsFlow  = m_OutxDsrFlow;
		
	return TRUE;
}


CComPort::~CComPort()
{
   m_bPortReady = FALSE;
   m_hCom = NULL;
}// end destructor CComPort

//
// initialize the com port
//
BOOL CComPort::Open(void)
{
	DWORD	dwRC;
	DWORD	dwError;
//	char	sMsg[512];

	m_bPortReady = TRUE; // everything is OK so far

	m_sComPort = m_comPort;

	m_hCom = CreateFile(m_sComPort, 
		GENERIC_READ | GENERIC_WRITE,
		0, // exclusive access
		NULL, // no security
		OPEN_EXISTING,
		0, // no overlapped I/O
		NULL); // null template

	if (m_hCom == INVALID_HANDLE_VALUE)
	{
		m_bPortReady = FALSE;
		dwError = GetLastError();
		
		// example error code expansion follows
		LPVOID lpMsgBuf;
		lpMsgBuf = NULL;
		dwRC = FormatMessage( 
			FORMAT_MESSAGE_ALLOCATE_BUFFER | 
			FORMAT_MESSAGE_FROM_SYSTEM | 
			FORMAT_MESSAGE_IGNORE_INSERTS,
			 NULL,
			dwError, //  from GetLastError(),
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
			(LPTSTR) &lpMsgBuf,
			0,
			NULL);
		
		if (dwRC && lpMsgBuf)
		{
			printf("COM open failed: Port=%s Error=%d - %s",
				m_sComPort, dwError, lpMsgBuf);
		}
		else
		{
			printf("COM open failed: Port=%s Error=%d ",
				m_sComPort, dwError);
		} // end if
		if (dwRC && lpMsgBuf)
		{
			LocalFree( lpMsgBuf );
		} // end if
 
	} // end if


	if (m_bPortReady)
	{
		m_bPortReady = GetCommState(m_hCom, &m_dcb);
		if (!m_bPortReady)
		{
			dwError = GetLastError();
			printf("GetCommState failed: Port=%s Error=%d",
				m_sComPort, dwError);
//			MessageBox(sMsg);
		} // end if
	} // end if

	if (m_bPortReady)
	{
		m_dcb.BaudRate = m_baudRate;
		m_dcb.ByteSize = m_byteSize;
		m_dcb.Parity = m_parity;
		m_dcb.StopBits = m_stopBit;
		m_dcb.fOutxCtsFlow = m_OutxCtsFlow;
		m_dcb.fOutxDsrFlow = m_OutxDsrFlow;
 		m_dcb.fAbortOnError = TRUE;
		m_dcb.fDtrControl = DTR_CONTROL_ENABLE; 
    m_dcb.fDsrSensitivity = FALSE;      // DSR sensitivity 
    m_dcb.fOutX = FALSE;                // No XON/XOFF out flow control 
    m_dcb.fInX = FALSE;                 // No XON/XOFF in flow control 
    m_dcb.fTXContinueOnXoff = TRUE;     // XOFF continues Tx 
    m_dcb.fErrorChar = FALSE;           // Disable error replacement 
    m_dcb.fNull = FALSE;                // Disable null stripping 




    //m_dcb.fParity = TRUE;               // Enable parity checking 
    //m_dcb.fOutxCtsFlow = FALSE;         // No CTS output flow control 
    //m_dcb.fOutxDsrFlow = FALSE;         // No DSR output flow control 
    //m_dcb.fRtsControl = RTS_CONTROL_ENABLE; 
    //m_dcb.fAbortOnError = FALSE;        // Do not abort reads/writes on 
    //m_dcb.ByteSize = 8;                 // Number of bits/byte, 4-8 
    //m_dcb.Parity = NOPARITY;            // 0-4=no,odd,even,mark,space (was NOPARITY)
    //m_dcb.StopBits = ONESTOPBIT;        // 0,1,2 = 1, 1.5, 2 


		m_bPortReady = SetCommState(m_hCom, &m_dcb);
		if (!m_bPortReady)
		{
			dwError = GetLastError();
			printf("SetCommState failed: Port=%s Error = %d",
				m_sComPort, dwError);
		}
	} // end if

	if (m_bPortReady)
	{
		m_bPortReady = GetCommTimeouts (m_hCom, &m_CommTimeouts);
		if (!m_bPortReady)
		{
			dwError = GetLastError();
			printf("GetCommTimeouts failed: Port=%s Error = %d",
				m_sComPort, dwError);
		} // end if
	} // end if

	if (m_bPortReady)
	{
		m_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
		m_CommTimeouts.ReadTotalTimeoutConstant = 1;
		m_CommTimeouts.ReadTotalTimeoutMultiplier = 0;
		m_CommTimeouts.WriteTotalTimeoutConstant = 0;
		m_CommTimeouts.WriteTotalTimeoutMultiplier = MAXDWORD;
		m_bPortReady = SetCommTimeouts (m_hCom, &m_CommTimeouts);
		if (!m_bPortReady)
		{
			dwError = GetLastError();
			printf("SetCommTimeouts failed: Port=%s Error = %d",
				m_sComPort, dwError);
		} // end if
	} // end if

	return m_bPortReady;
} // end CComPort::Open

void CComPort::Purge()
{
//	 PurgeComm(m_hCom, PURGE_RXABORT|PURGE_RXCLEAR);//|PURGE_TXABORT|PURGE_TXCLEAR);
	 PurgeComm(m_hCom, PURGE_RXCLEAR|PURGE_TXCLEAR);
}


//
// read data from the com port
//

BYTE CComPort::com_rx(CHAR& ch)
{
	BOOL	bReadRC;
	DWORD	iBytesWritten; 
	DWORD	iBytesRead;
	CHAR	rcvBuffer[10];
	DWORD	dwError;
	iBytesWritten = 0;
	//if(!m_bPortReady)
	//	return HANDL_RECREATE;
	bReadRC = ReadFile(m_hCom, rcvBuffer, 1, &iBytesRead, NULL);
	ch = '0';
	if ((bReadRC) && (iBytesRead))
	{
		ch = rcvBuffer[0];
		return COM_OK;
	}
		else if (!bReadRC)
		{
			dwError = GetLastError();
			printf("Read length failed: RC=%d Bytes read=%d, "
				"Error=%d ",bReadRC, iBytesRead, dwError);
			return COM_REOPEN;

		} // end if
	return COM_REOPEN;


} // end CComPort::Read



BOOL CComPort::Read(char* rcvBuffer, BYTE& msgLen)
{
	BOOL	bReadRC;
	DWORD	iBytesWritten; 
	DWORD	iBytesRead;
	DWORD	dwError;

	iBytesWritten = 0;
	bReadRC = ReadFile(m_hCom, rcvBuffer, MAXSIZE, &iBytesRead, NULL);
	if ((bReadRC) && (iBytesRead > 0))
	{
		msgLen = iBytesRead;
		return TRUE;
	}
	return FALSE;

}

BOOL CComPort::Write(LPBYTE pData, BYTE length)
{
	BOOL	bWriteRC;
	DWORD	iBytesWritten; 
	DWORD	dwError;

	iBytesWritten = 0;

	bWriteRC = WriteFile(m_hCom, pData,length,&iBytesWritten,NULL);
	if (!bWriteRC || (iBytesWritten != length))
	{	
		dwError = GetLastError();
		return false;
	} // end if
	return true;

} // end CComPort::Write



void CComPort::Close()
{
	CloseHandle(m_hCom);
	m_hCom = NULL;
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -