我想阅读化学分析仪通过串行端口发送的消息。我写了下面的代码。它读取接收到的字节,但是在某些情况下,某些字节会合并,并且在消息中途会收到一组意外的字节。有什么方法可以等到消息结束并获得所有字节吗?
SerialPort com = new SerialPort();
List<byte> thisMessage = new List<byte>();
string status = "";
private void btnOpen_Click_1(object sender, EventArgs e){
btnOpen.Enabled = false;
btnClose.Enabled = true;
try
{
com.PortName = cmbPort.Text;
com.BaudRate = Int32.Parse(txtBaudRate.Text);
com.DataBits = Int32.Parse(txtBitLength.Text);
com.ReadBufferSize = 100000;
com.StopBits = StopBits.One;
com.DtrEnable = true;
com.RtsEnable = true;
com.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);
}
private void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytes = com.BytesToRead;
byte[] buffer = new byte[bytes];
com.Read(buffer, 0, bytes);
if (ContainEnd(buffer))
{
status += DateTime.Now.ToString("dd MMM yyyy hh:mm:ss tt") + " Message Received From Analyzer." + Environment.NewLine;
thisMessage.AddRange(buffer);
String ts = "";
foreach (byte b in thisMessage)
{
ts += b + " ";
}
status += ts + Environment.NewLine;
thisMessage = new List<byte>();
status += "End of a Message " + Environment.NewLine;
}
else
{
thisMessage.AddRange(buffer);
String ts = "";
foreach (byte b in buffer)
{
ts += b + " ";
}
status += DateTime.Now.ToString("dd MMM yyyy hh:mm:ss tt") + " Part of a Message " + ts + Environment.NewLine;
}
this.Invoke(new EventHandler(DisplayText));
}
运行此代码时,我得到的字节为5 2 2 194 77 181 48 105 94 在此消息的这一部分不希望字节2s。不能有194或181之类的字节。因此,我认为对字节的读取有误。
如何从串行端口获取正确的字节?