Below I will issue a more detailed description: the handling of a serial port to my reference the CSerialPort class, because it feels CSerialPort class in receiving low efficiency, bad and how to deal with the modbus rtu protocol of a class, so I have modified will receive, in addition to write a serial port without the thread function, specific idea is: initialize serial port, establishing monitoring thread, read call WaitCommEvent function, this function returns FALSE, call GetLastError, if for IO_PENDING, into the WaitForSingleObject subsequent processing, if it is other, error handling, if WaitCommEvent returns TRUE, call ClearCommError cbInQue, if is 0, the continue (with CSerialPort), then the WaitForSingleObject blocking threads waiting, if for OBJECT_0, receive function called RecvChar processing, concrete is slightly different with the CSerialPort RecvChar processing, in the for (;; ) read one character at a time, in the buffer has been read, until cbInQue is 0, reoccupy Sleep wait 5 ms, if does not arrive subsequent characters, receiving and sending messages, and end (due to conclude that call RecvChar cbInQue must not to 0, for monitoring thread continue down to 0, and subsequent treatment with to even still awaiting judgment over 5 ms is 0, so the beginning to judge not cbInQue==0),
我的问题是,当我在一收一发的应用中,发现当我发送一帧查询命令,程序收到了两次通知接收的消息,第一条消息后,数据全部被接收,是完整的,第二次接收长度为0,按照程序的设想,在RecvChar处理过程中,后续字符可能到达,并置位EV_RXCHAR,和WaitForSingleObject中的事件,当从RecvChar返回监视线程,WaitCommEvent应该返回TRUE,并continue掉,根本不会发出第二条通知接收的消息,但是情况是第二条消息确实发出了,我猜测除非是这样一种情况:在调用RecvChar处理接收时,每调用一次ReadFile系统都清除一次EV_RXCHAR,由于在WINDOWS中EV_RXCHAR产生的次数总是等于或比接收到的字符数少(这点和单片机不同),这样在RecvChar返回时已经没有EV_RXCHAR了,只有WaitForSingleObject中的事件了(ReadFile并不复位这一事件),再返回监视线程时,调用WaitCommEvent结果是FALSE,转入WaitForSingleObject处理,触发了第二次读,因为缓冲区没有字符,所以仅触发了一次接收消息,由于没有找到EV_RXCHAR触发,复位的相关信息,所以不知道自己的猜测对不对,还望知道的回复一下!
CodePudding user response:
Search "Xon Xoff"CodePudding user response:
I said with flow control is not much, I didn't use thisCodePudding user response:
It is recommended to use CxSerial classhttp://www.cnblogs.com/EdmundDwyane/p/3161524.html
CodePudding user response:
A serial port to send and receive, the an habitSend - take the initiative to call
The receive - thread
In the main program constantly judge whether a frame to receive complete,
Using multi-level buffer, just receive, a ring buffer, the size is 2 ^ n bytes, generally is 64 k bytes, with an unsigned short variable as written to subscript,
For (the number of the receiving)
Buffer_level_1 [io_read + +]=the character of the receiving [I];
Level 1 store complete data
According to business requirements, and then set the level 2, or 3 buffer that sends a sometimes, more than will receive a response, then in grade 2 will be deposited into the frame of data, the general frame or in the threads, as long as io_read do not agree with io_recv, kept waiting in the thread,