Hi all,
Have been testing for 30 minutes at 50 packets per second (packet 19 bytes)and no data lost.
At higher speed I get an exception: System.InvalidOperationException occurred Message = Object is currently in use elsewhere. Source=System.Drawing
This is no problem for me as speed is 10 times higher than needed and has nothing to do with serial port.
Here is my modified serialport_Datareceived event:
private bool sync = false;
private void portCs_Datarecieived(object sender, SerialDataReceivedEventArgs e)
{
if (!comportCcs.IsOpen) return;
if (sync)
{
byte[] buffer = new byte[19];
int bytes = comportCcs.BytesToRead;
if (bytes > 18)
{
comportCcs.Read(buffer, 0, 19);
if (buffer[0] == stx && buffer[1] == dle && buffer[18] == etx)
{
sync = true;
CsreceivedBytes = new byte[19];
CsreceivedBytes = buffer;
processCsData(CsreceivedBytes);
}
else
{
comportCcs.DiscardInBuffer();
sync = false;
if (readBuffer.Count > 0) readBuffer = new List<byte>();
}
}
}
if (!sync)
{
while (comportCcs.BytesToRead > 0)
{
int indata = comportCcs.ReadByte();
if (indata == (int)stx && readBuffer.Count == 0)
{
readBuffer.Add((byte)indata);
indata = comportCcs.ReadByte();
}
else
{
comportCcs.DiscardInBuffer();
sync = false;
if (readBuffer.Count > 0) readBuffer = new List<byte>();
}
if (indata == (int)dle && readBuffer.Count == 1)
{
readBuffer.Add((byte)indata);
indata = comportCcs.ReadByte();
}
else
{
comportCcs.DiscardInBuffer();
sync = false;
if (readBuffer.Count > 0) readBuffer = new List<byte>();
}
while (readBuffer.Count > 1 && readBuffer.Count < 18)
{
readBuffer.Add((byte)indata);
indata = comportCcs.ReadByte();
}
if (readBuffer.Count == 18 && indata == (int)etx)
{
sync = true;
readBuffer.Add((byte)indata);
CsreceivedBytes = new byte[19];
CsreceivedBytes = readBuffer.ToArray();
processCsData(CsreceivedBytes);
readBuffer = new List<byte>();
}
else
{
sync = false;
readBuffer = new List<byte>();
}
}
}
}
I hope this can help others and +5 for Sergey, leading me in the right direction.
Regards,
GrooverFromHolland