我从串行端口接收数据,并在多行文本框中显示这些数据。数据有一个起始标题(>)、一个标识符(“T”或“I”或“N”)和一个结束标题(<)。因此,完整的消息类似于 >T123< 或 >N456< 或 >I086<。txtOutput 中显示的数据以正确的形状出现 >T123< 每行即使在串行输出窗口中它们以这种方式出现:
>T22
0<\r\n
>T22
2<\r\n
>T22
2<\r\n
>T223<\r\n
>
T225<\r\n
>
T228<\r\n
....
我需要过滤这些数据以在 PID 中进行一些计算,并且我创建了一个类来去除标题和标识符。该类返回已经在不同变量(a、b、c)中排序的数据,准备用于其他计算。这是从串口接收数据并将数据附加到txtOutput中的方法,这很好。然后该方法将数据发送到类“ strp.Distri(invia , out a, out b, out c)”。
private void SetText(string text)
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.BeginInvoke(d, new object[] { text });
}
else
{
txtOutput.AppendText(text);
string a = "", b = "", c = "";
string invia = text.ToString();
Stripper strp = new Stripper();
strp.Distri(invia, out a, out b, out c);
textBox7.Text = a; //current
textBox2.Text = b; //temperature
textBox6.Text = c; //giri
这是我用来过滤和去除不必要字符的类。
class Stripper
{
public void Distri (string inComing, out string param1, out string param2, out string param3)
{
string current="";
string temperature="";
string numRPM="";
string f = inComing;
char firstChar = f[0];
char lastChar =f [f.Length - 1];
bool test1 =(firstChar.Equals('>'));
bool test2 =(lastChar.Equals('<'));
int messLenght = f.Length;
if (test1 == true && test2 == true && messLenght <=6)
{
f = f.Replace("<", "");
f = f.Replace(">", "");
if (f[0] == 'I')
{
string _current = f;
_current = _current.Replace("I", "");
current = _current;
}
else if (f[0] == 'T')
{
string _temperature = f;
_temperature = _temperature.Replace("T", "");
temperature = _temperature;
}
else if (f[0] == 'N')
{
string _numRPM = f;
_numRPM = _numRPM.Replace("N", "");
numRPM = _numRPM;
}
else
{}
}
else
{}
param1 = current;
param2 = temperature;
param3 = numRPM;
}
}
这是我的串行端口和关联的委托:
delegate void SetTextCallback(string text);
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
SetText(serialPort1.ReadExisting());
}
catch (Exception ex)
{
SetText(ex.ToString());
}
}
我的问题是 a、b 和 c 没有返回任何内容,因为“test1”和“test2”之后的消息显然不是真的,因为它们是分片接收的。我怎么解决这个问题?有没有办法在我将它们发送到剥离器类之前正确地重新组合这些消息?