www.pudn.com > 串口以太网通信技术转换.rar > Comm.cpp
// Comm.cpp: implementation of the Comm class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "CtoE.h"
#include "Comm.h"
#include "mainfrm.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Comm::Comm(CWnd *p)
{
char appfile[100];
GetCurrentDirectory(100,appfile);
strcat(appfile,"\\app.ini");
speed=GetPrivateProfileInt("SERIAL","speed",-1,appfile);
GetPrivateProfileString("SERIAL","comname","",ComName,5,appfile);
commset.Connected=FALSE;
commset.m_hWindow=p->m_hWnd;
}
Comm::~Comm()
{
DWORD dwExitCode;
commset.Connected = FALSE;
SetCommMask(comv,0);
for( GetExitCodeThread(hCommThread,&dwExitCode);
dwExitCode == STILL_ACTIVE;
GetExitCodeThread( hCommThread, &dwExitCode )
);
if( comv != INVALID_HANDLE_VALUE)
CloseHandle( hCommThread );
CloseHandle( ComOverlapped.hEvent );
CloseHandle( comv );
}
BOOL Comm::initcomport()
{
DCB dcb;
int err;
unsigned char s;
ComOverlapped.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
ComOverlapped.Offset = 0;
ComOverlapped.OffsetHigh = 0;
comv = CreateFile(
ComName,
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL
);
if( comv == INVALID_HANDLE_VALUE)
return FALSE;
commset.hComm = comv;
if( !SetupComm(comv,5120,5120) )
return FALSE;
PurgeComm( comv,
PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
//err = GetCommState(comv,&dcb);
if( GetCommState(comv,&dcb) == 0 )
return FALSE;
dcb.BaudRate = speed;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;
dcb.fBinary = 1;
// s = 0xfe;
// memcpy( &dcb.EvtChar, &s, 1 );
//memcpy(&dcb.EofChar,&s,1);
err = SetCommState(comv,&dcb);
if (err==0)
return FALSE;
EscapeCommFunction(comv,SETDTR); //conment for test
commset.Connected = TRUE;
hCommWatchThread = AfxBeginThread(
AFX_THREADPROC(CommWatchProc),
(LPVOID)&commset
);
if( NULL == hCommWatchThread->m_hThread )
{
commset.Connected = FALSE;
return FALSE;
}
if( NULL == DuplicateHandle(GetCurrentProcess(),
hCommWatchThread->m_hThread,
GetCurrentProcess(),
&hCommThread,
0,
FALSE,
DUPLICATE_SAME_ACCESS)
)
return FALSE;
return TRUE;
}
BOOL Comm::SendString(char *p,int length)
{
DWORD dw;
COMSTAT stat;
int err;
for(int i=0;ihComm, EV_RXFLAG|EV_RXCHAR|EV_RX80FULL ) )
{
MessageBox(lpCommSet->m_hWindow,
"Comm Error:SetCommMask Error",
NULL,
MB_OK
);
return FALSE;
}
wparam =(WPARAM)(lpCommSet->hComm);
// LPARAM 32 bit mask.
while(lpCommSet->Connected)
{
WaitCommEvent( lpCommSet->hComm, &dwEvtMask,NULL );
lparam = dwEvtMask;
SendNotifyMessage(
lpCommSet->m_hWindow,
WM_COMMNOTIFY,
wparam,
lparam
);
}
return TRUE;
}