// // Write a string to the port // void CSerialPort::WriteToPort(BYTE bWriteBuffer[],int nWriteBufferSize) { assert(m_hComm != 0); int nSize = sizeof(bWriteBuffer)/sizeof(BYTE); m_nWriteBufferSize = nWriteBufferSize; for(int i = 0 ; i < nWriteBufferSize ; i ++) m_bWriteBuffer[i] = bWriteBuffer[i]; // set event for write SetEvent(m_hWriteEvent); } ...... |
CSerialPort m_Ports; int nColtAddr,//这个用来存放当前采集设备地址。 nColts;//这个用来存放当前缓冲区收到的字节数目 HANDLE m_pThread;//外部控制线程 BYTE m_RecBuff[1000];//接收缓冲区 float fVal[20];//处理解包内容,这里可以根据实际情况进行定义。 |
nColtAddr = 0 ; nColts = 0; if(m_Ports.InitPort(this,1,4800,\'N\',8,1,EV_RXCHAR|EV_RXFLAG,1024)) { this->m_Ports.StartMonitoring();启动监视线程 SetCommVal();发送第一台设备数据命令 } |
下面是启动外部控制线程
unsigned int nDummy; m_pThread=(HANDLE) _beginthreadex(NULL,0,CommThread,this,CREATE_SUSPENDED,&nDummy);//开辟外部控制线程 ResumeThread(m_pThread); 运行线程 |
UINT C××××View::CommThread(LPVOID pParam) { C××××View *pView = (C××××View *)pParam; while(1) { CTime cNowTime = CTime::GetCurrentTime(); tNow = cNowTime.GetTime(); struct _timeb timebuffer; _ftime(&timebuffer); int nNowMillSecond = timebuffer.millitm; /// tLast = cLastColtTime[0].GetTime(); if((tNow - tLast)*1000 + (nNowMillSecond - nMillSecond[0]) > 800) pView->SetCommVal();发送下一台设备要数据命令或者进行其他的相关处理 Sleep(100); } } |
void C××××View::SetCommVal() { int HAddr,LAddr,m_Xnh; int nHAdd,nLAdd; nHAdd = ExchangeAscII((nColtAddr>>4)&0x0f); nLAdd = ExchangeAscII(nColtAddr&0x0f); m_Xnh = nHAdd^nLAdd^0x52^0x44; HAddr = ExchangeAscII((m_Xnh>>4)&0x0f); LAddr = ExchangeAscII(m_Xnh&0x0f); BYTE OutBuff[8] = {0x40,nHAdd,nLAdd,0x52,0x44,HAddr,LAddr,0x0d}; m_Ports.WriteToPort(OutBuff,8); cLastColtTime = CTime::GetCurrentTime(); nColtAddr++; if(nColtAddr > 19)//19 define max addr numbers nColtAddr = 0; } |
BYTE C××××View::ExchangeAscII(BYTE bInput) { BYTE bRef = 0; if(bInput > 9) bRef = bInput+0x37; else bRef = bInput+0x30; return bRef; } |
BYTE C××××View::ExchangeAscIItoNormal(BYTE bInput)
{
BYTE bRef = 0;
if(bInput > 0x39)
bRef = bInput-0x37;
else
bRef = bInput-0x30;
return bRef;
}