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);
VulpesPosted Mar 22, 2014, 3:33 PM
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.handshake(v=vs.110).aspx
Failing that and assuming that no data is being skipped, I think you will have to assemble the bits of data and try and make sense of them.
Sometimes regular expressions can help with a task such as this and, if you're not familiar with these, I may be able to help with that.
SamPosted Mar 23, 2014, 1:33 AM
SamPosted Mar 22, 2014, 11:32 AM
VulpesPosted Mar 21, 2014, 9:43 AM
Instead, I'd use the number of bytes actually read when converting to a string:
//read the data and store it
int bytesRead = comPort.Read(comBuffer, 0, bytes);
//Convert the bytes stream to ascii
inData += Encoding.ASCII.GetString(comBuffer, 0, bytesRead);
If it's still no better, I'd experiment with the SerialPort.ReceivedBytesThreshold property which by default is set to 1.
This controls the number of bytes there needs to be in the input buffer before the DataReceived event is called. If data is being received quickly, it might be better to set this to a higher value to avoid the possibility that some events may be skipped or called out of order.