int CSerial::Write(BYTE *pBuf, DWORD nSize)
{
COMSTAT ComStat;
DWORD dwErrorFlags;
DWORD dwBytesWritten;
OVERLAPPED osWrite;
BOOL bWriteStat;
DWORD dwEventStat;
memset(&osWrite, 0, sizeof(OVERLAPPED));
osWrite.hEvent = _hWrEvt;
ClearCommError(_hCom,&dwErrorFlags,&ComStat);
bWriteStat=WriteFile(_hCom, pBuf, nSize, &dwBytesWritten, &osWrite);
if(!bWriteStat)
{
if(GetLastError()==ERROR_IO_PENDING)
{
do{
dwEventStat = WaitForSingleObject(osWrite.hEvent, 200);
}while(dwEventStat == WAIT_TIMEOUT);
if(dwEventStat == WAIT_OBJECT_0) //write done.
{
if(GetOverlappedResult(_hCom, &osWrite, &dwBytesWritten, TRUE))
{
return dwBytesWritten;
}
}
}
//Reset Send Error.
ResetTx();
return 0;
}
return dwBytesWritten;
}
int CSerial::Read(BYTE *pBuf, DWORD nSize)
{
COMSTAT ComStat;
DWORD dwEventStat;
DWORD dwBytesRead;
DWORD dwErrorFlags;
OVERLAPPED osRead;
BOOL bReadStatus;
if(!isValid())
return -1;
memset(&osRead,0,sizeof(OVERLAPPED));
osRead.hEvent = _hRdEvt;
ClearCommError(_hCom,&dwErrorFlags,&ComStat);
//if(!ComStat.cbInQue)
// return 0;
dwBytesRead=min(nSize, (DWORD)ComStat.cbInQue);
bReadStatus = ReadFile(_hCom, pBuf, dwBytesRead, &dwBytesRead, &osRead);
if(!bReadStatus) //如果ReadFile函数返回FALSE
{
if(GetLastError()==ERROR_IO_PENDING)
{
do{
dwEventStat = WaitForSingleObject(osRead.hEvent, 200);
}while(dwEventStat == WAIT_TIMEOUT);
if(dwEventStat == WAIT_OBJECT_0) //write done.
{
if(GetOverlappedResult(_hCom, &osRead, &dwBytesRead, TRUE))
{
return dwBytesRead;
}
}
}
ResetTx();
return 0;
}
return dwBytesRead;
}