串口通信握手与功率数据读取优化代码
private void ReadWriter()
{
string handshake = "?"; // 握手信号
string received = ""; // 接收到的数据
int count = 0; // 发送次数计数器
// 发送握手信号
serialPort.Write(handshake);
// 循环等待接收数据
while (count < 50)
{
// 暂停50毫秒
System.Threading.Thread.Sleep(50);
try
{
// 读取数据
received = serialPort.ReadExisting();
}
catch (Exception ex)
{
Send(ex.Message);
return;
}
// 判断是否握手成功
if (received.Contains("."))
{
// 发送T信号
for (int i = 0; i < 24; i++)
{
serialPort.Write("T");
System.Threading.Thread.Sleep(3);
}
// 暂停50毫秒
System.Threading.Thread.Sleep(50);
// 读取所有数据
string str = "";
try
{
str = serialPort.ReadExisting();
}
catch (Exception ex)
{
Send(ex.Message);
return;
}
// 查找匹配的波长
string match = arr.FirstOrDefault(x => str.IndexOf(x.ToString().Length == 3 ? "0" + x.ToString() : x.ToString()) >= 0);
if (match == null)
{
Send("功率波长错误,目前功率计,计算值的波长是:" + string.Join(",", arr.ToArray()) + ",请检查你的功率计波长是否正确,波长正确但未包含在目前计算的波长里,如果连续是这样,请联内网通联系蒋云开。");
return;
}
// 截取匹配波长前的数据
int index = str.IndexOf(match);
if (index < 5)
{
continue;
}
str = str.Substring(0, index == 0 ? str.Length - 0 : index);
// 根据最后一位数字计算功率值
switch (str[str.Length - 1])
{
case '2':
str = Replace(str.Insert(7 - 1, "."));
Send(str);
break;
case '3':
str = Replace(str.Insert(7 - 2, "."));
Send(str);
break;
case '4':
str = Replace(str.Insert(7 - 3, "."));
Send(str);
break;
case '5':
str = Replace(str.Insert(7 - 4, "."));
Send(str);
break;
default:
Send("计算功率值失败。");
return;
}
// 发送HO信号
serialPort.Write("HO");
return;
}
else
{
// 继续发送握手信号
serialPort.Write(handshake);
count++;
}
}
Send("握手失败。");
}
// 替换字符串中的空格和换行符
private string Replace(string str)
{
return str.Replace(" ", "").Replace("\n", "").Replace("\r", "");
}
// 发送消息
private void Send(string message)
{
// TODO: 发送消息
}
原文地址: http://www.cveoy.top/t/topic/jGPk 著作权归作者所有。请勿转载和采集!