Sam

Sam

  • NA
  • 166
  • 0

Serial port breaks messages

Mar 21 2014 8:45 AM
Hi, 
I read the serial port with various length and format messages in bytes.
Some messages that are of csv numerical data of interest enclosed within "FDDD" and "FEEE".
Short messages are fine, but when a long message arrives, more often than not the message is broken down into two streams, which makes it very difficult to parse.
I have the correct baud rate (115200 on both sides), increased the buffer size to significantly bigger than the message (8192), and all seems OK, except that the stream is not contiguous.
How can I make it 
contiguous ?
(Alternatively, I could try to combine the message parts, but this would be quite complex to make it 100% safe!).
Here is the code snippet:

public void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] dataRecord = new byte[4];
            if (!comPort.IsOpen) comPort.Open();
            string inData = "";     //The incoming string from port.
            holdPortOpen = true;  //Disable port closure.
          
                //retrieve number of bytes in the buffer
                int bytes = comPort.BytesToRead;
                //create a byte array to hold the awaiting data
                byte[] comBuffer = new byte[bytes];
                //read the data and store it
                comPort.Read(comBuffer, 0, bytes);
                //Convert the bytes stream to ascii 
                inData += Encoding.ASCII.GetString(comBuffer, 0, bytes);
              
                if (inData.Contains("FDDD") && inData.Contains("FEEE"))

                   mainForm.displayData(inData);
              

Answers (4)