Serial communication Code. It was written by someone else, and I added some notes.

Source: Internet
Author: User
Tags readfile

Communication.h:interface for the ccommunication class.///////////////////////////////////////////////////////// #if!defined (afx_communication_h__6ca00576_f088_11d1_89bb_8311a0f2733d__included_) #define AFX_ communication_h__6ca00576_f088_11d1_89bb_8311a0f2733d__included_#if _msc_ver >= 1000#pragma once#endif//_MSC_ VER >= 1000/*_msc_ver Definition Compiler version MS VC + + 10.0 _msc_ver = ms VC + + 9.0 _msc_ver = ms + + 8.0 _msc_ver = 1400 ms V C + + 7.1 _msc_ver = 1310 MS VC + + 7.0 _msc_ver = 1300 MS VC + + 6.0 _msc_ver = 10.0 MS VC + + 5.0 _msc_ver = 1100 MS VC + + + is Visual C + + 2010,ms VC + + 9.0 is Visual C + + 2008,ms VC + + 8.0 is Visual C + + 2005. Adding a _msc_ver macro to a program allows the compiler to selectively compile a program based on the compiler version. For example, the Lib file generated by a version compiler may not be called by another version of the compiler, so when developing the application, a Lib file generated by multiple versions of the compiler is placed in the LIB call Library of the program. By adding the _msc_ver macro to the program, the compiler will be able to automatically select the version of the Lib library that can be linked to it at the time of invocation, as shown below. #if _msc_ver >= 1400//For VC8, or vc9 #ifdef _DEBUG #pragma comment (lib, "Somelib-vc8-d.lib") #else if #pragma comm Ent (lib, "Somelib-vc8-r.lib") #endif #else If _Msc_ver >= 1310//For vc71 #ifdef _DEBUG #pragma comment (lib, "Somelib-vc71-d.lib") #else if #pragma comment (lib, " Somelib-vc71-r.lib ") #endif #else if _msc_ver >=1200//For VC6 #ifdef _DEBUG #pragma comment (lib," Somelib-vc6-d.lib ") #else if #pragma comment (lib," Somelib-vc6-r.lib ") #endif #endif */#define Wm_receivepacket Wm_user+100class Ccommun ication {public://bool connect;//send data function int senddata (char *data,int len);//Set Message receiver void Setmessagereceiver (CWnd *pwnd) ;//initialization function bool Initialize (char *device,dword baudrate,int bits,int ddv,int stopbit);//constructor ccommunication ();// destructor virtual ~ccommunication ();//close Communication interface bool Closeserialport ();//cwnd is the base class for MFC window classes, providing basic functionality for all Windows classes in the Microsoft Base Class library CWnd *msg_ Receiver;//overlapped is a struct that contains information for asynchronous input and output overlapped write_os;//defines a handle handle hcomport;private:}; #endif//!defined (afx_communication_h__6ca00576_f088_11d1_89bb_8311a0f2733d__included_)/* First declaration: typedef struct _OVERLAPPED {DWORD   Internal;   DWORD Internalhigh;   DWORD Offset;   DWORD Offsethigh; HANDLE hevent; } overlapped parameter description: Internal: Reserved for operating system use. It specifies a system-independent state that is valid when the GetOverlappedResult function returns without setting the extended error message error_io_pending. Internalhigh: reserved for use by the operating system. It specifies the length of the data transfer, which is valid when the GetOverlappedResult function returns True. Offset: The location of the file is the byte offset from the beginning of the file. Call the ReadFile or WriteFile function before calling the process to set this member. This member is ignored to zero when reading or writing to named Pipes and communication devices. Offsethigh: Specifies the high-level word for the byte offset of the file transfer. This member is ignored to zero when reading or writing to named Pipes and communication devices. Hevent: Processing an event when the transfer is complete is set to signaled state. Call process set this member before calling ReadFile, WriteFile, Transactnamedpipe, connectnamedpipe functions. *//* Second statement: typedef struct _OVERLAPPED {ULONG_PTR Internal;//operating system reserved, indicating a system-related state ulong_ptr Internalhigh; Indicates the length of the data sent or received union {struct {DWORD offset;//File transfer byte offset low word DWORD offsethigh;//File Transfer byte offset high word}; PVOID Pointer; Pointer, pointing to the file transfer location}; HANDLE hevent; Specifies an event that fires when an I/O operation is completed} OVERLAPPED, *lpoverlapped;*//*i/o device processing is bound to let the main program stop waiting for the completion of I/O, to solve this problem, you can use the OVERLAPPED. OVERLAPPED I/O is a technology of WIN32, you can ask the operating system to send data to you, and notify you when the transfer is complete. This technology allows your program to continue to process transactions while I/O is in progress. In fact, it is the thread I/O that completes the overlapped I/O within the operating system. , without the cost of any pain. In other words, overlapped is primarily about setting up asynchronous I/O operations, where an application can read or write data in the background and do other things in the foreground. */

