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

📄 commtestdlg.cpp

📁 实现串口通信测试的程序
💻 CPP
📖 第 1 页 / 共 2 页
字号:
				{
					m_comm.SetOutput(COleVariant(m_SendData.Mid(j,MAX_LEN)));
					j+=1;
					if (j==n) break;
				}
			}
		}
	}
    if(SendMode==HEX)
	{
		
		int DataSize=m_Sendhexdata.GetSize();
		if(DataSize<512 && DataSize>0 )
		{
			m_comm.SetOutput(COleVariant(m_Sendhexdata));
		}else if(DataSize>512) 
		{		
			int n = DataSize /MAX_LEN ;               // 将数据分t次读入;
			if(MAX_LEN * n <DataSize)  n+=1;
			
			int j=0;
			
			CByteArray DataBlock;
			while(1)
			{
				//if(m_comm.GetInBufferCount()==0 && m_comm.GetOutBufferCount()==0 )
				{	
					for(int index=0;index<MAX_LEN;index++)
					{
						if(index + MAX_LEN * j >=DataSize) break;
						DataBlock.Add(m_Sendhexdata[index + MAX_LEN * j]);
					}
					m_comm.SetOutput(COleVariant(DataBlock));
					DataBlock.RemoveAll();
					j+=1;
					if (j==n) break;
				}
				
			}
		}
	}


		//if(SendMode==ASCII)
		//	m_comm.SetOutput(COleVariant(m_SendData));
		//else
		//	m_comm.SetOutput(COleVariant(m_Sendhexdata));


	drawPortSet=PORTOPEN;
	InvalidateRect(&m_w,TRUE);
}

void CCommTestDlg::OnSetPort() 
{
	CSetport * dlg = new CSetport(this,&PortInfo);
	if(dlg->DoModal()==IDOK)
	 {
		 //CString str;
		 //str.Format("%d",PortInfo.BaudRate);
		 //::MessageBox(NULL, str,"aaa",MB_OK);
		 
		 PortInfo.BaudRate=dlg->Port_settings.BaudRate;
         PortInfo.ByteSize=dlg->Port_settings.ByteSize;
		 PortInfo.CurPortID=dlg->Port_settings.CurPortID;
		 PortInfo.Parity=dlg->Port_settings.Parity;
		 PortInfo.StopBits=dlg->Port_settings.StopBits;
		 
		 CurrentPort=PortInfo.CurPortID;

		 SetSBtext(0," ",1);             // 更新状态栏
		 SetSBtext(2," ",1);             // 更新状态栏
	}
}

CString CCommTestDlg::OpenFile()
{
	static char BASED_CODE szFilter[]="文本文件(*.txt)|*.txt|二进制文件(*.bin)|*.bin||" ;
  
	CFileDialog openFile (TRUE,"文本文件","*.txt",NULL,szFilter,NULL);

	if(openFile.DoModal()==IDOK)
	{
		CString fileName=  openFile.GetPathName();	
		return fileName;	
	}else
	{
		return "USER_CANCEL";
	}

  return "OPEN_ERR";
}

