📄 com232.cpp
字号:
#include "stdafx.h"
#include "com232.h"
CComStatus::CComStatus()
{
m_hCom = NULL;
m_bByteSize=8;
// m_bStopBits=ONESTOPBIT;
// m_bParity=NOPARITY;
m_dwBaudRate=115200;
// m_bEvtChar=EVENTCHAR;
// m_fBinary=1;
m_bConnected = FALSE;
// m_bFlowCtrl = FC_XONXOFF ;
// m_fXonXoff = FALSE;
}
CComStatus::CComStatus(BYTE bByteSize,BYTE bStopBits,BYTE bParity,
DWORD dwBaudRate,char bEvtChar,DWORD fBinary)
{
m_hCom = NULL;
m_bByteSize=bByteSize;
// m_bStopBits=bStopBits;
// m_bParity=bParity;
m_dwBaudRate=dwBaudRate;
// m_bEvtChar=bEvtChar;
// m_fBinary=fBinary;
m_bConnected = FALSE;
// m_bFlowCtrl = FC_XONXOFF ;
// m_fXonXoff = FALSE;
}
BOOL CComStatus::OpenConnection(short m_bComId)
{
char csCom[10];
COMMTIMEOUTS CommTimeOuts ;
if((m_bComId < 0) || (m_bComId > 2))
return FALSE;//从COM1到COM2
if(m_hCom)//if already open
return FALSE;
//OVERLAPPED包含异步I/O信息
m_rdos.Offset = 0;
m_rdos.OffsetHigh = 0;
//memset(&m_rdos,0,sizeof(OVERLAPPED));
m_rdos.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
if(m_rdos.hEvent == NULL)
return FALSE;
m_wtos.Offset = 0;
m_wtos.OffsetHigh = 0;
//memset(&m_wtos,0,sizeof(OVERLAPPED));
m_wtos.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
if(m_wtos.hEvent == NULL)
{
CloseHandle(m_rdos.hEvent);
return FALSE;
}
wsprintf(csCom,"COM%d",m_bComId);
m_hCom = CreateFile(csCom,GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL
);
if(m_hCom == INVALID_HANDLE_VALUE)
return FALSE;
//SetCommMask( m_hCom, EV_RXFLAG);//RXCHAR ) ;
SetupComm( m_hCom, 2048, 2048 ) ;
//PurgeComm( m_hCom, PURGE_TXABORT | PURGE_RXABORT |
// PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
CommTimeOuts.ReadIntervalTimeout =0xFFFFFFFF ;
CommTimeOuts.ReadTotalTimeoutMultiplier =0;
CommTimeOuts.ReadTotalTimeoutConstant = 1000;
CommTimeOuts.WriteTotalTimeoutMultiplier = 2*CBR_115200/this->m_dwBaudRate;//( npTTYInfo ) ;
CommTimeOuts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts( m_hCom, &CommTimeOuts ) ;
if(!SetupConnection())
{
CloseConnection();
return FALSE;
}
// EscapeCommFunction( m_hCom, SETDTR );
m_bConnected = TRUE;
return TRUE;
}
BOOL CComStatus::CloseConnection()
{
if (NULL == m_hCom)
return ( TRUE ) ;
m_bConnected = FALSE;
//SetCommMask( m_hCom, 0 ) ;
//EscapeCommFunction( m_hCom, CLRDTR ) ;
//PurgeComm( m_hCom, PURGE_TXABORT | PURGE_RXABORT |
// PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
CloseHandle( m_hCom ) ;
m_hCom = NULL;
CloseHandle(m_rdos.hEvent);
CloseHandle(m_wtos.hEvent);
return ( TRUE ) ;
}
BOOL CComStatus::SetupConnection()
{
BOOL fRetVal ;
DCB dcb ;
if(m_hCom == NULL)
return FALSE;
dcb.DCBlength = sizeof( DCB ) ;
GetCommState( m_hCom, &dcb ) ;
dcb.BaudRate = 115200;//this->m_dwBaudRate;
dcb.ByteSize = 8;//this->m_bByteSize;
//dcb.Parity = this->m_bParity;
//dcb.StopBits = this->m_bStopBits ;
//dcb.EvtChar = this->m_bEvtChar ;
//dcb.fBinary = TRUE ;
//dcb.fParity = TRUE ;
fRetVal = SetCommState( m_hCom, &dcb ) ;
return ( fRetVal ) ;
} // end of SetupConnection()
BOOL CComStatus::IsConnected()
{
return m_bConnected;
}
//监视串口数据
/*UINT CommWatchProc( LPVOID lpData )
{
DWORD dwEvtMask ;
//NPTTYINFO npTTYInfo = (NPTTYINFO) lpData ;
OVERLAPPED os ;
int nLength ;
//BYTE abIn[ MAXBLOCK + 1] ;
CComStatus * pCom = (CComStatus *)lpData;
memset( &os, 0, sizeof( OVERLAPPED ) ) ;
// create I/O event used for overlapped read
os.hEvent = CreateEvent( NULL, // no security
TRUE, // explicit reset req
FALSE, // initial event reset
NULL ) ; // no name
if (os.hEvent == NULL)
{
MessageBox( NULL, "Failed to create event for thread!", "TTY Error!",
MB_ICONEXCLAMATION | MB_OK ) ;
return ( FALSE ) ;
}
if (!SetCommMask( pCom->m_hCom, EV_RXFLAG))//CHAR ))
return ( FALSE ) ;
char buf[256];
while ( pCom->m_bConnected )
{
dwEvtMask = 0 ;
WaitCommEvent( pCom->m_hCom, &dwEvtMask, NULL );
if ((dwEvtMask & EV_RXCHAR) == EV_RXCHAR)
{
if ((nLength = ReadCommBlock( *pCom, (LPSTR) buf, 255 )))
{
buf[nLength]='\0';
AfxMessageBox(buf);
}
}
}
// get rid of event handle
CloseHandle( os.hEvent ) ;
return( TRUE ) ;
} // end of CommWatchProc()*/
int ReadCommBlock(CComStatus& comDev,LPSTR lpszBlock, int nMaxLength )
{
BOOL fReadStat;
COMSTAT ComStat ;
DWORD dwErrorFlags;
DWORD dwLength;
DWORD dwError;
char szError[ 10 ] ;
// only try to read number of bytes in queue
ClearCommError( comDev.m_hCom, &dwErrorFlags, &ComStat ) ;
//ClearCommError() return true,no error
dwLength = nMaxLength;//min( (DWORD) nMaxLength, ComStat.cbInQue ) ;
if (dwLength > 0)
{
fReadStat = ReadFile( comDev.m_hCom, lpszBlock,
dwLength, &dwLength, &(comDev.m_rdos) ) ;
if (!fReadStat)
{
if (GetLastError() == ERROR_IO_PENDING)
{
OutputDebugString("\n\rIO Pending");
// We have to wait for read to complete.
// This function will timeout according to the
// CommTimeOuts.ReadTotalTimeoutConstant variable
// Every time it times out, check for port errors
while(!GetOverlappedResult( comDev.m_hCom ,
&(comDev.m_rdos), &dwLength, TRUE))
{
dwError = GetLastError();
if(dwError == ERROR_IO_INCOMPLETE)
// normal result if not finished
continue;
else
{
// an error occurred, try to recover
wsprintf( szError, "<CE-%u>", dwError ) ;
ClearCommError( comDev.m_hCom , &dwErrorFlags, &ComStat ) ;
break;
}
}
}
else
{
// some other error occurred
dwLength = 0 ;
ClearCommError( comDev.m_hCom , &dwErrorFlags, &ComStat ) ;
}
}
}
return ( dwLength) ;
} // end of ReadCommBlock()
/*int ReadCommBlockEx(CComStatus& comDev,LPSTR lpszBlock, int nMaxLength,DWORD dwTimeOut)
{
LPSTR lpOffset=lpszBlock;
int nReadCount = 0;
char chBuf;
if(!comDev.m_hCom)
return 0;
if(dwTimeOut <= 0)
return 0;
MSG msg;
DWORD dwLastTick,dwNowTick,dwGoneTime;
dwGoneTime = 0;
dwLastTick = GetTickCount();
dwNowTick = dwLastTick;
do
{
if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
if(ReadCommBlock(comDev,&chBuf,1) > 0)
{
*lpOffset = chBuf;
lpOffset ++;
nReadCount ++;
}
dwNowTick = GetTickCount();
if(dwNowTick < dwLastTick)
{
dwLastTick = dwNowTick;
}
dwGoneTime = dwNowTick - dwLastTick;
}while((nReadCount < nMaxLength) && (dwGoneTime < dwTimeOut));
return (nReadCount);
}//end ReadCommBlockEx*/
BOOL WriteCommBlock( CComStatus& comDev, LPSTR lpByte , DWORD dwBytesToWrite)
{
BOOL fWriteStat ;
DWORD dwBytesWritten ;
DWORD dwErrorFlags;
DWORD dwError;
DWORD dwBytesSent=0;
COMSTAT ComStat;
char szError[ 128 ] ;
fWriteStat = WriteFile( comDev.m_hCom , lpByte,
dwBytesToWrite,&dwBytesWritten,
&comDev.m_wtos);
if (!fWriteStat)
{
if(GetLastError() == ERROR_IO_PENDING)
{
// We should wait for the completion of the write operation
// so we know if it worked or not
// This is only one way to do this. It might be beneficial to
// place the write operation in a separate thread
// so that blocking on completion will not negatively
// affect the responsiveness of the UI
// If the write takes too long to complete, this
// function will timeout according to the
// CommTimeOuts.WriteTotalTimeoutMultiplier variable.
// This code logs the timeout but does not retry
// the write.
while(!GetOverlappedResult( comDev.m_hCom,
&(comDev.m_wtos), &dwBytesWritten, TRUE ))
{
dwError = GetLastError();
if(dwError == ERROR_IO_INCOMPLETE)
{
// normal result if not finished
dwBytesSent += dwBytesWritten;
continue;
}
else
{
// an error occurred, try to recover
wsprintf( szError, "<CE-%u>", dwError ) ;
ClearCommError( comDev.m_hCom, &dwErrorFlags, &ComStat ) ;
break;
}
}
dwBytesSent += dwBytesWritten;
if( dwBytesSent != dwBytesToWrite )
wsprintf(szError,"\nProbable Write Timeout: Total of %ld bytes sent", dwBytesSent);
else
wsprintf(szError,"\n%ld bytes written", dwBytesSent);
OutputDebugString(szError);
//AfxMessageBox(szError);
}
else
{
// some other error occurred
ClearCommError( comDev.m_hCom, &dwErrorFlags, &ComStat ) ;
return ( FALSE );
}
}
return ( TRUE ) ;
} // end of WriteCommBlock()
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -