Serial Communication and overlapping I/O

Source: Internet
Author: User
Serial Communication and overlapping I/O

Windows 32 extends the file concept. Whether it is a file, communication device, named pipe, mail slot, disk, or console, it is opened or created using the createfile () API function. The declaration of this function is:

Handle createfile (

Lptstr lpfilename, // file name

DWORD dwdesiredaccess, // Access Mode

DWORD dw1_mode, // share mode

Lpsecurity_attributes lpsecurityattributes, // usually null

DWORD dwcreationdistribution, // Creation Method

DWORD dwflagsandattributes, // file attributes and flag

Handle htemplatefile // temporary file handle, usually null

);

If the call is successful, the function returns the file handle. If the call fails, the function returns invalid_handle_value.


After the communication device handle is opened, you often need to initialize the serial port. This requires a DCB structure. The DCB structure contains information such as the baud rate, the number of data digits for each character, the parity and the number of stopped digits. When querying or configuring the properties of a serial port, the DCB structure is used as the buffer zone.

Call the getcommstate function to obtain the serial port configuration. This function fills the current configuration in a DCB structure. After using createfile to open a serial port, you can call the getcommstate function to obtain the initial configuration of the serial port. To modify the configuration of a serial port, you should first modify the DCB structure, and then call the setcommstate function to set the serial port with the specified DCB structure.

In addition to the settings in DCB, the program generally needs to set the size and timeout of the I/O buffer. Windows uses an I/O buffer to store input and output data of a serial port. If the communication speed is high, a large buffer zone should be set. You can call the setupcomm function to set the input and output buffer sizes of the serial port.

Timeout must be considered when readfile and writefile are used to read and write the serial port. If no specified number of characters are read or written within the specified time period, the readfile or writefile operation ends. To query the current timeout settings, call the getcommtimeouts function, which will fill in a commtimeouts structure. You can call setcommtimeouts to set the timeout value using the content of a commtimeouts structure.

There are two types of Timeout: interval timeout and total timeout. The interval timeout refers to the maximum latency between two characters at the time of receiving. The total timeout refers to the maximum time spent in read/write operations. Write operations only support total timeouts, while read Operations Support both timeouts. The commtimeouts structure can be used to specify the read/write operation timeout. The structure is defined:

Typedef struct _ commtimeouts {

DWORD readintervaltimeout; // read interval timeout

DWORD readtotaltimeoutmultiplier; // read time coefficient

DWORD readtotaltimeoutconstant; // read Time Constant

DWORD writetotaltimeoutmultiplier; // write time coefficient

DWORD writetotaltimeoutconstant; // write time constant

} Commtimeouts, * lpcommtimeouts;

Members of the commtimeouts structure are in milliseconds. The formula for calculating the total timeout is:

Total timeout = time coefficient × number of characters required to read/write + Time Constant

For example, if you want to read 10 characters, the formula for calculating the total read operation timeout is:
Total read timeout = readtotaltimeoutmultiplier × 10 + readtotaltimeoutconstant

It can be seen that the interval timeout and total timeout settings are irrelevant, which allows the communication program to flexibly set various timeout settings.

If all write timeout parameters are 0, write timeout is not used. If readintervaltimeout is 0, the read interval timeout is not used. If both readtotaltimeoutmultiplier and readtotaltimeoutconstant are 0, the total read timeout is not used. If the read interval time-out is set to maxdword and the total read time-out between the two is 0, the read operation is completed immediately after the content in the input buffer is read, regardless of whether the required characters are read.

When reading and writing a serial port in overlapping mode, although readfile and writefile may return before the operation is completed, the timeout still works. In this case, the timeout specifies the operation completion time, rather than the return time of readfile and writefile.

When readfile and writefile are used to read and write a serial port, they can be executed simultaneously or asynchronously. During synchronous execution, the function is not returned until the operation is complete. This means that the thread will be blocked during synchronous execution, resulting in lower efficiency. During overlapping operations, the called function returns immediately even if the operation is not completed. Time-consuming I/O operations are performed in the background so that threads can do other things. For example, a thread can execute I/O operations on different handles at the same time, or even perform read/write operations on the same handle at the same time. This is the meaning of the word "Overlap.