void CCommTestDlg::OnOpenFile() 
{
	 CFile readIN;
     CFileException e;
	 CString FileName=OpenFile();
	 if (FileName=="USER_CANCEL") 
	 {
		 return;					//没有选择文件;
	 }else if(FileName=="OPEN_ERR")
	 {
		 return;
	 }
	 
	 #ifdef _DEBUG
		::MessageBox(NULL, FileName,"DDD",MB_OK);
	 #endif

	 if(!readIN.Open( FileName, CFile::modeRead , &e ))
	 { 
		::MessageBox(NULL,"文件打开错误","Err",MB_OK);
		 return ;
	 }
	 int  len=readIN.GetLength();
	 char buf[BUF_SIZE];					// 缓冲区大小;

	 #ifdef _DEBUG
		mesbox(len);	
	 #endif
     
	 if(len>BUF_SIZE)    // 由于不知道文件大小;无法预先定义合适大小的缓冲区;
	 {                    // 可以分批读入;
		 int t=0;
		 int index=0;                  // 字符索引;
		 t=len/BUF_SIZE;               // 将数据分t次读入;
										//int f=15%7;
		 if(BUF_SIZE * t <len) t+=1;
        
		 m_SendData.Empty();           // 清空已保存的 发送数据;
		 for(int i=1;i<=t;i++)         // 将数据分t次读入;
		 {
			len=(int )readIN.Read(buf,BUF_SIZE);    // len>缓冲区大小 会出现内存溢出错误;
			for( int j=0 ;j<len;j++)
			{
				m_SendData.Insert(index,buf[j]);
				index++;
			}
		 }
	 }else
	 {   
		 len=(int )readIN.Read(buf,BUF_SIZE);
		 m_SendData.Empty();
		for( int n=0 ;n<len;n++)
		{
			m_SendData.Insert(n,buf[n]);
		}
	 }
	 readIN.Close();
     if (SendMode==ASCII)
		OnUpdateTBottonStatus(ID_SEND,!m_SendData.IsEmpty());


	 UpdateData(FALSE);
	 
	if(SendMode==HEX)  //如果当前为十六进制发送模式,验证是否
	{     
		 OnChangeSend() ;    //是否有非十六进制字符;
	}
}



void CCommTestDlg::OnAsciiReceive() 
{
    if (ReceiveMode==ASCII) return;
	ReceiveMode=ASCII;
	int i=HexToChar(m_ReceiveData);
	if (i==-1){ MesBox("有无法转换的字符");return;}
	UpdateData(FALSE);
}

void CCommTestDlg::OnHexReceive() 
{
	if (ReceiveMode==HEX) return;
	ReceiveMode=HEX;
    CString	Str;
	CString convert="";

	int len =m_ReceiveData.GetLength();
	for(int i=0 ;i<len;i++)
	{
		BYTE a=m_ReceiveData[i];
        Str.Format("%02X ",a);
		convert+=Str;
    }
    
	m_ReceiveData=convert;
	UpdateData(FALSE);
}

void CCommTestDlg::OnAsciiSend() 
{

	SendMode=ASCII;
	if(m_SendData.IsEmpty() ){	
		OnUpdateTBottonStatus(ID_SEND,FALSE);
    }else if(!m_SendData.IsEmpty() && PortIsOpen){
		OnUpdateTBottonStatus(ID_SEND,TRUE);
	}

}

void CCommTestDlg::OnHexSend() 
{
	
    SendMode=HEX;
	OnChangeSend() ;  // 改变发送模式时,重新作数据转换检查
	                  // 待发送数据中是否有非十六进制字符;	
}

void CCommTestDlg::initParams()
{

	Len_Receive=0;
	m_maxLen=1024;

    SendMode=HEX;
	ReceiveMode=HEX;
	PortIsOpen=FALSE;

    PortInfo.BaudRate=9600;
	PortInfo.ByteSize=8;
	PortInfo.Parity='n';
	PortInfo.StopBits=1;
	PortInfo.CurPortID=1;      // 默认串口号;

	CurrentPort=PortInfo.CurPortID;
    
	m_sendTime=1000;
	UpdateData(FALSE);
	m_AutoSend=FALSE;
	
    
    m_hexsend.SetCheck(1);
	m_hexreceive.SetCheck(1);

	drawPortSet=PORTCLOSE; //置绘制标志;

	::GetWindowRect (::GetDlgItem(m_hWnd,IDC_D1),&m_r);
	::MapWindowPoints(NULL ,m_hWnd,(LPPOINT) &m_r,2);
	::DestroyWindow(::GetDlgItem(m_hWnd,IDC_D1));

	::GetWindowRect (::GetDlgItem(m_hWnd,IDC_D2),&m_w);
	::MapWindowPoints(NULL ,m_hWnd,(LPPOINT) &m_w,2);
	::DestroyWindow(::GetDlgItem(m_hWnd,IDC_D2));
	
    ::GetWindowRect (::GetDlgItem(m_hWnd,IDC_R),&m_regin);

	//程序初始化时;
	//工具栏按钮:关闭,清除,发送 为禁止状态
	OnUpdateTBottonStatus(ID_CLOSE_PORT,FALSE);
	OnUpdateTBottonStatus(ID_SEND,FALSE);
//	OnUpdateTBottonStatus(ID_CLEAR,FALSE);
	//


}

