Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SerialData.Eof circumstances

Tags:

c#

.net-4.0

In my SerialPort.DataReceived event handler, I am checking for SerialData.Eof:

void DataReceived(object sender, SerialDataReceivedEventArgs e) {
    if (e.EventType == SerialData.Eof)
        throw new NotImplementedException("SerialData.Eof");
    // ... Read
}

In my entire development up to this point, I have never hit this exception. But today, when working on a different piece of the protocol, it hit.

My question is, what exactly does SerialData.Eof mean? MSDN says:

The end of file character was received and placed in the input buffer.

I'm dealing with binary data. What is the "end of file character"?


This MSDN Forum Post states that

the DCB.EofChar member always gets initialized to 0x1A (Ctrl+Z)

In the reference sources for the SerialStream class, at line 1343, we see that indeed:

dcb.EofChar = NativeMethods.EOFCHAR;

And in Microsoft.Win32.NativeMethods:

internal const byte EOFCHAR = (byte) 26; 

So does this mean anytime my device sends an 0x1A byte, that I will get a SerialData.Eof event? If that is the case, should I just stop testing for it altogether?

like image 890
Jonathon Reinhart Avatar asked Sep 18 '12 19:09

Jonathon Reinhart


1 Answers

My original analysis in that MSDN post was correct. However, the reference source reveals the answer, from SerialStream.cs:

dcb.EofChar = NativeMethods.EOFCHAR;

//OLD MSCOMM: dcb.EvtChar = (byte) 0;
// now changed to make use of RXFlag WaitCommEvent event => Eof WaitForCommEvent event
dcb.EvtChar = NativeMethods.EOFCHAR;

Ugh, they used the DCB's EvtChar setting to detect a Ctrl+Z. This was a Really Bad Idea, given that there's no way to change it and a 0x1a byte value can certainly appear in a binary protocol. In practice this almost always comes to a good end since there will be something to read when the event fires. Nevertheless, there's now a race condition that can fire another event, this time SerialData.Chars, with nothing to read since the previous event caused all bytes to be read. Which will make the Read() call block until a byte is available. Which usually works out but does increase the odds that the Close() call deadlocks. A chronic SerialPort problem.

The proper way to deal with this is:

void DataReceived(object sender, SerialDataReceivedEventArgs e) {
    if (e.EventType == SerialData.Eof) return;
    // ... Read
}
like image 186
Hans Passant Avatar answered Oct 11 '22 23:10

Hans Passant