commport.cpp

来自「嵌入式DOS系统上位升级程序FileUpgrade, 需配合本人上传的FileU」· C++ 代码 · 共 129 行

CPP
129
字号
// CommPort.cpp: implementation of the CCommPort class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CommPort.h"
#include "Pcomm.h"

CCommPort::CCommPort()
{
	m_HaveDataEvent=NULL;
	m_RecvThreadHandle=NULL;
	mHead=mTail=0;
	m_port=0;
}
CCommPort::~CCommPort()
{
	sio_close();
}
UINT CCommPort::MyCommPortThread( LPVOID pParam )
{
	((CCommPort*)pParam)->MyCommPortThread();
	return 0;
}
//0=OK 非0=错误。
int CCommPort::sio_open(int portNo,long Speed)
{
	::sio_flush(m_port,2);
	mHead=mTail=0;
	sio_close();
	if(::sio_open(portNo)==SIO_OK)
	{
		m_port=portNo;
		::sio_ioctl (portNo,B9600,BIT_8|STOP_1|P_NONE);
		::sio_SetReadTimeouts(portNo,0,0);
		if(Speed!=9600) ::sio_baud(portNo,Speed);
		m_RecvThreadHandle=AfxBeginThread(MyCommPortThread,this)->m_hThread;

		m_HaveDataEvent=new CEvent(FALSE,TRUE,NULL,NULL);

		return 0;
	}
	return 1;
}
void CCommPort::sio_close()
{
	if(m_port)
	{
		::sio_close(m_port);
		m_port=0;
		WaitForSingleObject(m_RecvThreadHandle,1000);
	}
	if(m_HaveDataEvent) delete m_HaveDataEvent;
	m_HaveDataEvent=NULL;

}
void CCommPort::MyCommPortThread()
{
	signed short Newchar;
	for(;;)
	{
		Newchar=::sio_getch(m_port);
		if(Newchar>=0) 
		{
			mData[mTail++]=(unsigned char)Newchar;
			if(mTail==MAXBUFFER) mTail=0;
			if(mHead==mTail)
			{ 	mHead++;
				if(mHead==MAXBUFFER) mHead=0;
			}
			if(m_HaveDataEvent)	m_HaveDataEvent->SetEvent();
			RecvNewChar((unsigned char)Newchar);
		}
		else if(Newchar==SIO_BADPORT) break;
	}
}
signed short int CCommPort::sio_getch()
{
	signed short int ch=-1;
	if(m_HaveDataEvent) m_HaveDataEvent->Lock(110);
	if(mHead!=mTail)
	{
		ch=(mData[mHead++]&0xFF);
		if(mHead==MAXBUFFER) mHead=0;
	}
	if(mHead==mTail && m_HaveDataEvent)m_HaveDataEvent->ResetEvent();
	return ch;
}

void CCommPort::sio_write(char *buf, int len)
{
	::sio_write(m_port,buf,len);
}
void CCommPort::sio_write(char *buf)
{
	while(*buf)
	{
		::sio_putch(m_port,*buf);
		buf++;
	}
}
void CCommPort::sio_putch(char ch)
{
	::sio_putch(m_port,ch);
}
void CCommPort::sio_flush()
{
	mHead=mTail=0;
	::sio_flush(m_port,2);
}
int CCommPort::sio_check(int portNo)
{
	if(::sio_open(portNo)==SIO_OK)
	{
		::sio_close(portNo);
		return 0;
	}
	return 1;
}
void CCommPort::RecvNewChar(unsigned char ch)
{

}

void CCommPort::sio_baud(unsigned short speed)
{
	::sio_baud(m_port,speed);
}

⌨️ 快捷键说明

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