BEGIN_EVENTSINK_MAP(CCommTestDlg, CDialog)
    //{{AFX_EVENTSINK_MAP(CCommTestDlg)
	ON_EVENT(CCommTestDlg, IDC_MSCOMM1, 1 /* OnComm */, OnOnComm, VTS_NONE)
	//}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()

void CCommTestDlg::OnOnComm() 
{

	drawPortSet=READ;
	InvalidateRect(&m_r,TRUE);  //&m_regin
	
	int len=ReceiveData( m_comm.GetCommEvent());

	drawPortSet=PORTOPEN;
	InvalidateRect(&m_r,TRUE);


	Len_Receive+=len;
//	m_c +=len;
	UpdateData(FALSE);			//更新编辑框内容
								//    HWND hwnd=::FindWindowEx(this ->m_hWnd,NULL ,"Edit",m_ReceiveData);
								//	HWND hwnd=(HWND ) GetDlgItem(IDC_RECEIVE);

								//	::SendMessage(hwnd, EM_SETSEL, Len_Receive-len,Len_Receive);
    SetSBtext(3," ",1);         // 更新状态栏
}

int CCommTestDlg::ReceiveData(int CommEvent)
{

	VARIANT			m_input1;
	COleSafeArray	m_input2;
	long			length,i;
	BYTE			data[1024];
	CString			str;


	if(CommEvent==2)			//接收缓冲区内有字符
	{
			
		m_input1=m_comm.GetInput();			//读取缓冲区内的数据
		m_input2=m_input1;					//将VARIANT型变量转换为ColeSafeArray型变量
		length=m_input2.GetOneDimSize();	//确定数据长度

		for(i=0;i<length;i++)
			m_input2.GetElement(&i,data+i);	//将数据转换为BYTE型数组

		for(i=0;i<length;i++)				//将数组转换为Cstring型变量
		{
			BYTE a=* (char *)(data+i);

			if (ReceiveMode==HEX)
				str.Format("%02X ",a);
			else 
				str.Format("%c",a);

			m_ReceiveData+=str;
		
		}
		
	}
    return length;
}

void CCommTestDlg::OnAutosend() 
{
	if(m_AutoSend==FALSE)
	{
		UpdateData(TRUE); // 设置自动发送时间
		m_AutoSend=TRUE;
		if( m_sendTime==0) return;
		CString ss;
		ss.Format("%d",m_sendTime);
        	::MessageBox(NULL,ss,"rr",MB_OK);
		SetTimer(1,m_sendTime,NULL);
	}else
	{
		m_AutoSend=FALSE;
		KillTimer(1);
	}		
}

void CCommTestDlg::OnChangeSend() 
{

	UpdateData(TRUE);

//	MesBox("onchange evev ");
	if(m_SendData.GetLength()<=0) 
	{
		                                //更新工具栏
		OnUpdateTBottonStatus(ID_SEND,FALSE);		
	}else if(m_SendData.GetLength()>0 && PortIsOpen)
	{
		OnUpdateTBottonStatus(ID_SEND,TRUE);
	}	

	m_SendDataLen=HexToStr(m_SendData ,m_Sendhexdata);
	if(m_SendDataLen==-1 && SendMode==HEX)
	{
		MesBox(" 发送数据有非十六进制字符!     \n您将无法按十六进制发送数据!\n\n         @^_^@ ");
		m_Sendhexdata.RemoveAll();   
		
		OnUpdateTBottonStatus(ID_SEND,FALSE);
		return;

	}
}


void CCommTestDlg::OnTimer(UINT nIDEvent) 
{
	if(!PortIsOpen) return;
	if( !m_comm.GetPortOpen()) return ;

	if(m_AutoSend)
		OnSend();	
	CDialog::OnTimer(nIDEvent);
}

