using Aitex.Core.Util; using MECF.Framework.Common.Communications; using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Sensors; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps { public class SensorTempConnection : SerialPortConnectionBase { private List _lstCacheBuffer = new List(); public SensorTempConnection(string portName) : base(portName, 115200, 8, System.IO.Ports.Parity.Even, System.IO.Ports.StopBits.One, "\r", false) { deviceTimer = new DeviceTimer(); } public DeviceTimer deviceTimer; private int ErrorCount = 0; public override bool SendMessage(byte[] message) { _lstCacheBuffer.Clear();//每次发送前清除接收区缓存 return base.SendMessage(message); } protected override MessageBase ParseResponse(byte[] rawMessage) { _lstCacheBuffer.AddRange(rawMessage);//持续添加通讯缓存 //验证最后一位是不是结束符\r if (rawMessage[rawMessage.Length - 1] != 13)//byte 13 是字符串\r,SerialPortConnectionBase通讯中添加结束符\r { var mes= IsTimeOut() ? ReceiveTempMessage(true, false, _lstCacheBuffer.ToArray()) : ReceiveTempMessage(false,false, _lstCacheBuffer.ToArray()); if (deviceTimer.IsIdle()) deviceTimer.Start(5000); return mes; } Reset();//复位状态和计数 return ReceiveTempMessage(false,true, _lstCacheBuffer.ToArray()); } public bool IsTimeOut() { if (deviceTimer.IsTimeout()) { deviceTimer.Stop(); ErrorCount += 1; if (ErrorCount >= 3) return true; return false; } return false; } private void Reset() { ErrorCount = 0; deviceTimer.Stop(); } private BinaryMessage ReceiveTempMessage(bool isError, bool isComplete, byte[] bytes) { BinaryMessage msg = new BinaryMessage(); msg.IsError = isError; msg.IsComplete = isComplete; msg.RawMessage = bytes; return msg; } } }