mfc--Serial Programming---WIN API way to encapsulate the thread in a threaded class

Source: Internet
Author: User

Serial Data acquisition

This document describes how to obtain the serial port raw data and parse the raw data into data that can be processed or displayed.

First, the serial port collection has many ways:

1), MFC has a special control, direct programming acquisition, a control can only collect a serial port, and the serial port name such as COM20 may not open (here I do not practice, senior to say so), the baud rate is too high reading will be wrong.

2), using the Windows API Communication function (this is the way it is used in this project)

3), using Visual C + + standard communication functions _INP, _INPW, _INPD, _OUTP and so on directly to the serial port operation.

4), third-party written communication class.

Second, the realization process

Software Reference "VC + + Programming Practice treasure" in the 18th chapter of the content, the main reference to the last example code, the operation of the serial port is encapsulated in a thread class, when it is necessary to open a serial port to collect data, instantiate a package window operation of the thread class.

The following describes the implementation of the thread class (Environment VS2010):

1, new MFC class Cthreadcom, inherit from CWinThread.

2. Constructor initialization related variables

cthreadcom::cthreadcom (HANDLE hCom) {//Initialize the serial port handle//If you use other variables, add them yourself.M_binit =false;//serial port initialization status is Falsem_scom = _t ("");//clear the serial nameM_serror = _t ("No error!");//Initialize error messageM_hthread = NULL;//empty thread handlememset ((unsignedChar*) &m_overread,0,sizeof(OVERLAPPED)); //initializing read async variablesmemset ((unsignedChar*) &m_overwrite,0,sizeof(OVERLAPPED)); //Initialize write asynchronous variableM_overread.hevent = CreateEvent (NULL,true,false, NULL);//Create a Read eventM_overwrite.hevent = CreateEvent (NULL,true,false, NULL);//Create write Events}

3, initialization function: initialization of the relevant variables, with the function of the constructor is similar, but the specific relationship I'm not quite clear

BOOL cthreadcom::initinstance () {    //  TODO:  perform and per-thread initialization here        m_bautodelete=FALSE;    M_bdone=FALSE;     return TRUE;}

4. Open the serial port function: Set the serial port parameters and open the serial port

//Open the serial portBOOL cthreadcom::opencom (CString strcom,dword baudrate,byte bytesize,byte parity,byte stopbits) {CloseCom ();    CString Strlog; M_hcom= CreateFile (Strcom,generic_read | Generic_write,0, Null,open_existing,file_flag_overlapped,null); if(m_hcom = =Invalid_handle_value) {Strlog.format (_t ("Open%s Error"), strcom);        AfxMessageBox (Strlog); return false; } setupcomm (M_HCOM,MAXCOMINBUF,MAXCOMOUTBUF);//set input and output best buffersDCB DCB; if(! Getcommstate (m_hcom,&DCB)) {AfxMessageBox (_t ("failed to get serial port status"));        CloseHandle (m_hcom); M_hcom=Invalid_handle_value; return false; } DCB. BaudRate=baudrate; Dcb. ByteSize=ByteSize; Dcb. Parity=Parity; Dcb. StopBits=stopbits; if(! SetCommState (m_hcom,&DCB))        {CloseHandle (m_hcom); M_hcom=Invalid_handle_value; Strlog.format (_t ("Set%s commstate error!"), strcom);        AfxMessageBox (Strlog); return false; }    //Initialize error message variablesM_serror = _t ("No Error"); //defining the serial port time stampDWORD Commmask; Commmask=0             //| Ev_break//Interrupt Signal Detected//| Ev_cts//detection of a CTS signal interruption//| EV_DSR//detected a change in DSR signal//| Ev_err//Line status error occurred//| Ev_event1//event specified by the first program//| Ev_event2//event specified by the second program//| Ev_perr//Print error occurred//| Ev_ring//Ringing ringing detected//| EV_RLSD//detects changes in PLSD signal//| Ev_rx80full//receive buffer data arrives 80%| Ev_rxchar;//receives the character and puts it into the input and output buffer//| Ev_rxflag//The event character is received and placed into the input/output buffer//|    Ev_txempty; //the last word of the output buffer character sent outSetcommmask (M_hcom,commmask);//registering the event to be processedGetcommtimeouts (m_hcom,&m_commtimeout); //Set readintervaltimeout to Maxdword;readtotaltimeoutmultiplier and readtotaltimeoutconstant to 0, indicating that the read operation will immediately return data placed in the buffer M_commtimeout.readintervaltimeout = Maxdword;//the maximum time, in milliseconds, between two characters to arrive. 0 means no time limitM_commtimeout.readtotaltimeoutmultiplier =0;//Specify a multiplier of B in milliseconds to calculate the total time limit for the read operation:M_commtimeout.readtotaltimeoutconstant =0;//specifies a constant C, in milliseconds, that calculates the total time limit for read operations: 0 indicates that the read operation does not use a timed period//The effect of the three lines of code on the time limit is to read as long as there is data in the buffer .M_binit =true;//Initialize serial port status to True    return true;}

5, the thread class of the run function inside the read operation, has been read, know that threads exit

intCthreadcom::run () {//TODO: Add private code here and/or call base classDWORD dwerror,dwreadnum,dwbyteread,dwevent; Comstat comstate;//window StateBYTE Rbuf[maxcominbuf];//input data buffers     while(!M_bdone) {                 while(M_hcom! =Invalid_handle_value) {            if(Waitcommevent (M_hcom,&dwevent,null))//serial port event waiting for registration to occur{dwreadnum=30000;//the number of initialized read numbers is 30000                if(Dwevent &Ev_rxchar) {Clearcommerror (m_hcom,&dwerror,&comstate);//empty serial port events                    if(Comstate.cbinque! =0)                    {                        //if the buffer content is less than 30,000, remove all                        if(Comstate.cbinque <dwreadnum) {Dwreadnum=Comstate.cbinque; } memset (RBuf,0,sizeof(RBuf)); Dwbyteread=0; ReadFile (M_hcom,rbuf,dwreadnum,&dwbyteread,&m_overread);//reading Data//In this case, we have put the data of this reading operation into the RBUF array, and then we analyze the definition of the data frame according to the next computer, and then do the data storage or display.                             }                        }                    }                } }        }    }        returnCwinthread::run ();}

6, in the class using the thread after the thread is no longer used, such as: Close the window, must be a thread exit operation, otherwise it will cause a memory leak problem.

The Cportset class is the class that I define cthreadcom class variables and use. The function is called where the collection ends. Frees thread memory.

DWORD Cportset::stopwinthread (/*CWinThread *pthread,*/DWORD dwtimeout) {CWinThread*pthread =pthreadcom; if(Pthread==null)returnNULL; PThread->postthreadmessage (Wm_quit,0,0); :: WaitForSingleObject (PThread-m_hthread,dwtimeout); DWORD Nexitcode=0; BOOL Bflag=::getexitcodethread (pthread->m_hthread,&Nexitcode); if(bflag) {DeletePThread; }            returnNexitcode;}

mfc--Serial Programming---WIN API way to encapsulate the thread in a threaded class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.