void CCommTestDlg::OnUpdateOpenPort(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(FALSE);
	MesBox("wwwww");
}

void CCommTestDlg::drawR(int color )
{
	CClientDC dc(this);//GRAY_BRUSH
	int nBrush =color ; //DKGRAY_BRUSH;//HOLLOW_BRUSH;//LTGRAY_BRUSH;//WHITE_BRUSH;
	SelectObject(dc,GetStockObject(nBrush));
	dc.Ellipse(&m_r);
}

void CCommTestDlg::drawW(int color)
{
	CClientDC dc(this);//GRAY_BRUSH
	int nBrush=color ; //DKGRAY_BRUSH;//HOLLOW_BRUSH;//LTGRAY_BRUSH;//WHITE_BRUSH;
	SelectObject(dc,GetStockObject(nBrush));
	dc.Ellipse(&m_w);
}

//绘制读写标志:设如下几个标记;
//1.程序初始化--白色;
//2.串口打开后--深灰色;
//3.串口关闭后--白色;
//4.读写时,灰色;之后深灰色;
void CCommTestDlg::OnWRdraw()
{
	//LTGRAY_BRUSH;
	//WHITE_BRUSH;
	//GRAY_BRUSH
	//DKGRAY_BRUSH;

	if(drawPortSet==PORTCLOSE)
	{
		drawR(WHITE_BRUSH);
		drawW(WHITE_BRUSH);
	}else if (drawPortSet==PORTOPEN)
	{
		drawR(GRAY_BRUSH);
		drawW(GRAY_BRUSH);
	}else if(drawPortSet==READ)
	{
		drawR(WHITE_BRUSH);
		drawW(GRAY_BRUSH);
	}else if(drawPortSet==WRITE)
	{
		drawR(GRAY_BRUSH);
		drawW(WHITE_BRUSH);
	}

}

void CCommTestDlg::mesbox(DWORD c)
{
	CString s;
	s.Format("%d",c);
	::MessageBox(NULL,s,"the value is ---",MB_OK);

}

void CCommTestDlg::SetSBtext(int position,LPSTR szText,int nText)
{
	// 此函数第二个参数 LPSTR szText 暂时为空 即 “ ”;

	char *c[2]={"关闭","打开"};
	if(position==0)
	{
		CString txt;
		txt.Format(" 端口: %d",CurrentPort);
		char *t=txt.GetBuffer(txt.GetLength());
		::SendMessage(hStatusWindow,SB_SETTEXT,(WPARAM) (position),(LPARAM)(LPSTR)(t));
	}
	if(position==1)
	{
		CString txt;
		txt.Format(" 状态:%s ",c[ (int) PortIsOpen ] );
		char *t=txt.GetBuffer(txt.GetLength());
		::SendMessage(hStatusWindow,SB_SETTEXT,(WPARAM) (position),(LPARAM)(LPSTR)(t));
    }
	if (position==2)
	{
		CString txt;
		txt.Format( " %d: %c-%d-%d ",PortInfo.BaudRate, toupper( PortInfo.Parity ),   // toupper(  )函数将字符转成大写 #include "string.h";
		                  PortInfo.ByteSize,PortInfo.StopBits );
		char *t=txt.GetBuffer(txt.GetLength());
		::SendMessage(hStatusWindow,SB_SETTEXT,(WPARAM) (position),(LPARAM)(LPSTR)(t));
	}

	if (position==3)
	{
		CString txt;
		txt.Format( " 已接收字符数: %d",Len_Receive);
		char *t=txt.GetBuffer(txt.GetLength());
		::SendMessage(hStatusWindow,SB_SETTEXT,(WPARAM) (position),(LPARAM)(LPSTR)(t));
	}




}

void CCommTestDlg::OnUpdateTBottonStatus(int idButton, BOOL fEnable)
{
   ::SendMessage(m_wndToolBar,TB_ENABLEBUTTON,(WPARAM) (idButton),(LPARAM) MAKELONG(fEnable, 0));//工具栏按钮
}


⌨️ 快捷键说明

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