Communication.cpp:implementation of the Ccommunication class./////////////////////////////////////////////////// #include "stdafx.h" #include "Communication.h" #ifdef _debug#undef this_filestatic Char this_file []=__file__; #define NEW debug_new#endif//////////////////////////////////////////////////////////////////////// Construction/destruction//////////////////////////////////////////////////////////////////////bool CState;// Defines a global variable cstate. The constructor is used to give the global variable Cstate onccommunication::ccommunication () {cstate=true;} Destructors are used to give global variables Cstate offccommunication::~ccommunication () {cstate=false;} The specific function definition. This commwatchproc function is a thread function, this function is to handle the processing of serial port related events. In the following code, there is a afxcreatethrend function that is used to create the thread, where the first parameter is to be filled commwatchprocuint commwatchproc (lpvoid lpdata) {//add message wm_ Receivepacket handler in class caller://(Wparam=pointer to data block lparam=length of data Block//add message WM_SENDSU   Ccess handler in class callerccommunication* com= (ccommunication*) lpdata;     DWORD  Dwevtmask;   OVERLAPPED OS;   Comstat Comstat;   DWORD Dwerrorflag;   DWORD Dwlength;//afxmessagebox ("receiving");   memset (&os, 0, sizeof (OVERLAPPED));                            Create I/O event used for overlapped read os.hevent = CreateEvent (NULL,//No security  TRUE,//Explicit reset req FALSE,//initial event Reset NULL ) ; No Name if (os.hevent = = null) {MessageBox (null, _t ("Failed to create event for thread!"), _t ("Comm Unication error! "), Mb_iconexclamation |      MB_OK);   return (FALSE); } if (!   Setcommmask (Com->hcomport, Ev_rxchar)) return (FALSE);   DWORD Dwread;   Char *buf;   Buf=new Char[max_path];   memset (Buf,0,max_path); while (cstate) {dwevtmask = 0; Waitcommevent (Com->hcomport, &dwevtmask, 0);//wait for the serial communication event to occur. Sleep (+);//memset (Buf,0,max_path); detects the returned dwevtmask and knows what serial port event occurred if (Dwevtmask & ev_rxchar) = = Ev_rxchar{//ev_rxchar represents a buffer with data coming up//read Codeclearcommerror (com->hcomport,&dwerrorflag,&comstat);// Clear error dwlength=comstat.cbinque;//How much data is in the input buffer? if (dwlength)//If greater than 0{if (ReadFile (Com->hcomport,buf,dwlength,&dwread,&os))//Call ReadFile function to read buffer data {com- >msg_receiver->postmessage (Wm_receivepacket, (WPARAM) buf, (LPARAM) dwread);//want the system message queue to put a message, the main thread of the notification program, the serial port received data.   }}}} delete buf;   Get rid of event handle CloseHandle (Os.hevent); return (TRUE); End of Commwatchproc ()//Initialize the port to define the number of bandwidth bits of the port parity stop bit such as bool Ccommunication::initialize (char * device,dword baudrate,int B   Its,int ddv,int stopbit) {//Srand ((unsigned) time (NULL)); Open COMM devicecstate=true;//assigns the return value of the function Createfilea to Hcomport and determines that it is equal to (HANDLE)-1 if (Hcomport = Createfilea ( device,//device name can be a name like COM2 COM3 generic_read |                 generic_write,//allow read/write 0,//exclusive access must be 0 NULL, No security attrs open_existing,//set production mode File_attribute_normal |   file_flag_overlapped,//OVERLAPPED I/O uses asynchronous communication NULL) = = (HANDLE)-1) return (FALSE); Get any early notifications Setcommmask (Hcomport, Ev_rxchar);//Set event-driven type//Setup device buffers Setupcomm (Hcomp ORT, 10240, 10240);//Set the size of the input/output buffer//purge any information in the buffer PurgeComm (hcomport, Purge_txabort |                                   Purge_rxabort | Purge_txclear | Purge_rxclear);//clear the input and output buffers//Set up for overlapped I/O commtimeouts commtimeouts;//Define the timeout structure and assign values to the values in the structure COMMTI   Meouts.readintervaltimeout = 0xFFFFFFFF;   Commtimeouts.readtotaltimeoutmultiplier = 0;   commtimeouts.readtotaltimeoutconstant = 1000;   Commtimeouts.writetotaltimeoutmultiplier = 0;   Commtimeouts.writetotaltimeoutconstant = 10000;   SetCommTimeouts (Hcomport, &commtimeouts); DCB dcb;//defines the data control block structure DCB.   Dcblength=sizeof (DCB); Dcb.   baudrate=baudrate;//communication baud rate dcb.fbinary=1; Dcb.fparity=1;   dcb.foutxctsflow=0;   dcb.foutxdsrflow=0;   dcb.fdtrcontrol=0;   dcb.fdsrsensitivity=0;   dcb.ftxcontinueonxoff=0;   dcb.foutx=0;   dcb.finx=0;   dcb.ferrorchar=0;   dcb.fnull=0;   dcb.frtscontrol=0;   dcb.fabortonerror=0;//dcb.wreserved=0; Dcb.   xonlim=0; Dcb.   xofflim=0; Dcb. bytesize=bits;//data bit length bits is a eight-bit meaning that can also be written in the number 8 DCB.   parity=0; Dcb. The stopbits=onestopbit;//stop bit is one of several//DCB written here.   Stopbits=stopbit; if (! SetCommState (HCOMPORT,&DCB))//After the data is configured, call the SetCommState function to configure the port to return (false);//If the configuration is unsuccessful, return FALSE if (! AfxBeginThread (Commwatchproc, (LPVOID) this))//Start a worker thread for the processing of serial port events//The thread here needs to be explained:/* Windows provides two threads, worker threads and user interface threads. The difference is that the worker thread does not have a window, so it does not have its own message loop. But worker threads are easy to program and often useful. We use worker threads. Mainly use it to monitor the status of the serial port, to see if there is no data arrival, communication error, while the main thread can concentrate on data processing, provide a friendly user interface and other important work.   The worker thread also has a name that is the worker thread.   */{CloseHandle (Hcomport);//If the thread does not start successfully, close the handle and return False return (false);    } else {//assert DTR and RTS escapecommfunction (HCOMPORT,SETDTR);   Escapecommfunction (Hcomport,setrts); } memset (&AMp;write_os, 0, sizeof (OVERLAPPED));                                  Write_os.hevent = CreateEvent (NULL,//No security TRUE,//Explicit reset req FALSE,//initial event reset NULL);      No Name if (NULL = = write_os.hevent) {CloseHandle (write_os.hevent);   return (FALSE); } return (TRUE); Turn off port bool Ccommunication::closeserialport () {cstate=false; Sleep, if (! CloseHandle (Hcomport)) return false;else return TRUE; void Ccommunication::setmessagereceiver (CWND * pWnd) {//add a line in class caller://??. Setmessagereceiver (this); msg_receiver=pwnd;} Function: Used to send data.    You need to commit the character content and length of the sent data int ccommunication::senddata (char * data, int len) {CString b;int a=1,c=1;unsigned long Sendlen; A=writefile (Hcomport, data, Len, &sendlen, &write_os);//In fact, its internal call is WriteFile this function. In essence, the system regards communication as a file read and write. CString Strtext;strtext.format (",, '%s", data),//::log (getdirectory () + "\\Log\\Com.csv", Strtext.left (31), TRUE, "Time,receive,send"); return Sendlen;} /* Using multithreading technology, in the work thread (that is, the so-called worker thread) to monitor the serial port, the data arrived by relying on event-driven, read the data to the main thread to report, note that the work of sending data is completed in the main thread, because usually the content of the sending data (so-called downlink data) is less, and Waitcommevent,readfile (), WriteFile () uses non-blocking communication technology. Rely on overlapping (overlappend) Read and write operation, let the serial port read and write work done in the background. *//* read and write files are the work that every Windows software developer needs to do. It can be seen that this work is very important, after all, all kinds of data need to be saved for a variety of analysis, or transmitted over the network to others. Like everyone with BT download movies, in that BT software, you need to constantly receive data from the network, and then save the data to the appropriate location in the file, you can generate the same file as the publisher, so that can be played out. Another example I play "Journey" in the game, just open the game, it constantly download the updated files from the server down, and then save to the hard disk. The WriteFile function is used to write data to a file, and the ReadFile function reads the data from the file. But these two functions can not only read the disk files, but also can receive and send the network data, as well as read and write serial, USB, and other devices such as port data. In the read and write file, the first is to open the file, and then determine whether the open is successful. When writing a file, also pay attention to whether the disk is full of space and so on. When reading a file, often need to read a different location of the file, such as to read a 4G video file, it is impossible to completely read it into memory, so you need to locate the file to read. The *//* functions WriteFile and ReadFile are declared as follows: Winbaseapiboolwinapiwritefile (__in HANDLE hfile,//is a file handle __in_bcount (nnumberofby Testowrite) Lpcvoid lpbuffer,//is a read-write data buffer __in DWORD nnumberofbytestowrite,//is how much data to write __out_opt Lpdword lpnum  berofbyteswritten,//is how much data has been written __inout_opt lpoverlapped lpoverlapped//is the structure of asynchronous read and write); Winbaseapiboolwinapireadfile (__in HANDLE hfile,//is a file handle __out_bcount_part (nNumberOfBytesToRead, *lpNumberOfB Ytesread) LPVoid lpbuffer,//is a read-write data buffer __in DWORD nnumberofbytestoread,//is how much data to read __out_opt Lpdword Lpnumbero fbytesread,//is how much data has been read __inout_opt lpoverlapped lpoverlapped//is the structure of asynchronous read and write); hfile is a file handle. Lpbuffer is a read-write data buffer. Nnumberofbytestowrite is how much data to write. Lpnumberofbyteswritten is how much data has been written. nNumberOfBytesToRead is how much data to read. nNumberOfBytesToRead is how much data has been read.  Lpoverlapped is the structure of asynchronous read and write. Examples of calling functions are as follows: #001//Create, write, read files. #002//Cai Junsheng 2007/10/21 qq:9073204 shenzhen #003 void Createfiledemo (void) #004 {#005//#006 HANDLE hfile =:: Cre Atefile (_t ("CreateFileDemo.txt"),//name of the created file. #007 generic_write| Generic_read,//write and read files. #008 0,//do not share read/write. #009 NULL,//default security attribute. #010 Create_always,//If the file exists, also created.      #011 File_attribute_normal,//general documentation. #012 NULL); The template file is empty. #013 #014 if (hfile = = INVALID_HANDLE_VALUE)//Determines whether the creation was successful based on the value of the return file handle. #015 {#016//#017 OutputDebugString (_t ("CreateFile fail!/r/n")), #018} #019 #02 0//write data to the file.    #021 const int BUFSIZE = 4096;//defines the size of the buffer #022 Char chbuffer[bufsize];                                       The definition of a buffer is actually an array of characters #023 memcpy (Chbuffer, "Test", 4);//The data is copied to the contiguous n bytes from the SRC point to the address as the starting address In a space where Destin points to the address as the starting address.    #024 DWORD dwwritensize = 0; #025 BOOL bRet =:: WriteFile (Hfile,chbuffer,4,&dwwritensize,null);//character array inside The data is written to the memory area corresponding to the file handle. #026 if (bRet) #027 {#028//#029 OutputDebugString (_t ("WriteFile Write file succeeded/r/n")) 030} #031 #032//writes data written to the buffer to disk first. #033 flushfilebuffers (hfile), #034 #035//#036//Read data from the file. #037 LONG ldistance = 0; #038 DWORD dwptr = SetFilePointer (hfile, Ldistance, NULL, File_begin#039 if (dwptr = = Invalid_set_file_pointer) #040 {#041//Get error code.           #042 DWORD dwerror = GetLastError (); #043//processing error. #044} #045 #046 DWORD dwreadsize = 0; #047 bRet =:: ReadFile (Hfile,chbuffer,4,&dwreadsize,null); #048 if (bRet) #049 {#050//#051 OutputDebugString (_t ("ReadFile read file succeeded/r/n"); #0 else#054} #053 {#055//Get error code.           #056 DWORD dwerror = GetLastError (); #057//processing error.                #058 TCHAR cherrorbuf[1024]; #059 wsprintf (cherrorbuf,_t ("GetLastError () =%d/r/n"), dwerror); #060 OutputDebugString (CHERRORBUF); #061} #062 #063}*//* in the requirements of the software, it is very important to save the useful data. For example, daily stock market data need to be saved to generate candlestick chart. For example, the log of the game client needs to be saved so that when the client fails, it can send log back to analyze the cause of the error. For example, when a bank trades every day, it also needs to save all the transaction data to a file to be backed up for settlement. Also in the field of data acquisition is more need to save more data, such as from the DV to read video and voice data out, will generate 12G of giant files. For example, to read a DVD, the CD made into a virtual CD-ROM is also 9G in size. Therefore, createThe file is a very common feature, which is definitely mastered and will be used very well.  Of course, this CreateFile function can not only create files, but also can play serial, and port, network, USB devices and other functions.     The function CreateFile is declared as follows: Winbaseapi__outhandlewinapicreatefilea (__in LPCSTR lpfilename, __in DWORD dwdesiredaccess, __in DWORD dwShareMode, __in_opt lpsecurity_attributes lpsecurityattributes, __in DWORD Dwcreationdispos ition,//is the creation attribute __in DWORD dwflagsandattributes, __in_opt HANDLE htemplatefile); Winbaseapi__outhandlewinapicreatefilew (__in lpcwstr lpfilename,//is the name of the file or device __in DWORD dwdesiredaccess,//is an interview Q Property __in DWORD dwsharemode,//is a shared mode __in_opt lpsecurity_attributes lpsecurityattributes,//is a security attribute __in Dwo     RD dwcreationdisposition,//is a file template that creates properties __in DWORD dwflagsandattributes,//is a file flag and attributes __in_opt HANDLE htemplatefile// ); #ifdef unicode#define CreateFile createfilew#else#define CreateFile createfilea#endif//! Unicodelpfilename is the name of the file or device. dwDesiredAccess is the Access property. dwShareMode is a shared property. lpSecurityAttributes is a security attribute. dwCreationDisposition is the creation property. DwFlagsAndattributes are file flags and attributes. hTemplateFile is a file template. Examples of calling functions are: #001//Create files. #002//Cai Junsheng 2007/10/18 qq:9073204 shenzhen #003 void Createfiledemo (void) #004 {#005//#006 HANDLE hfile =:: Cre Atefile (_t ("CreateFileDemo.txt"),//name of the created file. #007 generic_write,//write files. #008 0,//do not share read/write. #009 NULL,//default security attribute. #010 Create_always,//If the file exists, also created.         #011 File_attribute_normal,//general documentation.                 #012 NULL); The template file is empty. #013 #014 if (hfile = = Invalid_handle_value) #015 {#016//#017 Outputdebugstrin G (_t ("CreateFile fail!/r/n")); #018} #019}*/

  

Serial communication Code. It was written by someone else, and I added some notes.

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.