The readfile function completes the operation by reading a specified number of characters in the input buffer of a serial port. The writefile function not only needs to merge a specified number of characters into the output buffer, but also completes the operation after these characters are sent from the serial port.

Whether the readfile and writefile functions overlap is determined by the createfile function. If the file_flag_overlapped flag is specified when createfile is called to create a handle, the read and write operations on the handle by calling readfile and writefile overlap. If no overlap flag is specified, the read/write operations are synchronized.

The readfile and writefile functions have similar parameters and return values. Only the declaration of the readfile function is listed here:

Bool readfile (

Handle hfile, // file handle

Lpvoid lpbuffer, // read buffer

DWORD nnumberofbytestoread, // number of bytes to be read

Lpdword lpnumberofbytesread, // number of bytes actually read

Lpoverlapped // point to an overlapped Structure

); // If true is returned, the operation is successful.
 
Note that if the function is returned because of timeout, the return value is true. The lpoverlapped parameter should point to an overlapped structure during the overlap operation. If this parameter is null, the function will perform the synchronization operation, regardless of whether the handle is created by the file_flag_overlapped flag.

When readfile and writefile return false, the operation may not necessarily fail. The thread should call the getlasterror function to analyze the returned results. For example, if the operation is not completed before the overlapping operation, the function returns false, and the getlasterror function returns error_io_pending.

When overlapping I/O is used, the thread needs to create an overlapped structure for read/write functions. The most important member of the overlapped structure is hevent, which is an event object handle. The thread should use the createevent function to create a manual reset event for the hevent member. The hevent member will be used as the synchronization object of the thread. If the read/write function returns the result after the operation is not completed, set the hevent member to signal-free. After the operation is completed (including timeout), The hevent will become a signal.

If the getlasterror function returns error_io_pending, the overlap operation is still completed, and the thread can wait for the Operation to complete. There are two waiting Methods: one is to use a waiting function like waitforsingleobject to wait for the hevent Member of the overlapped structure. You can specify the waiting time and call getoverlappedresult after the function returns. Another method is to call the getoverlappedresult function to wait. If the bwait parameter of the function is set to true, the function waits for the hevent event of the overlapped structure. Getoverlappedresult returns an overlapped structure to report the overlapping operation results, including the actual transmitted bytes.

If the read/write operation times out, the hevent member will become a signal when the specified time is exceeded. Therefore, after a timeout occurs, both waitforsingleobject and getoverlappedresult end the wait. The dwmilliseconds parameter of waitforsingleobject specifies a wait timeout value. The actual wait time of this function is the minimum value of the two timeout values. Note that getoverlappedresult cannot set the waiting time limit. Therefore, if the hevent member does not have a signal, the function will keep waiting.

Before calling readfile and writefile, the thread should call the clearcommerror function to clear the error mark. This function is used to report specified errors and the current status of the device.

You can call the purgecomm function to terminate ongoing read/write operations. This function also clears the content in the input or output buffer.

 

Typedef struct_overlapped
{
DWORD internal;

DWORD internalhigh;

DWORD offset;

DWORD offsethigh;

Handle hevent;

} Overlapped;

Internal specifies the system-related status, which is retained for use by the operating system;
Internalhigh specifies the length of the transmitted data, which is retained by the operating system;
Offset specifies the file location from which data is transmitted. The file location is the byte offset relative to the start of the file. Before calling the readfile or writefile function, call the process to set this member. When the read/write name pipeline and communication device are called, the call process ignores this member;
Offsethigh specifies the high character of the byte offset of the data to be transmitted. When you read and write the named pipe and communication device, the calling process ignores this member;
The hevent identifies the event. When data transmission is complete, it is set to the signal state. before calling the readfile writefile connectnamedpipe transactnamedpipe function, the process is called to set this member.

Related functions: createevent resetevent getoverlappedresult waitforsingleobject cwinthread getlasterro.

 

This article from: http://hi.baidu.com/lovely_elle/blog/item/34c0628a2bdfe51ac9fc7ace.html

Thank you for sharing this article.

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.