首次上传

This commit is contained in:
hanqiangqiang
2026-06-15 10:56:30 +08:00
commit b0213b94d6
4160 changed files with 736101 additions and 0 deletions
@@ -0,0 +1,213 @@
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Xml;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public sealed class AETemp : TempSensorBase
{
private AETempConnection _connection;
private readonly R_TRIG _trigCommunicationError = new ();
private readonly R_TRIG _trigFewChannels = new ();
private readonly R_TRIG _trigMonitorExcepted = new ();
private readonly LinkedList<HandlerBase> _lstHandler = new ();
private readonly object _locker = new ();
private double[] _tempBuff;
/// <summary>
/// 设备通道启用
/// </summary>
private bool[] _channelInstalled;
public override bool IsConnected => _connection is { IsConnected: true };
public AETemp(string module, XmlElement node, string ioModule = "") : base(module, node, ioModule)
{
RTrigs.Add(_trigCommunicationError);
RTrigs.Add(_trigFewChannels);
RTrigs.Add(_trigMonitorExcepted);
}
private void QueryTemp()
{
lock (_locker)
{
_lstHandler.AddLast(new AETempReadCommandHandler(this, "OUT", "1"));
}
}
protected override bool HandleInitialize()
{
InitController();
_channelInstalled=new bool[MaxChannels];
for (int i = 0; i < _channelInstalled.Length; i++)
_channelInstalled[i] = SC.GetValue<bool>($"{ScBasePath}.{Name}.Channel{i+1}");
_tempBuff = new double[MaxChannels];
return true;
}
private void InitController()
{
Address = SC.GetStringValue($"{ScBasePath}.{Name}.Address");
_connection = new AETempConnection(Address);
_connection.EnableLog(IsEnableLog);
SC.RegisterValueChangedCallback($"TempSensors.EnableLogMessage", (obj) =>
{
_connection.EnableLog((bool)obj);
});
}
protected override double[] HandleReadTemp()
{
OnTimeQueryTemp();
return IsConnected ? _tempBuff : null;
}
protected void OnTimeQueryTemp()
{
try
{
_connection.MonitorTimeout();
if (!_connection.IsConnected || _connection.IsCommunicationError)
{
lock (_locker)
{
_lstHandler.Clear();
}
//只要断开,就进行连接
if (!_connection.Connect())
{
_trigCommunicationError.CLK = !_connection.IsConnected;
if (_trigCommunicationError.Q)
{
TempBasFunction.PM1PM2PostLog($"Can not connect with {_connection.Address}, {Module}.{Name}",EV.PostAlarmLog);
TempBasFunction.SetPm1Pm2IoForInterlock(true);
}
_connection.ForceClear();
Thread.Sleep(1000);//重连延时
}
else
{
//连接成功后不会再进入,所以也只是写入一次LOG
LOG.Write($"{Module} {Name} Connected");
EV.PostInfoLog(Module, $"{Name} Connected");
TempBasFunction.PM1PM2PostLog($"{Name} Connected", EV.PostInfoLog);
TempBasFunction.SetPm1Pm2IoForInterlock(false);
}
_trigCommunicationError.CLK = !_connection.IsConnected;
_connection.ForceClear();
}
else
{
lock (_locker)
{
if (_lstHandler.Count == 0)
QueryTemp();
if (_lstHandler.Count > 0 && !_connection.IsBusy)
{
var handler = _lstHandler.First.Value;
_lstHandler.RemoveFirst();
if (handler != null)
{
_connection.Execute(handler);
}
}
}
}
}
catch (Exception ex)
{
_trigMonitorExcepted.CLK = true;
if(_trigMonitorExcepted.Q)
LOG.Write(ex);
}
}
public void ParseCommandInfo(string command, string message)
{
try
{
switch (command)
{
case "OUT":
{
if (message != null)
{
if (message.Contains(" "))
{
var strs = message.Split(' ');
if (strs.Length > 0 )
{
//判断AE温度通道启用,和上位机设定通道启用,是否相同
if (strs.Length != _channelInstalled.Count(c => c == true))
{
_trigFewChannels.CLK = true;
if (_trigFewChannels.Q)
{
TempBasFunction.PM1PM2PostLog("AE Error: Too few channels.", EV.PostAlarmLog);
}
return;
}
//温度数组,根据通道是否屏蔽来赋值,
_trigFewChannels.RST = true;
for (int i = 0; i < strs.Length; i++)
{
if (_channelInstalled[i] == true)
{
_tempBuff[i] = float.Parse(strs[i]);
}
}
//温度连续多次不变化侦测
//TempInvariantCount = TempBasFunction.TempInvariantCount(TempDatasArray, out string tempInvariantData);
//_trigTempNoChange.CLK = TempInvariantCount >= TempInvariantCountMax ? true : false;
//if (_trigTempNoChange.Q)
//{
// TempBasFunction.PM1PM2PostLog($"{Name} {TempInvariantCount} temp no changeCount {tempInvariantData}", EV.PostWarningLog);
//}
}
}
}
}
break;
}
}
catch (Exception ex)
{
// ignored
}
}
public override void Reset()
{
_connection?.SetCommunicationError(false, "");
base.Reset();
}
public override void Terminate()
{
_connection.Disconnect();
}
}
}
@@ -0,0 +1,108 @@
using Aitex.Core.RT.Log;
using MECF.Framework.Common.Communications;
using System.Collections.Generic;
using System.Linq;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public class AETempMessage : BinaryMessage
{
public byte DeviceAddress { get; set; }
public byte FunctionCode { get; set; }
public byte Length { get; set; }
public byte[] Data { get; set; }
}
public class AETempAsciiMessage : AsciiMessage
{
public string Data { get; set; }
public string ErrorText { get; set; }
}
class AETempConnection : TCPPortConnectionBase
{
private List<byte> _lstCacheBuffer = new List<byte>();
public AETempConnection(string address) : base(address, "\r\n", true)
{
}
public override bool SendMessage(string message)
{
return base.SendMessage(message);
}
public override bool SendMessage(byte[] message)
{
_lstCacheBuffer.Clear();
return base.SendMessage(message);
}
protected override MessageBase ParseResponse(byte[] rawMessage)
{
_lstCacheBuffer.AddRange(rawMessage);
byte[] temps = _lstCacheBuffer.ToArray();
AETempMessage msg = new AETempMessage();
msg.IsResponse = false;
msg.IsAck = false;
msg.IsComplete = false;
msg.RawMessage = _lstCacheBuffer.ToArray();
if (temps.Length < 9) return msg;
msg.DeviceAddress = temps[6];
msg.FunctionCode = temps[7];
if (msg.FunctionCode == 0x03)
{
msg.Length = temps[8];
if (temps.Length != 9)
{
if (temps.Length < msg.Length + 9) return msg;
}
msg.Data = _lstCacheBuffer.Skip(9).Take(msg.Length).ToArray();
}
else
{
msg.Data = _lstCacheBuffer.ToArray();
}
msg.IsResponse = true;
msg.IsAck = true;
msg.IsComplete = true;
return msg;
}
protected override MessageBase ParseResponse(string rawText)
{
AETempAsciiMessage msg = new AETempAsciiMessage();
msg.RawMessage = rawText;
if (rawText.Length <= 0)
{
LOG.Error($"empty response");
msg.IsFormatError = true;
return msg;
}
//if (rawText.Length <= 4)
//{
// LOG.Error($"too short response");
// msg.IsFormatError = true;
// return msg;
//}
msg.Data = rawText.Replace("\r", "").Replace("\n", "");
if (msg.Data.ToUpper().StartsWith("ERR"))
{
var errorCodeString = msg.Data.ToUpper().Replace("ERR", "").Replace(" ", "");
int.TryParse(errorCodeString, out int errorCode);
if (errorCode > 0)
{
msg.ErrorText = errorCodeString;
msg.IsError = true;
}
}
msg.IsResponse = true;
msg.IsAck = true;
return msg;
}
}
}
@@ -0,0 +1,91 @@
using MECF.Framework.Common.Communications;
using System.Collections.Generic;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public class AETempHandler : HandlerBase
{
public AETemp Device { get; }
public string _command;
protected string _parameter;
protected AETempHandler(AETemp device, string command, string parameter)
: base(BuildMessage(command, parameter))
{
Device = device;
_command = command;
_parameter = parameter;
Name = command;
}
private static string _CH = "\t";
private static string _endLine = "\r";
private static string BuildMessage(string command, string parameter)
{
if (string.IsNullOrEmpty(parameter))
return command + _endLine;
else
return command +_CH + parameter + _endLine;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
AETempAsciiMessage response = msg as AETempAsciiMessage;
ResponseMessage = msg;
if (response.IsAck)
{
SetState(EnumHandlerState.Acked);
if (msg.IsError)
{
//Device.NoteError($"Command '{_command}' Error: {response.Data}:{ErrorString(response.ErrorText)}");
}
else
{
SetState(EnumHandlerState.Completed);
handled = true;
//Device.NoteError(null);
return true;
}
}
handled = false;
return false;
}
private static Dictionary<string, string> ErrorDict = new Dictionary<string, string>()
{
{"1","Invalid message" },
{"2","Number not found" },
{"3","Number Invalid" },
{"4","Parameter’s value not received" },
{"5","Command not possible" }
};
private static string ErrorString(string errorCode)
{
if (ErrorDict.ContainsKey(errorCode))
return ErrorDict[errorCode];
else
return "NotDefined error";
}
}
public class AETempReadCommandHandler : AETempHandler
{
public AETempReadCommandHandler(AETemp device, string command, string parameter)
: base(device, command, parameter)
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (base.HandleMessage(msg, out handled))
{
var result = msg as AETempAsciiMessage;
Device.ParseCommandInfo(_command, result.Data);
}
return true;
}
}
}
@@ -0,0 +1,275 @@
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using System;
using System.Linq;
using System.Threading;
using System.Xml;
using RTOverEthernetDevelopmentKit;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
/// 昂坤Viper-RTC测温数据交互流程简介
/// 1:上位机连接昂坤软件启动的服务器,昂坤服务器启用 工控机的IP + 53888固定端口,上位机连接服务器获取温度数据
/// 2:昂坤软件通过USB线连接主机盒子获取温度,上位机不用干预
/// 3:昂坤通讯特性,上位机发送一条指令后,服务器会一直安装设定频率,一直发送数据,上位机只接受就可以了
/// 4:上位机读取数据,通过昂坤提供的库,调用连接和数据获取方法
/// 5:断联分为昂坤软件服务器、USB两种断联和重连判断,例如:昂坤软件未打开或UBS线松动
/// 6:继承ITempData接口,上层使用接口获取数据,方便以后扩展测温硬件
/// <summary>
/// 昂坤Viper-RTC测温
/// </summary>
public class AKunTemp : TempSensorBase
{
#region Variables
private IROverEthernet _ir;
/// <summary>
/// 连接昂坤软件服务器
/// </summary>
private readonly R_TRIG _trigConnServiceError = new();
/// <summary>
/// 机箱USB断联
/// </summary>
private readonly R_TRIG _trigUSBDataError = new();
/// <summary>
/// 机箱USB重连
/// </summary>
private readonly R_TRIG _trigUSBDataOK = new();
private int _lastIntegTime;
#endregion Variables
#region Constructors
public AKunTemp(string module, XmlElement node, string ioModule = "") : base(module, node, ioModule)
{
RTrigs.Add(_trigConnServiceError);
RTrigs.Add(_trigUSBDataError);
RTrigs.Add(_trigUSBDataOK);
}
#endregion
#region Properties
private int Port { get; set; }
public override bool IsConnected => _ir.IsConnected;
#endregion
#region Methods
/// <summary>
/// 获取系统配置中的积分时间。
/// </summary>
/// <returns></returns>
private int GetScIntegrationTime()
{
var integrationTime = SC.GetValue<int>($"{ScBasePath}.{Name}.ControllerAverageTime"); // the minimum value should be 10ms.
if (integrationTime < 10)
integrationTime = 10;
return integrationTime;
}
public override bool Connect()
{
try
{
if (IsSimMode)
return true;
_ir.Init(Address, Port);
_ir.StopIR();
_lastIntegTime = GetScIntegrationTime();
_ir.SetIntegrationTime(_lastIntegTime);
_ir.StartIR();
return true;
}
catch (Exception ex)
{
return false;
}
}
private void Reconnect()
{
try
{
if (IsSimMode)
return;
_ir.Close();
}
catch
{
// ignored
}
finally
{
Connect();
}
}
protected override bool HandleInitialize()
{
InitAKunController();
return true;
}
private void InitAKunController()
{
if (IsSimMode)
return;
var data = SC.GetStringValue($"{ScBasePath}.{Name}.Address").Split(':');
Address = data[0];
Port = Convert.ToInt32(data[1]);
_ir = new IROverEthernet();
_trigUSBDataOK.CLK = true;//初始化重连信号
SC.RegisterValueChangedCallback($"{ScBasePath}.{Name}.ControllerAverageTime",
SetControllerAverageTime);
}
private void SetControllerAverageTime(object time)
{
if (IsSimMode)
return;
if (time != null && int.TryParse(time.ToString(), out var avt))
{
_ir.StopIR();
_ir.SetIntegrationTime(avt);
_ir.StartIR();
}
else
{
LOG.Error($"Unable to set {Name} controller average time, the parameter {time} is not a integer.");
}
}
private int _usbReConnCnt = 0;//接受数据失败次数
private double[] ReadTemp()
{
try
{
if (IsSimMode)
return null;
var allChannel = _ir.GetAllChannel();
//USB线断联和重连逻辑
{
//连接时使用次数报警,多次接收到空数据开始报警 ,此时发现正常连接时Count=0会出现,频率是几分钟出现一次
if (allChannel.FirstOrDefault(ch => ch == null || !ch.Any()) != null || // 某个通道没有数据
_ir.Current.Status != 0) //首次打开上位机时,测试昂坤软件打开且未连接USB时,Count一直大于0,所以此处添加厂商提供的属性值判断USB连接
{
_usbReConnCnt++;
if (_usbReConnCnt <= 10)
return null;
_trigUSBDataOK.CLK = false; //复位USB重连信号,
_trigUSBDataError.CLK = true;
if (_trigUSBDataError.Q)
TempBasFunction.PM1PM2PostLog(
$"Can not connect with {Name} From USB,Status:{_ir.Current.Status}",
EV.PostAlarmLog);
_usbReConnCnt = 0;
TempBasFunction.SetPm1Pm2IoForInterlock(true);
return null;
}
_trigUSBDataOK.CLK = true;
if (_trigUSBDataOK.Q)
{
TempBasFunction.PM1PM2PostLog($"Connect OK with {Name} From USB", EV.PostInfoLog);
_trigUSBDataError.RST = true;//复位USB断联信号
TempBasFunction.SetPm1Pm2IoForInterlock(false);
}
//有数据时必须复位
_usbReConnCnt = 0;
}
return allChannel.Select(ch => (double)ch.Average()).ToArray();
}
catch (Exception ex)
{
LOG.Write($"{Name} Read controller error, {ex}");
return null;
}
}
protected override double[] HandleReadTemp()
{
try
{
//判断昂坤软件服务器断联和重连逻辑
if (_ir.IsConnected)
return ReadTemp();
Reconnect();
if (!_ir.IsConnected)//昂坤软件的服务器未打开
{
_trigConnServiceError.CLK = true;
if (_trigConnServiceError.Q)
{
Thread.Sleep(2000);//不加延时软件刚启动可能不打印
TempBasFunction.PM1PM2PostLog($"AKun Temp Software Maybe Not Open {Address} {Name}", EV.PostAlarmLog);
TempBasFunction.SetPm1Pm2IoForInterlock(true);
}
}
else//连接成功后不会再进入,只会提示一次
{
_trigConnServiceError.RST = true;
TempBasFunction.PM1PM2PostLog($"Connect OK with AKun Temp Software Form {Address} {Name}", EV.PostInfoLog);
TempBasFunction.SetPm1Pm2IoForInterlock(false);
}
Thread.Sleep(1000);
return null;
}
catch (Exception ex)
{
if (_trigConnServiceError.Q)
{
TempBasFunction.PM1PM2PostLog($"{this} Unable to read data from viper RTC, {ex.Message}", EV.PostAlarmLog);
}
return null;
}
}
public override void Terminate()
{
try
{
if (IsSimMode)
return;
_ir.Close();
}
catch (Exception ex)
{
LOG.Write(ex);
}
}
public override bool Disconnect()
{
Terminate();
return true;
}
#endregion
}
}
@@ -0,0 +1,417 @@
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Threading;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.P116PIDTC
{
public class AdressInfo
{
public string Name { get; set; }
public byte DeviceAddress { get; set; }
public int UnitAddress { get; set; }
public int Length { get; set; }
public int Data;
public string Remark { get; set; }//H3-N2-H4-N5-H6(H3代表连续3个地址有数据,N2代表H3与H4中间有两个地址为预留)
}
public class P116PIDTC : BaseDevice, IConnection,IDevice
{
private P116PIDTCConnection _connection;
private bool _activeMonitorStatus;
private int _errorCode;
private R_TRIG _trigCommunicationError = new R_TRIG();
private R_TRIG _trigRetryConnect = new R_TRIG();
private PeriodicJob _thread;
//private int tempCount = 1;
private LinkedList<HandlerBase> _lstHandler = new LinkedList<HandlerBase>();
private object _locker = new object();
private bool _enableLog = true;
private string _scRoot;
//private int _actualTempValue = 999;
//private int _settingTempValue = 888;
public int moduleCount { get; set; }
private int _tempWarningMaxDiff = 1; //报警最大温度(实际温度与设定温度之间的差值)
//private R_TRIG[] TempWarningTrig = new R_TRIG[12]; //温度报警
//string[] WarningInfo = new string[12] { "HeatTMAPanel","HeatTCSPanel","OuterPanel","MidPanel","InnerPanel","HeatShowerOuter", "HeatShowerInner", "HeatShowerMid", "HeatDptPanel","HeatLeakSource","HeatLeakBypass","HeatDptGate"};
//public float[] ActualTemp = new float[12];
//public float[] SettingTemp = new float[12];
public float fPVInValue, fTargetSP;
public int iAM = -1;
public string Address
{
get; set;
}
public bool IsConnected
{
get
{
return _connection != null && _connection.IsConnected;
}
}
public bool Connect()
{
return true;
}
public bool Disconnect()
{
return true;
}
public P116PIDTC(string module, string name, string scRoot) : base(module, name, name, name)
{
_scRoot = scRoot;
_activeMonitorStatus = true;
}
~P116PIDTC()
{
_connection.Disconnect();
}
public void QueryTemp()
{
_lstHandler.AddLast(new P116PIDTCQueryHandler(this, "QueryPVInValue", 0x01, 0x00, 0x01, 0x00, 0x01));
_lstHandler.AddLast(new P116PIDTCQueryHandler(this, "QueryTargetSP", 0x01, 0x00, 0x02, 0x00, 0x01));
_lstHandler.AddLast(new P116PIDTCQueryHandler(this, "QueryAM", 0x01, 0x01, 0x11, 0x00, 0x01));
}
public void ResetDevice()
{
}
public void QueryError()
{
EV.PostInfoLog(Module, "Query error");
}
public bool Initialize()
{
// string portName = SC.GetStringValue($"{_scRoot}.{Module}.{Name}.Address");
string portName =SC.GetStringValue($"{Name}.Address");
Address = portName;
//int address = SC.GetValue<int>($"{_scRoot}.{Name}.DeviceAddress");
moduleCount= SC.GetValue<int>($"{Name}.Modules");
_enableLog = SC.GetValue<bool>($"{Name}.EnableLogMessage");
_connection = new P116PIDTCConnection(portName);
_connection.EnableLog(_enableLog);
_tempWarningMaxDiff = SC.GetValue<int>($"{Name}.TempWarnMaxDiff");
//
fPVInValue = fTargetSP = 0.0f;
iAM = -1;
int count = SC.ContainsItem("System.ComPortRetryCount") ? SC.GetValue<int>("System.ComPortRetryCount") : 5;
int sleep = SC.ContainsItem("System.ComPortRetryDelayTime") ? SC.GetValue<int>("System.ComPortRetryDelayTime") : 2;
if (sleep <= 0 || sleep > 10)
sleep = 2;
int retry = 0;
do
{
_connection.Disconnect();
Thread.Sleep(sleep * 1000);
if (_connection.Connect())
{
EV.PostInfoLog(Module, $"{Name} connected");
break;
}
if (count > 0 && retry++ > count)
{
LOG.Write($"Retry connect {Module}.{Name} stop retry.");
EV.PostAlarmLog(Module, $"Can't connect to {Module}.{Name}.");
break;
}
Thread.Sleep(sleep * 1000);
LOG.Write($"Retry connect {Module}.{Name} for the {retry + 1} time.");
} while (true);
_thread = new PeriodicJob(200, OnTimer, $"{Module}.{Name} MonitorHandler", true);
DATA.Subscribe($"{Module}.{Name}.PVInValue", () => fPVInValue);
DATA.Subscribe($"{Module}.{Name}.TargetSP", () => fTargetSP) ;
DATA.Subscribe($"{Module}.{Name}.AM", () => iAM);
OP.Subscribe($"{Module}.{Name}.WritePVInValue", SetPVInValue);
OP.Subscribe($"{Module}.{Name}.WriteTargetSP", SetTargetSP);
OP.Subscribe($"{Module}.{Name}.WriteAM", SetAM); //0-Auto,1-Manual,2-Off
ConnectionManager.Instance.Subscribe($"{Name}", this);
return true;
}
public int _connecteTimes { get; set; }
private bool OnTimer()
{
try
{
_connection.MonitorTimeout();
if (!_connection.IsConnected || _connection.IsCommunicationError)
{
lock (_locker)
{
_lstHandler.Clear();
}
_trigRetryConnect.CLK = !_connection.IsConnected;
if (_trigRetryConnect.Q)
{
_connection.SetPortAddress(SC.GetStringValue($"{Name}.Address"));
if (!_connection.Connect())
{
EV.PostAlarmLog(Module, $"Can not connect with {_connection.Address}, {Module}.{Name}");
}
else
{
//重连成功后将TargetSP设置为0
SetTargetSP("WriteTargetSP", new object[] { 0 });
}
}
if (_connecteTimes++ < 3)
_connection.ForceClear();
else _connecteTimes= 4;
return true;
}
HandlerBase handler = null;
//if (!_connection.IsBusy)
//{
lock (_locker)
{
if (_lstHandler.Count == 0 && !IsConfig)
QueryTemp();
if (_lstHandler.Count > 0 && !_connection.IsBusy)
{
handler = _lstHandler.First.Value;
_lstHandler.RemoveFirst();
if (handler != null)
{
_connection.Execute(handler);
}
}
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
return true;
}
internal void NoteError()
{
}
public void Monitor()
{
try
{
_connection.EnableLog(_enableLog);
if (_connecteTimes < 4) return;
_trigCommunicationError.CLK = _connection.IsCommunicationError;
if (_trigCommunicationError.Q)
{
fPVInValue = 0f;
fTargetSP = 0f;
iAM = -1;
EV.PostAlarmLog(Module, $"{Module}.{Name} communication error, {_connection.LastCommunicationError}");
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
}
public bool IsConfig { get; set; }
public bool SetPVInValue(string cmd, object [] obj)//设置单个地址 0x0001
{
IsConfig = true;
_lstHandler.Clear();
lock (_locker)
{
if (obj.Length > 0)
{
byte DeviceAddress = 0x01;
int adress = 0x0001;
byte addressH = Convert.ToByte((adress >> 8) & 0xff); ;
byte addressL = Convert.ToByte(adress & 0xff);
//var floatdata = Convert.ToSingle(objs[1]) * 10;
//var data = Convert.ToInt16(floatdata);
var data = Convert.ToInt16(obj[0]);
byte dataH = Convert.ToByte((data >> 8) & 0xff);
byte dataL = Convert.ToByte(data & 0xff);
_lstHandler.AddLast(new P116PIDTCWriteSingleHandler(this, "WritePVInValue", DeviceAddress, addressH, addressL, dataH, dataL));
}
}
return true;
}
public bool SetTargetSP(string cmd, object[] obj)//设置单个地址 0x0002
{
IsConfig = true;
_lstHandler.Clear();
lock (_locker)
{
if (obj.Length > 0)
{
byte DeviceAddress = 0x01;
int adress = 0x0002;
byte addressH = Convert.ToByte((adress >> 8) & 0xff); ;
byte addressL = Convert.ToByte(adress & 0xff);
var data = Convert.ToInt16(obj[0]) * 10;//10倍值
byte dataH = Convert.ToByte((data >> 8) & 0xff);
byte dataL = Convert.ToByte(data & 0xff);
_lstHandler.AddLast(new P116PIDTCWriteSingleHandler(this, "WriteTargetSP", DeviceAddress, addressH, addressL, dataH, dataL));
}
}
return true;
}
public bool SetAM(string cmd, object[] obj)//设置单个地址 0x0111 = 273
{
IsConfig = true;
_lstHandler.Clear();
lock (_locker)
{
if (obj.Length > 0)
{
byte DeviceAddress = 0x01;
int adress = 0x0111;
byte addressH = Convert.ToByte((adress >> 8) & 0xff); ;
byte addressL = Convert.ToByte(adress & 0xff);
var data = Convert.ToInt16(obj[0]);
if (data == 0)
{
//开启自动
byte dataH = Convert.ToByte((data >> 8) & 0xff);
byte dataL = Convert.ToByte(data & 0xff);
_lstHandler.AddLast(new P116PIDTCWriteSingleHandler(this, "WriteAM", DeviceAddress, addressH, addressL, dataH, dataL));
}
else if(data == 2)
{
//关闭输出
//A-M:address 273
data = 0x1;
byte dataH = Convert.ToByte((data >> 8) & 0xff);
byte dataL = Convert.ToByte(data & 0xff);
_lstHandler.AddLast(new P116PIDTCWriteSingleHandler(this, "WriteAM", DeviceAddress, addressH, addressL, dataH, dataL));
//OP: address 3
adress = 0x0003;
addressH = Convert.ToByte((adress >> 8) & 0xff); ;
addressL = Convert.ToByte(adress & 0xff);
data = 0x0;
dataH = Convert.ToByte((data >> 8) & 0xff);
dataL = Convert.ToByte(data & 0xff);
_lstHandler.AddLast(new P116PIDTCWriteSingleHandler(this, "WriteAM", DeviceAddress, addressH, addressL, dataH, dataL));
}
else
{
EV.PostWarningLog(Module, "Find wrong parameter when writing AM.");
}
}
}
return true;
}
public void Reset()
{
_connecteTimes = 0;
_connection.SetCommunicationError(false, "");
_trigCommunicationError.RST = true;
_enableLog = SC.GetValue<bool>($"{Name}.EnableLogMessage");
_trigRetryConnect.RST = true;
}
public void RespondAbnormal(int funcode, int abnormalcode)
{
if (funcode == 0x83)
{
foreach (var code in AbnormalCode)
{
if (code.Key == abnormalcode)
EV.PostWarningLog(Name, $"Query Abnormal:{code.Value}");
}
}
if (funcode == 0x90 || funcode == 0x86)
{
foreach (var code in AbnormalCode)
{
if (code.Key == abnormalcode)
EV.PostWarningLog(Name, $"Write Abnormal:{code.Value}");
}
}
}
public Dictionary<int, string> AbnormalCode = new Dictionary<int, string>()
{
{ 1,"ncorrect function code, this machine does not correspond to the function code." },
{ 2,"Incorrect data address" },
{ 3,"Incorrect data." },
{ 4,"operation error" },
};
public void SetActiveMonitor(bool active)
{
_activeMonitorStatus = active;
}
public void SetErrorCode(int errorCode)
{
_errorCode = errorCode;
}
public void Terminate()
{
_connection.Disconnect();
}
}
}
@@ -0,0 +1,82 @@
using MECF.Framework.Common.Communications;
using System.Collections.Generic;
using System.Linq;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.P116PIDTC
{
public class P116PIDTCMessage : BinaryMessage
{
public byte DeviceAddress { get; set; }
public byte FunctionCode { get; set; }
public byte Length { get; set; }
public byte[] Data { get; set; }
}
public class P116PIDTCConnection:SerialPortConnectionBase
{
private List<byte> _lstCacheBuffer = new List<byte>();
public P116PIDTCConnection(string portName) : base(portName, 9600, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One, "\n", false)
{
}
public override bool SendMessage(byte[] message)
{
_lstCacheBuffer.Clear();
return base.SendMessage(message);
}
protected override MessageBase ParseResponse(byte[] rawMessage)
{
_lstCacheBuffer.AddRange(rawMessage);
byte[] temps = _lstCacheBuffer.ToArray();
P116PIDTCMessage msg = new P116PIDTCMessage();
msg.IsResponse = false;
msg.IsAck = false;
msg.IsComplete = false;
msg.RawMessage = _lstCacheBuffer.ToArray();
if (temps.Length < 4) return msg;
msg.DeviceAddress = temps[0];
msg.FunctionCode = temps[1];
if (msg.FunctionCode !=0x03)
{
msg.Data = _lstCacheBuffer.ToArray();
}
else
{
msg.Length = temps[2];
if (temps.Length < msg.Length + 5)
{
//msg.IsFormatError = true;
return msg;
}
msg.Data = _lstCacheBuffer.Skip(3).Take(msg.Length).ToArray();
}
msg.IsResponse = true;
msg.IsAck = true;
msg.IsComplete = true;
return msg;
}
private static byte ModRTU_CRC(byte[] buffer)
{
//ushort crc = 0xFFFF;
// var buf = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, buffer));
var buf = buffer;
var len = buffer.Length;
byte temp = buffer[0];
for (int i = 1; i < buffer.Length; i++)
{
temp = (byte)(temp ^ buffer[i]);
}
return (byte)~temp;
}
}
}
@@ -0,0 +1,166 @@
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.P116PIDTC
{
public abstract class P116PIDTCHandler : HandlerBase
{
public P116PIDTC Device { get; }
protected P116PIDTCHandler(P116PIDTC device, byte[] commandvalue)
: base(BuildMessage(commandvalue))
{
Device = device;
}
private static byte[] BuildMessage(byte[] commandvalue)
{
byte[] crc = ModRTU_CRC(commandvalue);
List<byte> result = commandvalue.ToList();
foreach (byte b in crc)
{
result.Add(b);
}
return result.ToArray();
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as P116PIDTCMessage;
ResponseMessage = msg;
handled = true;
return true;
}
private static byte[] ModRTU_CRC(byte[] buffer)
{
ushort crc = 0xFFFF;
// var buf = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, buffer));
var buf = buffer;
var len = buffer.Length;
for (var pos = 0; pos < len; pos++)
{
crc ^= buf[pos]; // XOR byte into least sig. byte of crc
for (var i = 8; i != 0; i--)
// Loop over each bit
if ((crc & 0x0001) != 0)
{
// If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
{
crc >>= 1; // Just shift right
}
}
// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
return BitConverter.GetBytes(crc);
}
}
public class P116PIDTCQueryHandler : P116PIDTCHandler
{
public P116PIDTCQueryHandler(P116PIDTC device,string name, byte groupAddress,byte offerHigh,byte offerLow,byte dataHigh,byte dataLow)
: base(device, new byte[] { groupAddress, 3, offerHigh, offerLow, dataHigh, dataLow })
{
Name = name;//"Query Temp";
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as P116PIDTCMessage;
handled = false;
if (!result.IsResponse) return true;
short rvalue = 0;
rvalue = (short)(rvalue ^ result.Data[0]);
rvalue = (short)(rvalue << 8);
rvalue = (short)(rvalue ^ result.Data[1]);
//if(Name.Contains("Actual"))
//Device.ActualTemp = rvalue;
//else
//Device.SettingTemp = rvalue;
if (Name.Contains("QueryPVInValue"))
{
Device.fPVInValue =Convert.ToSingle(rvalue)/10;
}
else if(Name.Contains("QueryTargetSP"))
{
Device.fTargetSP = Convert.ToSingle(rvalue)/10;
}
else if (Name.Contains("QueryAM"))
{
Device.iAM = Convert.ToInt32(rvalue);
}
else
{
}
Device._connecteTimes = 0;
ResponseMessage = msg;
handled = true;
Thread.Sleep(500);
return true;
}
}
public class P116PIDTCWriteSingleHandler : P116PIDTCHandler
{
public P116PIDTCWriteSingleHandler(P116PIDTC device, string name, byte groupAddress, byte offerHigh, byte offerLow, byte dataHigh, byte dataLow)
: base(device, new byte[] { groupAddress, 0x06, offerHigh, offerLow, dataHigh, dataLow })
{
Name = name;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as P116PIDTCMessage;
handled = false;
if (!result.IsResponse) return true;
if (result.FunctionCode == 0x86)
{
Device.RespondAbnormal(result.FunctionCode, result.Data[2]);
}
ResponseMessage = msg;
handled = true;
Device.IsConfig = false;
Thread.Sleep(1000);
return true;
}
}
public class P116PIDTCWriteHandler : P116PIDTCHandler
{
public P116PIDTCWriteHandler(P116PIDTC device, string name,byte groupAddress, byte offerHigh, byte offerLow,byte unitH,byte unitL,byte length, byte dataHigh, byte dataLow)
: base(device, new byte[] { groupAddress, 0x10, offerHigh, offerLow, unitH, unitL, length, dataHigh, dataLow })
{
Name = name;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as P116PIDTCMessage;
handled = false;
if (!result.IsResponse) return true;
if (result.FunctionCode == 0x90)
{
Device.RespondAbnormal(result.FunctionCode, result.Data[2]);
}
ResponseMessage = msg;
handled = true;
Device.IsConfig = false;
Thread.Sleep(1000);
return true;
}
}
}
@@ -0,0 +1,23 @@
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps;
/// <summary>
/// 温度滤波器类型枚举。
/// </summary>
public enum FilterTypes
{
/// <summary>
/// 无滤波
/// </summary>
None,
/// <summary>
/// 移动平均滤波
/// </summary>
MAF,
/// <summary>
/// 卡尔曼滤波
/// </summary>
Kalman
}
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using Aitex.Core.RT.Log;
using Aitex.Core.Util;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.Filters
{
public abstract class FilterBase : IFilter, IDisposable
{
#region Variables
private const int MAX_BUFFER_SIZE = 100000;
private readonly R_TRIG _rTrigFilterError = new();
protected readonly string ScBase;
protected readonly Queue<TempPoint> DataBuffer = [];
#endregion
public FilterBase(string module, string filterName, string scBasePath)
{
Module = module;
FilterName = filterName;
ScBase = scBasePath;
}
public string Module { get; }
public string FilterName { get; }
public virtual bool Initialize(out string reason)
{
reason = "";
return true;
}
public virtual double Update(double data)
{
if (DataBuffer.Count >= MAX_BUFFER_SIZE)
DataBuffer.Dequeue();
DataBuffer.Enqueue(new TempPoint(data));
try
{
var ret = HandleFilter(data);
_rTrigFilterError.CLK = false;
return ret;
}
catch (Exception ex)
{
_rTrigFilterError.CLK = true;
if(_rTrigFilterError.Q)
LOG.Error($"{FilterName} Filter error, {ex.Message}", ex);
return data;
}
}
public virtual void Reset()
{
DataBuffer.Clear();
_rTrigFilterError.RST = true;
}
protected virtual double HandleFilter(double lastTemp)
{
throw new NotImplementedException();
}
public void Dispose()
{
DataBuffer?.Clear();
}
}
}
@@ -0,0 +1,9 @@
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.Filters
{
public interface IFilter
{
double Update(double temp);
void Reset();
}
}
@@ -0,0 +1,235 @@
using System;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.Filters
{
public class KalmanFilter : FilterBase
{
private const double INIT_TEMP = 600.0;
private bool _isInitialized = false;
private double[,] F;
private double[,] H;
private double[,] Q;
private double[,] P;
private double[] x;
public KalmanFilter(string module, string filterName, string scBasePath, double pollIntervalMs)
: base(module, filterName, scBasePath)
{
Dt = pollIntervalMs / 1000.0;
}
public double Dt { get; }
public double R { get; private set; }
public double QScale { get; private set; }
public (double temp, double rate) LastTempRate { get; private set; }
public override bool Initialize(out string reason)
{
reason = "";
DATA.Subscribe($"{FilterName}.R", () => R);
DATA.Subscribe($"{FilterName}.QScale", () => QScale);
DATA.Subscribe($"{FilterName}.DeltaT", () => Dt);
var scName = $"{ScBase}.R";
R = SC.SafeGetValue(scName, 0d);
SC.RegisterValueChangedCallback(scName, value =>
{
if (value is not double rValue)
LOG.Warning($"{scName} Invalid value for Kalman R: '{value}', expected an double value.");
else if (R != rValue)
{
R = rValue;
Reset();
}
});
scName = $"{ScBase}.QScale";
QScale = SC.SafeGetValue(scName, 0d);
SC.RegisterValueChangedCallback(scName, value =>
{
if (value is not double qValue)
LOG.Warning($"{scName} Invalid value for Kalman QScale: '{value}', expected an double value.");
else if(QScale != qValue)
{
QScale = qValue;
Reset();
}
});
// 移除对Dt的重新获取,使用构造函数传入的值
// 如果需要从SC获取Dt,可以取消注释下面的代码
/*
scName = $"TempSensors.PollInterval";
Dt = SC.GetValue(scName, 1000) / 1000.0; // Convert milliseconds to seconds
SC.RegisterValueChangedCallback(scName, value =>
{
if (value is double dtValue && Dt != dtValue)
{
Dt = dtValue / 1000; // Convert milliseconds to seconds
Reset();
}
else
LOG.Warning($"{FilterName} Invalid value for Kalman Dt: {value}. Expected an double.");
});
*/
Reset();
return true;
}
public void InitializeForUnitTest(double r, double qScale)
{
R = r;
QScale = qScale;
Reset();
}
protected override double HandleFilter(double lastTemp)
{
if (!_isInitialized)
{
x[0] = lastTemp;
x[1] = 0;
_isInitialized = true;
LastTempRate = (x[0], x[1]);
return LastTempRate.temp;
}
// ---------- 预测 ----------
var xPred = MatMul(F, x);
var FP = MatMul(F, P);
var FPFt = MatMul(FP, F, transposeA: false, transposeB: true);
var PPred = Add(FPFt, Q);
// ---------- 更新 ----------
double[] y = [lastTemp - Dot(H, xPred)]; // 残差
// 修正S和K的计算过程
var PPred_Ht = MatMul(PPred, [H[0, 0], H[0, 1]]);
var S = H[0, 0] * PPred_Ht[0] + H[0, 1] * PPred_Ht[1] + R;
var K = new[] { PPred_Ht[0] / S, PPred_Ht[1] / S };
// 状态更新
x[0] = xPred[0] + K[0] * y[0];
x[1] = xPred[1] + K[1] * y[0];
// 协方差更新
var KH = new[,]
{
{ K[0] * H[0,0], K[0] * H[0,1] },
{ K[1] * H[0,0], K[1] * H[0,1] }
};
var I_KH = Subtract(Identity(2), KH);
P = MatMul(I_KH, PPred);
LastTempRate = (x[0], x[1]);
return LastTempRate.temp;
}
public override void Reset()
{
base.Reset();
// 状态转移矩阵
F = new[,]
{
{ 1, Dt },
{ 0, 1 }
};
// 观测矩阵
H = new double[,] { { 1, 0 } };
// 过程噪声协方差
Q = new[,]
{
{ QScale * Math.Pow(Dt, 4) / 4, QScale * Math.Pow(Dt, 3) / 2 },
{ QScale * Math.Pow(Dt, 3) / 2, QScale * Math.Pow(Dt, 2) }
};
P = new double[,]
{
{ 1, 0 },
{ 0, 1 }
};
x = [0, 0];
//x[0] = INIT_TEMP;
//x[1] = 0;
_isInitialized = false;
}
#region Util Methods
private static double[] MatMul(double[,] A, double[] x)
{
return
[
A[0, 0] * x[0] + A[0, 1] * x[1],
A[1, 0] * x[0] + A[1, 1] * x[1]
];
}
private static double[,] MatMul(double[,] A, double[,] B, bool transposeA = false, bool transposeB = false)
{
var rows = transposeA ? A.GetLength(1) : A.GetLength(0);
var cols = transposeB ? B.GetLength(0) : B.GetLength(1);
var shared = transposeA ? A.GetLength(0) : A.GetLength(1);
var result = new double[rows, cols];
for (var i = 0; i < rows; i++)
for (var j = 0; j < cols; j++)
for (var k = 0; k < shared; k++)
result[i, j] +=
(transposeA ? A[k, i] : A[i, k]) *
(transposeB ? B[j, k] : B[k, j]);
return result;
}
private static double Dot(double[,] H, double[] x)
{
return H[0, 0] * x[0] + H[0, 1] * x[1];
}
private static double[,] Add(double[,] A, double[,] B)
{
int rows = A.GetLength(0), cols = A.GetLength(1);
var result = new double[rows, cols];
for (var i = 0; i < rows; i++)
for (var j = 0; j < cols; j++)
result[i, j] = A[i, j] + B[i, j];
return result;
}
private static double[,] Subtract(double[,] A, double[,] B)
{
int rows = A.GetLength(0), cols = A.GetLength(1);
var result = new double[rows, cols];
for (var i = 0; i < rows; i++)
for (var j = 0; j < cols; j++)
result[i, j] = A[i, j] - B[i, j];
return result;
}
private static double[,] Identity(int n)
{
var result = new double[n, n];
for (var i = 0; i < n; i++)
result[i, i] = 1;
return result;
}
#endregion
}
}
@@ -0,0 +1,93 @@
using System;
using System.Linq;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.Filters
{
public class MoveAverageFilter : FilterBase
{
#region Variables
private readonly R_TRIG _rTrigFilterError = new R_TRIG();
#endregion
#region Constructor
public MoveAverageFilter(string module, string filterName, string scBasePath)
: base(module, filterName, scBasePath)
{
}
#endregion
#region Properties
public int WindowSize { get; set; }
#endregion
public override bool Initialize(out string reason)
{
reason = string.Empty;
DATA.Subscribe($"{FilterName}.WindowSize", () => WindowSize);
var scName = $"{ScBase}.WindowSize";
WindowSize = SC.GetValue(scName, 0);
SC.RegisterValueChangedCallback(scName, value =>
{
if(value is int winSize)
WindowSize = winSize;
else
LOG.Warning($"{FilterName} Invalid value for MAF WindowSize: {value}. Expected an integer.");
});
return true;
}
protected override double HandleFilter(double lastTemp)
{
// make sure that minimal window size is 1.
if (WindowSize < 0)
WindowSize = 0;
var lastData = DataBuffer.LastOrDefault();
if (lastData == null)
throw new NullReferenceException("Unable to find last temp data in DataBuffer.");
try
{
if (WindowSize <= 0)
return lastData.Value;
var filterRange = lastData.TimeStamp - TimeSpan.FromMilliseconds(WindowSize).Ticks;
var filteredTemp = lastData.Value;
// Remove old data points that are outside the filter range
while (DataBuffer.Count > 0 && DataBuffer.Peek().TimeStamp < filterRange)
DataBuffer.Dequeue();
var ave = DataBuffer.Average(x => x.Value);
if (!double.IsNaN(ave) && !double.IsInfinity(ave))
filteredTemp = ave;
_rTrigFilterError.CLK = false;
return filteredTemp;
}
catch (Exception ex)
{
_rTrigFilterError.CLK = true;
if (_rTrigFilterError.Q)
LOG.Error($"{FilterName} Unable to perform MAF, {ex.Message}.");
return lastData.Value;
}
}
}
}
@@ -0,0 +1,30 @@
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public interface ITempSensor
{
/// <summary>
/// 返回温度传感器所属模组。
/// </summary>
string Module { get; }
/// <summary>
/// 返回当前温度传感器所胡
/// </summary>
string Name { get; }
/// <summary>
/// 测温硬件测试温度下限,属于硬件特性,在相应测温代码中已经预先固定写死
/// </summary>
double MinimalTemp { get; }
/// <summary>
/// 测温硬件通道数量,属于硬件特性,在相应测温代码中已经预先固定写死,AE、Akun都是四通道,德国三铯是单通道
/// </summary>
int MaxChannels { get; }
/// <summary>
/// 返回温度测量值。该测量值用于PID温度反馈。
/// </summary>
double[] Temp { get; }
}
}
@@ -0,0 +1,501 @@
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Threading;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.Omron
{
public class AdressInfo
{
public string Name { get; set; }
public byte DeviceAddress { get; set; }
public int UnitAddress { get; set; }
public int Length { get; set; }
public int Data;
public string Remark { get; set; }//H3-N2-H4-N5-H6(H3代表连续3个地址有数据,N2代表H3与H4中间有两个地址为预留)
}
public class TempOmron : BaseDevice, IConnection,IDevice
{
private TempOmronConnection _connection;
private bool _activeMonitorStatus;
private int _errorCode;
private R_TRIG _trigCommunicationError = new R_TRIG();
private R_TRIG _trigRetryConnect = new R_TRIG();
private PeriodicJob _thread;
private int tempCount = 1;
private LinkedList<HandlerBase> _lstHandler = new LinkedList<HandlerBase>();
private object _locker = new object();
private bool _enableLog = true;
private string _scRoot;
private int _actualTempValue = 999;
private int _settingTempValue = 888;
public int moduleCount { get; set; }
//public int ActualTemp
//{
// get { return _actualTempValue; }
// set { _actualTempValue = value; }
//}
//public int SettingTemp
//{
// get { return _settingTempValue; }
// set { _settingTempValue = value; }
//}
private int _tempWarningMaxDiff = 1; //报警最大温度(实际温度与设定温度之间的差值)
private R_TRIG[] TempWarningTrig = new R_TRIG[12]; //温度报警
string[] WarningInfo = new string[12] { "HeatTMAPanel","HeatTCSPanel","OuterPanel","MidPanel","InnerPanel","HeatShowerOuter", "HeatShowerInner", "HeatShowerMid", "HeatDptPanel","HeatLeakSource","HeatLeakBypass","HeatDptGate"};
public float[] ActualTemp = new float[12];
public float[] SettingTemp = new float[12];
public string Address
{
get; set;
}
public bool IsConnected
{
get
{
return _connection != null && _connection.IsConnected;
}
}
public bool Connect()
{
return true;
}
public bool Disconnect()
{
return true;
}
public TempOmron(string module, string name, string scRoot) : base(module, name, name, name)
{
_scRoot = scRoot;
_activeMonitorStatus = true;
}
~TempOmron()
{
_connection.Disconnect();
}
//public TempOmron(string module, string name, string scRoot) : base(module, name, name, name)
//{
// //tempCount = _count;
// _scRoot = scRoot;
// _activeMonitorStatus = true;
//}
public void QueryTemp()
{
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel1 Actual1 Temp", 0x01, 0x02, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel1 Setting1 Temp", 0x01, 0x02, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel1 Actual2 Temp", 0x01, 0x04, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel1 Setting2 Temp", 0x01, 0x04, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel1 Actual3 Temp", 0x01, 0x06, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel1 Setting3 Temp", 0x01, 0x06, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel1 Actual4 Temp", 0x01, 0x08, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel1 Setting4 Temp", 0x01, 0x08, 0x40, 0x00, 0x01));
if (moduleCount >= 2)
{
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel2 Actual1 Temp", 0x02, 0x02, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel2 Setting1 Temp", 0x02, 0x02, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel2 Actual2 Temp", 0x02, 0x04, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel2 Setting2 Temp", 0x02, 0x04, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel2 Actual3 Temp", 0x02, 0x06, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel2 Setting3 Temp", 0x02, 0x06, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel2 Actual4 Temp", 0x02, 0x08, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel2 Setting4 Temp", 0x02, 0x08, 0x40, 0x00, 0x01));
}
if (moduleCount >= 3)
{
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel3 Actual1 Temp", 0x03, 0x02, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel3 Setting1 Temp", 0x03, 0x02, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel3 Actual2 Temp", 0x03, 0x04, 0x0, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel3 Setting2 Temp", 0x03, 0x04, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel3 Actual3 Temp", 0x03, 0x06, 0x0, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel3 Setting3 Temp", 0x03, 0x06, 0x40, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel3 Actual4 Temp", 0x03, 0x08, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, "Query Channel3 Setting4 Temp", 0x03, 0x08, 0x40, 0x00, 0x01));
}
}
public void ResetDevice()
{
}
public void QueryError()
{
EV.PostInfoLog(Module, "Query error");
}
public bool Initialize()
{
// string portName = SC.GetStringValue($"{_scRoot}.{Module}.{Name}.Address");
string portName =SC.GetStringValue($"{Name}.Address");
Address = portName;
//int address = SC.GetValue<int>($"{_scRoot}.{Name}.DeviceAddress");
moduleCount= SC.GetValue<int>($"{Name}.Modules");
_enableLog = SC.GetValue<bool>($"{Name}.EnableLogMessage");
_connection = new TempOmronConnection(portName);
_connection.EnableLog(_enableLog);
_tempWarningMaxDiff = SC.GetValue<int>($"{Name}.TempWarnMaxDiff");
int count = SC.ContainsItem("System.ComPortRetryCount") ? SC.GetValue<int>("System.ComPortRetryCount") : 5;
int sleep = SC.ContainsItem("System.ComPortRetryDelayTime") ? SC.GetValue<int>("System.ComPortRetryDelayTime") : 2;
if (sleep <= 0 || sleep > 10)
sleep = 2;
int retry = 0;
do
{
_connection.Disconnect();
Thread.Sleep(sleep * 1000);
if (_connection.Connect())
{
EV.PostInfoLog(Module, $"{Name} connected");
break;
}
if (count > 0 && retry++ > count)
{
LOG.Write($"Retry connect {Module}.{Name} stop retry.");
EV.PostAlarmLog(Module, $"Can't connect to {Module}.{Name}.");
break;
}
Thread.Sleep(sleep * 1000);
LOG.Write($"Retry connect {Module}.{Name} for the {retry + 1} time.");
} while (true);
_thread = new PeriodicJob(200, OnTimer, $"{Module}.{Name} MonitorHandler", true);
DATA.Subscribe($"{Module}.{Name}.ActualTemp", () => ActualTemp);
DATA.Subscribe($"{Module}.{Name}.SettingTemp", () =>SettingTemp);
OP.Subscribe($"{Module}.{Name}.WriteConfigData", SetCofig);
OP.Subscribe($"{Module}.{Name}.WriteSingelData", SetSingle);
ConnectionManager.Instance.Subscribe($"{Name}", this);
return true;
}
public int _connecteTimes { get; set; }
private bool OnTimer()
{
try
{
_connection.MonitorTimeout();
if (!_connection.IsConnected || _connection.IsCommunicationError)
{
lock (_locker)
{
_lstHandler.Clear();
}
_trigRetryConnect.CLK = !_connection.IsConnected;
if (_trigRetryConnect.Q)
{
//_connection.SetPortAddress(SC.GetStringValue($"{_scRoot}.{Name}.Address"));
_connection.SetPortAddress(SC.GetStringValue($"{Name}.Address"));
if (!_connection.Connect())
{
EV.PostAlarmLog(Module, $"Can not connect with {_connection.Address}, {Module}.{Name}");
}
}
//if (_trigRetryConnect.CLK)
//{
// if (!_connection.Connect())
// {
// if (_trigRetryConnect.Q)
// {
// EV.PostAlarmLog(Module, $"Can not connect with {_connection.Address}, {Module}.{Name}");
// }
// }
// else
// {
// EV.PostAlarmLog(Module, $"Retry connect succee with {_connection.Address}, {Module}.{Name}");
// _trigRetryConnect.CLK = false;
// }
// Thread.Sleep(3000);
//}
if (_connecteTimes++ < 3)
_connection.ForceClear();
else _connecteTimes= 4;
return true;
}
HandlerBase handler = null;
//if (!_connection.IsBusy)
//{
lock (_locker)
{
if (_lstHandler.Count == 0 && !IsConfig)
QueryTemp();
if (_lstHandler.Count > 0 && !_connection.IsBusy)
{
handler = _lstHandler.First.Value;
_lstHandler.RemoveFirst();
if (handler != null)
{
_connection.Execute(handler);
}
}
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
return true;
}
internal void NoteError()
{
}
public void Monitor()
{
try
{
_connection.EnableLog(_enableLog);
if (_connecteTimes < 4) return;
_trigCommunicationError.CLK = _connection.IsCommunicationError;
if (_trigCommunicationError.Q)
{
for (int i = 0; i < 12; i++)
{
ActualTemp[i] = 0;
SettingTemp[i] = 0;
}
EV.PostAlarmLog(Module, $"{Module}.{Name} communication error, {_connection.LastCommunicationError}");
}
MonitorWarning();
}
catch (Exception ex)
{
LOG.Write(ex);
}
}
private void MonitorWarning()
{
for (int i = 0; i < 12; i++)
{
TempWarningTrig[i].CLK = SettingTemp[i] > 0 && _tempWarningMaxDiff > 0 && Math.Abs(ActualTemp[i] - SettingTemp[i]) > _tempWarningMaxDiff;
if (TempWarningTrig[i].Q)
{
EV.PostWarningLog(Module, $"{WarningInfo[i]},the difference between the actual value and the set value is too large");
}
}
}
public bool IsConfig { get; set; }
public bool SetSingle(string cmd, object[] objs)//设置单个或者多个地址 0x10
{
IsConfig = true;
_lstHandler.Clear();
lock (_locker)
{
string name = Convert.ToString(objs[0]);
int length = _dicAdressInfo[name].Length;
if (length == 1)
{
byte DeviceAddress = _dicAdressInfo[name].DeviceAddress;
int adress = _dicAdressInfo[name].UnitAddress;
byte addressH = Convert.ToByte((adress >> 8) & 0xff); ;
byte addressL = Convert.ToByte(adress & 0xff);
var data = _dicAdressInfo[name].Data;
byte dataH = Convert.ToByte((data >> 8) & 0xff);
byte dataL = Convert.ToByte(data & 0xff);
_lstHandler.AddLast(new TempOmronWriteSingleHandler(this, name, DeviceAddress, addressH, addressL, dataH, dataL));
//var name1 = "Query Channel" + DeviceAddress + " Actual" + addressH / 2 + " Temp";
//var name2 = "Query Channel" + DeviceAddress + " Setting" + addressH / 2 + " Temp";
//_lstHandler.AddLast(new TempOmronQueryHandler(this, name1, DeviceAddress, addressH, 0x00, 0x00, 0x01));
//_lstHandler.AddLast(new TempOmronQueryHandler(this, name2, DeviceAddress, addressH, 0x40, 0x00, 0x01));
}
}
return true;
}
public bool SetCofig(string cmd, object[] objs)//设置多个地址 0x10
{
IsConfig = true;
_lstHandler.Clear();
lock (_locker)
{
string name = Convert.ToString(objs[0]);
int length = _dicAdressInfo[name].Length;
if (length == 1)
{
byte DeviceAddress= _dicAdressInfo[name].DeviceAddress;
int adress = _dicAdressInfo[name].UnitAddress;
byte addressH = Convert.ToByte((adress >> 8) & 0xff); ;
byte addressL = Convert.ToByte(adress & 0xff);
var floatdata = Convert.ToSingle(objs[1])*10;
var data = Convert.ToInt16(floatdata);
byte dataH = Convert.ToByte((data >> 8) & 0xff);
byte dataL = Convert.ToByte(data & 0xff);
_lstHandler.AddLast(new TempOmronWriteHandler(this, name, DeviceAddress, addressH, addressL,0x00,0x01,0x02, dataH, dataL));
var name1 = "Query Channel" + DeviceAddress + " Actual" + addressH/2+ " Temp";
var name2 = "Query Channel" + DeviceAddress + " Setting" + addressH / 2 + " Temp";
_lstHandler.AddLast(new TempOmronQueryHandler(this, name1, DeviceAddress, addressH, 0x00, 0x00, 0x01));
_lstHandler.AddLast(new TempOmronQueryHandler(this, name2, DeviceAddress, addressH, 0x40, 0x00, 0x01));
}
}
return true;
}
public void Reset()
{
_connecteTimes = 0;
_connection.SetCommunicationError(false, "");
_trigCommunicationError.RST = true;
_enableLog = SC.GetValue<bool>($"{Name}.EnableLogMessage");
_trigRetryConnect.RST = true;
for (int i = 0; i < 12; i++)
{
TempWarningTrig[i].RST = true;
}
}
public void RespondAbnormal(int funcode, int abnormalcode)
{
if (funcode == 0x83)
{
foreach (var code in AbnormalCode)
{
if (code.Key == abnormalcode)
EV.PostWarningLog(Name, $"Query Abnormal:{code.Value}");
}
}
if (funcode == 0x90 || funcode == 0x86)
{
foreach (var code in AbnormalCode)
{
if (code.Key == abnormalcode)
EV.PostWarningLog(Name, $"Write Abnormal:{code.Value}");
}
}
}
public Dictionary<int, string> AbnormalCode = new Dictionary<int, string>()
{
{ 1,"ncorrect function code, this machine does not correspond to the function code." },
{ 2,"Incorrect data address" },
{ 3,"Incorrect data." },
{ 4,"operation error" },
};
public void SetActiveMonitor(bool active)
{
_activeMonitorStatus = active;
}
public void SetErrorCode(int errorCode)
{
_errorCode = errorCode;
}
public void Terminate()
{
_connection.Disconnect();
}
public Dictionary<string, AdressInfo> _dicAdressInfo = new Dictionary<string, AdressInfo>()//配置最多32个数据
{
{"Channel1Setting1", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0x0240,Length = 1 } },//手册 11-3
{"Channel1Setting2", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0x0440,Length = 1 } },
{"Channel1Setting3", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0x0640,Length = 1 } },
{"Channel1Setting4", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0x0840,Length = 1 } },
{"Channel2Setting1", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0x0240,Length = 1 } },//手册 11-3
{"Channel2Setting2", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0x0440,Length = 1 } },
{"Channel2Setting3", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0x0640,Length = 1 } },
{"Channel2Setting4", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0x0840,Length = 1 } },
{"Channel3Setting1", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0x0240,Length = 1 } },//手册 11-3
{"Channel3Setting2", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0x0440,Length = 1 } },
{"Channel3Setting3", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0x0640,Length = 1 } },
{"Channel3Setting4", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0x0840,Length = 1 } },
{"Channel1RunALL", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1,Data=0x0AFF} },
{"Channel1Run1", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A00} },
{"Channel1Run2", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A01} },
{"Channel1Run3", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A02} },
{"Channel1Run4", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1,Data=0x0A03} },
{"Channel2RunALL", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1,Data=0x0AFF } },
{"Channel2Run1", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A00} },
{"Channel2Run2", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A01} },
{"Channel2Run3", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A02} },
{"Channel2Run4", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A03} },
{"Channel3RunALL", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1,Data=0x0AFF } },
{"Channel3Run1", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A00} },
{"Channel3Run2", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A01 } },
{"Channel3Run3", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0A02} },
{"Channel3Run4", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1,Data=0x0A03} },
{"Channel1StopALL", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1,Data=0x0BFF } },
{"Channel1Stop1", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B00} },
{"Channel1Stop2", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B01} },
{"Channel1Stop3", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B02} },
{"Channel1Stop4", new AdressInfo() { DeviceAddress=0x01, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B03} },
{"Channel2StopALL", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0BFF} },
{"Channel2Stop1", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B00} },
{"Channel2Stop2", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1,Data=0x0B01} },
{"Channel2Stop3", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1,Data=0x0B02 } },
{"Channel2Stop4", new AdressInfo() { DeviceAddress=0x02, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B03} },
{"Channel3StopALL", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0BFF} },
{"Channel3Stop1", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B00} },
{"Channel3Stop2", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B01} },
{"Channel3Stop3", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B02} },
{"Channel3Stop4", new AdressInfo() { DeviceAddress=0x03, UnitAddress = 0xFFFF,Length = 1 ,Data=0x0B03} },
};
}
}
@@ -0,0 +1,237 @@
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.Omron
{
public class TempOmronMessage : BinaryMessage
{
public byte DeviceAddress { get; set; }
public byte FunctionCode { get; set; }
public byte Length { get; set; }
public byte[] Data { get; set; }
}
public class TempOmronConnection:SerialPortConnectionBase
{
private List<byte> _lstCacheBuffer = new List<byte>();
public TempOmronConnection(string portName) : base(portName, 9600, 8, System.IO.Ports.Parity.Even, System.IO.Ports.StopBits.One, "\n", false)
{
}
public override bool SendMessage(byte[] message)
{
_lstCacheBuffer.Clear();
return base.SendMessage(message);
}
protected override MessageBase ParseResponse(byte[] rawMessage)
{
_lstCacheBuffer.AddRange(rawMessage);
byte[] temps = _lstCacheBuffer.ToArray();
TempOmronMessage msg = new TempOmronMessage();
msg.IsResponse = false;
msg.IsAck = false;
msg.IsComplete = false;
msg.RawMessage = _lstCacheBuffer.ToArray();
if (temps.Length < 4) return msg;
msg.DeviceAddress = temps[0];
msg.FunctionCode = temps[1];
if (msg.FunctionCode !=0x03)
{
msg.Data = _lstCacheBuffer.ToArray();
}
else
{
msg.Length = temps[2];
if (temps.Length < msg.Length + 5)
{
//msg.IsFormatError = true;
return msg;
}
msg.Data = _lstCacheBuffer.Skip(3).Take(msg.Length).ToArray();
}
msg.IsResponse = true;
msg.IsAck = true;
msg.IsComplete = true;
return msg;
}
private static byte ModRTU_CRC(byte[] buffer)
{
//ushort crc = 0xFFFF;
// var buf = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, buffer));
var buf = buffer;
var len = buffer.Length;
byte temp = buffer[0];
for (int i = 1; i < buffer.Length; i++)
{
temp = (byte)(temp ^ buffer[i]);
}
return (byte)~temp;
}
}
public abstract class TempOmronHandler : HandlerBase
{
public TempOmron Device { get; }
protected TempOmronHandler(TempOmron device, byte[] commandvalue)
: base(BuildMessage(commandvalue))
{
Device = device;
}
private static byte[] BuildMessage(byte[] commandvalue)
{
byte[] crc = ModRTU_CRC(commandvalue);
List<byte> result = commandvalue.ToList();
foreach (byte b in crc)
{
result.Add(b);
}
return result.ToArray();
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as TempOmronMessage;
ResponseMessage = msg;
handled = true;
return true;
}
private static byte[] ModRTU_CRC(byte[] buffer)
{
ushort crc = 0xFFFF;
// var buf = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, buffer));
var buf = buffer;
var len = buffer.Length;
for (var pos = 0; pos < len; pos++)
{
crc ^= buf[pos]; // XOR byte into least sig. byte of crc
for (var i = 8; i != 0; i--)
// Loop over each bit
if ((crc & 0x0001) != 0)
{
// If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
{
crc >>= 1; // Just shift right
}
}
// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
return BitConverter.GetBytes(crc);
}
}
public class TempOmronQueryHandler : TempOmronHandler
{
public TempOmronQueryHandler(TempOmron device,string name, byte groupAddress,byte offerHigh,byte offerLow,byte dataHigh,byte dataLow)
: base(device, new byte[] { groupAddress, 3, offerHigh, offerLow, dataHigh, dataLow })
{
Name = name;//"Query Temp";
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as TempOmronMessage;
handled = false;
if (!result.IsResponse) return true;
short rvalue = 0;
rvalue = (short)(rvalue ^ result.Data[0]);
rvalue = (short)(rvalue << 8);
rvalue = (short)(rvalue ^ result.Data[1]);
//if(Name.Contains("Actual"))
//Device.ActualTemp = rvalue;
//else
//Device.SettingTemp = rvalue;
if (Name.Contains("Actual"))
{ var chel =Convert.ToInt16(Name.Split(' ')[1].Substring(7,1));
var count = Convert.ToInt16(Name.Split(' ')[2].Substring(6, 1));
var index = (chel-1) * 4 + count - 1;
Device.ActualTemp[index] =Convert.ToSingle(rvalue)/10;
}
else
{
var chel = Convert.ToInt16(Name.Split(' ')[1].Substring(7, 1));
var count = Convert.ToInt16(Name.Split(' ')[2].Substring(7, 1));
var index = (chel - 1) * 4 + count - 1;
Device.SettingTemp[index] = Convert.ToSingle(rvalue)/10;
}
Device._connecteTimes = 0;
ResponseMessage = msg;
handled = true;
Thread.Sleep(1000);
return true;
}
}
public class TempOmronWriteSingleHandler : TempOmronHandler
{
public TempOmronWriteSingleHandler(TempOmron device, string name, byte groupAddress, byte offerHigh, byte offerLow, byte dataHigh, byte dataLow)
: base(device, new byte[] { groupAddress, 0x06, offerHigh, offerLow, dataHigh, dataLow })
{
Name = name;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as TempOmronMessage;
handled = false;
if (!result.IsResponse) return true;
if (result.FunctionCode == 0x86)
{
Device.RespondAbnormal(result.FunctionCode, result.Data[2]);
}
ResponseMessage = msg;
handled = true;
Device.IsConfig = false;
Thread.Sleep(1000);
return true;
}
}
public class TempOmronWriteHandler : TempOmronHandler
{
public TempOmronWriteHandler(TempOmron device, string name,byte groupAddress, byte offerHigh, byte offerLow,byte unitH,byte unitL,byte length, byte dataHigh, byte dataLow)
: base(device, new byte[] { groupAddress, 0x10, offerHigh, offerLow, unitH, unitL, length, dataHigh, dataLow })
{
Name = name;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as TempOmronMessage;
handled = false;
if (!result.IsResponse) return true;
if (result.FunctionCode == 0x90)
{
Device.RespondAbnormal(result.FunctionCode, result.Data[2]);
}
ResponseMessage = msg;
handled = true;
Device.IsConfig = false;
Thread.Sleep(1000);
return true;
}
}
}
@@ -0,0 +1,210 @@
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Xml;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public class SensorTemp : TempSensorBase
{
private SensorTempConnection _connection;
private readonly R_TRIG _trigCommunicationError = new ();
private readonly R_TRIG _trigMonitorExcepted = new ();
private readonly LinkedList<HandlerBase> _lstHandler = new();
private readonly object _locker = new ();
private string PMName;
private double[] _tempBuff;
public override bool IsConnected => _connection is { IsConnected: true };
public SensorTemp(string module, XmlElement node, string ioModule = "") : base(module, node, ioModule)
{
RTrigs.Add(_trigCommunicationError);
RTrigs.Add(_trigMonitorExcepted);
}
private void QueryTemp()
{
SetQuery("QueryBup", "00mw0\r");
}
private void SetQuery(string name, string strCmd)
{
lock (_locker)
{
if (_connection.IsBusy)
{
_connection.ForceClear();
}
byte[] bCmd = Encoding.Default.GetBytes(strCmd);
_lstHandler.AddLast(new SensorTempQueryHandler(this, name, bCmd));
}
}
protected override bool HandleInitialize()
{
InitController();
_tempBuff = new double[MaxChannels];
return true;
}
private void InitController()
{
//添加参数设置
PMName = SC.GetStringValue($"{ScBasePath}.{Name}.PMName");
Address = SC.GetStringValue($"{ScBasePath}.{Name}.Address");
_connection = new SensorTempConnection(Address);
_connection.EnableLog(IsEnableLog);
SC.RegisterValueChangedCallback($"TempSensors.EnableLogMessage", (obj) =>
{
_connection.EnableLog((bool)obj);
});
}
protected override void HandleMonitor()
{
try
{
_connection.MonitorTimeout();
if (!_connection.IsConnected)
{
lock (_locker)
{
_lstHandler.Clear();
}
//只要断开,就进行连接
if (!_connection.Connect())
{
_trigCommunicationError.CLK = !_connection.IsConnected;
if (_trigCommunicationError.Q)
{
Thread.Sleep(2000);//不加延时软件刚启动可能不打印
TempBasFunction.PMPostLog(PMName, $"Can not connect with {_connection.Address}, {Name}", EV.PostAlarmLog);
TempBasFunction.SetPmIoForInterlock(PMName, true);
}
}
else//已连接,自动复位断联信号
{
_trigCommunicationError.RST = true;
TempBasFunction.PMPostLog(PMName, $"{PMName} {Name} {Address} reconnected.", EV.PostInfoLog);
TempBasFunction.SetPmIoForInterlock(PMName, false);
}
Thread.Sleep(1000);//重连延时
_connection.ForceClear();
}
else
{
lock (_locker)
{
if (_lstHandler.Count == 0)
QueryTemp();
if (_lstHandler.Count > 0 && !_connection.IsBusy)
{
var handler = _lstHandler.First.Value;
_lstHandler.RemoveFirst();
if (handler != null)
_connection.Execute(handler);
}
}
}
if (_connection.IsCommunicationError)
{
//ResponseError();
}
_trigMonitorExcepted.CLK = false;
}
catch (Exception ex)
{
_trigMonitorExcepted.CLK = true;
if(_trigMonitorExcepted.Q)
LOG.Write(ex);
}
}
protected override double[] HandleReadTemp()
{
return IsConnected ? _tempBuff : null;
}
public void ResponseQuery(string name, byte[] data)
{
try
{
var sData = Encoding.Default.GetString(data);
if (name == "QueryBup")
{
if (!sData.Contains("\r"))
return;
var strTemp = sData.Replace("\r", "");
var temp = (float)Convert.ToInt32(strTemp, 16) / 10;
if (temp < MinimalTemp - 10 || temp > 2000)//过滤因通讯数据截取,导致的异常
{
LOG.Write($"{Module} {Name} temp error :{temp}");
return;
}
_tempBuff[0] = temp ;
//温度连续多次不变化侦测
//TempInvariantCount = TempBasFunction.TempInvariantCount(TempDatasArray, out string tempInvariantData);
//_trigTempNoChange.CLK = TempInvariantCount >= TempInvariantCountMax ? true : false;
//if (_trigTempNoChange.Q)
//{
// TempBasFunction.PMPostLog(PMName, $"{PMName} {Name} {TempInvariantCount} temp no changeCount {tempInvariantData}", EV.PostWarningLog);
//}
}
}
catch (Exception ex)
{
}
}
public void ResponseError()
{
_trigCommunicationError.CLK = true;
if (_trigCommunicationError.Q)
{
TempBasFunction.PMPostLog(PMName, $"{PMName} {Name} {Address} could not receive temp", EV.PostAlarmLog);
TempBasFunction.SetPmIoForInterlock(PMName, true);
}
}
public override bool Connect()
{
return _connection.Connect();
}
public override void Terminate()
{
_connection.Disconnect();
}
}
}
@@ -0,0 +1,73 @@
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System.Collections.Generic;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public class SensorTempConnection : SerialPortConnectionBase
{
private List<byte> _lstCacheBuffer = new List<byte>();
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(1000);
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;
}
}
}
@@ -0,0 +1,54 @@
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public abstract class SensorTempHandler : HandlerBase
{
public SensorTemp Device { get; }
protected SensorTempHandler(SensorTemp device, byte[] commandvalue)
: base(commandvalue)
{
Device = device;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as BinaryMessage;
ResponseMessage = msg;
handled = true;
return true;
}
}
public class SensorTempQueryHandler : SensorTempHandler
{
public SensorTempQueryHandler(SensorTemp device, string name, byte[] commandvalue)
: base(device, commandvalue)
{
Name = name;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as BinaryMessage;
handled = false;
if (result.IsError)
{
Device.ResponseError();
return false;
}
if (!result.IsComplete)
{
return false;
}
Device.ResponseQuery(Name, result.RawMessage);
return true;
}
}
}
@@ -0,0 +1,187 @@
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Xml;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public class StrongTemp : TempSensorBase
{
private StrongTempConnection _connection;
private readonly R_TRIG _trigCommunicationError = new ();
private readonly R_TRIG _trigMonitorExcepted = new ();
private readonly LinkedList<HandlerBase> _lstHandler = new();
private readonly object _locker = new ();
private string PMName;
private double[] _tempBuff;
public override bool IsConnected => _connection is { IsConnected: true };
public StrongTemp(string module, XmlElement node, string ioModule = "") : base(module, node, ioModule)
{
RTrigs.Add(_trigCommunicationError);
RTrigs.Add(_trigMonitorExcepted);
}
private void QueryTemp()
{
SetQuery("QueryADT", "*ADT00000a");
}
private void SetQuery(string name, string strCmd)
{
lock (_locker)
{
_lstHandler.Clear();
if (_connection.IsBusy)
{
_connection.ForceClear();
}
var bCmd = Encoding.Default.GetBytes(strCmd);
_lstHandler.AddLast(new StrongTempQueryHandler(this, name, bCmd));
}
}
protected override bool HandleInitialize()
{
InitController();
_tempBuff = new double[MaxChannels];
return true;
}
private void InitController()
{
//添加参数设置
PMName = SC.GetStringValue($"{ScBasePath}.{Name}.PMName");
Address = SC.GetStringValue($"{ScBasePath}.{Name}.Address");
_connection = new StrongTempConnection(Address);
_connection.EnableLog(IsEnableLog);
SC.RegisterValueChangedCallback($"TempSensors.EnableLogMessage", (obj) => { _connection.EnableLog((bool)obj); });
}
protected override double[] HandleReadTemp()
{
return IsConnected ? _tempBuff : null;
}
protected override void HandleMonitor()
{
try
{
_connection.MonitorTimeout();
if (!_connection.IsConnected || _connection.IsCommunicationError)
{
lock (_locker)
{
_lstHandler.Clear();
}
//只要断开,就进行连接
if (!_connection.Connect())
{
_trigCommunicationError.CLK = !_connection.IsConnected;
if (_trigCommunicationError.Q)
{
Thread.Sleep(2000);//不加延时软件刚启动可能不打印
TempBasFunction.PMPostLog(PMName, $"Can not connect with {_connection.Address}, {Name}", EV.PostAlarmLog);
TempBasFunction.SetPmIoForInterlock(PMName, true);
}
}
else//已连接,自动复位断联信号
{
_trigCommunicationError.RST = true;
TempBasFunction.PMPostLog(PMName, $"{PMName} {Name} {Address} reconnected.", EV.PostInfoLog);
TempBasFunction.SetPmIoForInterlock(PMName, false);
}
Thread.Sleep(1000);//重连延时
_connection.ForceClear();
}
else
{
lock (_locker)
{
if (_lstHandler.Count == 0)
QueryTemp();
if (_lstHandler.Count > 0 && !_connection.IsBusy)
{
var handler = _lstHandler.First.Value;
_lstHandler.RemoveFirst();
if (handler != null)
{
_connection.Execute(handler);
}
}
}
}
}
catch (Exception ex)
{
_trigMonitorExcepted.CLK = true;
if(_trigMonitorExcepted.Q)
LOG.Write(ex);
}
}
public void ResponseQuery(string name, byte[] data)
{
try
{
if (name == "QueryADT")
{
var sData = Encoding.Default.GetString(data);
if (sData.Length < 9)
return;
if (sData.Contains("*A"))
{
string sT = sData.Substring(2, 6);
_tempBuff[0] = Convert.ToSingle(sT);
}
}
}
catch (Exception ex)
{
// ignored
}
}
public void ResponseError()
{
_trigCommunicationError.CLK = true;
if (_trigCommunicationError.Q)
{
TempBasFunction.PMPostLog(PMName, $"{PMName} {Name} {Address} could not receive temp", EV.PostAlarmLog);
TempBasFunction.SetPmIoForInterlock(PMName, true);
}
}
public override void Terminate()
{
_connection.Disconnect();
}
}
}
@@ -0,0 +1,72 @@
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public class StrongTempConnection : SerialPortConnectionBase
{
private List<byte> _lstCacheBuffer = new List<byte>();
public StrongTempConnection(string portName) : base(portName, 9600, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One, "", 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 (Array.IndexOf(rawMessage, 43) == -1)//byte 43 是通讯结束字符串C
//return IsTimeOut() ? ReceiveTempMessage(true, false, _lstCacheBuffer.ToArray()) : ReceiveTempMessage(false, false, _lstCacheBuffer.ToArray());
{
var mes = IsTimeOut() ? ReceiveTempMessage(true, false, _lstCacheBuffer.ToArray()) : ReceiveTempMessage(false, false, _lstCacheBuffer.ToArray());
if (deviceTimer.IsIdle())
deviceTimer.Start(1000);
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;
}
}
}
@@ -0,0 +1,42 @@
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
public abstract class StrongTempHandler : HandlerBase
{
public StrongTemp Device { get; }
protected StrongTempHandler(StrongTemp device, byte[] commandvalue) : base(commandvalue)
{
Device = device;
}
}
public class StrongTempQueryHandler : StrongTempHandler
{
public StrongTempQueryHandler(StrongTemp device, string name, byte[] commandvalue)
: base(device, commandvalue)
{
Name = name;//"Query Temp";
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as BinaryMessage;
handled = false;
if (result.IsError)
{
Device.ResponseError();
return false;
}
if (!result.IsComplete)
{
return false;
}
Device.ResponseQuery(Name, result.RawMessage);
return true;
}
}
}
@@ -0,0 +1,140 @@
using Aitex.Core.RT.IOCore;
using Aitex.Core.RT.SCCore;
using System;
using System.Text;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps
{
/// <summary>
/// 会根据PM安装与否,执行合适的Log输出,DO输出,温度在规定次数内是否改变方法
/// 此类作为一个测温类的对象使用,
/// 初始化时传入的名称+温度下限+测温通道数,
/// 1:名称会在Log中打印出来,2:传入温度<=最低温度时,认为温度发生变化
/// </summary>
public class TempBasFunction
{
private bool IsPM1Installed { get; set; }
private bool IsPM2Installed { get; set; }
private string DeviceName { get; set; }
private float[] tempChangeCache;
//硬件通道数
private int NumberOfChannels;
/// <summary>
/// 统计温度相同次数
/// </summary>
private int noChangeNum;
/// <summary>
/// 记录温度不变时数据,最多记录10次
/// </summary>
private StringBuilder strNoChangeMeg = new();
/// <summary>
/// 测温硬件最低测试温度,传入温度为此数值,不进行温度数据变化对比
/// </summary>
private readonly double TempMin;
/// <summary>
/// 初始化
/// </summary>
/// <param name="deviceName">测温硬件名称</param>
/// <param name="tempMin">最低温度显示,AE和昂坤都是600</param>
public TempBasFunction(string deviceName , double tempMin,int numberOfChannels)
{
DeviceName = deviceName;
TempMin = tempMin;
NumberOfChannels = numberOfChannels;
tempChangeCache = new float[NumberOfChannels];
IsPM1Installed = SC.GetValue<bool>($"System.SetUp.IsPM1Installed");
IsPM2Installed = SC.GetValue<bool>($"System.SetUp.IsPM2Installed");
}
public void PM1PM2PostLog(string str, Action<string, string, int> action)
{
if (IsPM1Installed)
action("PM1", $"{DeviceName} {str}", 2);
if (IsPM2Installed)
action("PM2", $"{DeviceName} {str}", 2);
}
/// <summary>
/// 操作DO_PyroCommunicationError信号为InterLock提供输出,DO输出为true时设备报警宕机
/// </summary>
/// <param name="isReset"></param>
public void SetPm1Pm2IoForInterlock(bool isReset)
{
if (IsPM1Installed)
IO.DO[$"PM1.DO_PyroCommunicationError"].SetValue(isReset, out _);
if (IsPM2Installed)
IO.DO[$"PM2.DO_PyroCommunicationError"].SetValue(isReset, out _);
}
/// <summary>
/// 复位单个PM的DO信号
/// </summary>
/// <param name="pm"></param>
/// <param name="isReset"></param>
public void SetPmIoForInterlock(string pm, bool isReset)
{
string PM = pm.ToUpper();
if (IsMP(PM))
IO.DO[$"PM1.DO_PyroCommunicationError"].SetValue(isReset, out _);
}
/// <summary>
/// 控制单个PM报警输出
/// </summary>
/// <param name="pm"></param>
/// <param name="str"></param>
/// <param name="action"></param>
public void PMPostLog(string pm, string str, Action<string, string, int> action)
{
string PM = pm.ToUpper();
if (IsMP(PM))
action(PM, $"{DeviceName} {str}", 2);
}
private bool IsMP(string pm)
{
return (pm == "PM1" || pm == "PM2")? true : false;
}
/// <summary>
/// 温度是否发生改变,返回数据不发生改变次数
/// </summary>
/// <param name="outputTemp"></param>
/// <returns></returns>
public int TempInvariantCount(float[] outputTemp, out string errorInf)
{
errorInf = "";
if (noChangeNum > 999999)//防止数据溢出
noChangeNum = 0;
for (int i = 0; i < outputTemp.Length; i++)
{
if (outputTemp[i] <= TempMin)//低于温度下限,数据不做对比
continue;
if (outputTemp[i] == tempChangeCache[i])
{
if (noChangeNum < 10)//记录前10次的数据
strNoChangeMeg.Append($"#{i + 1}:{outputTemp[i]:0.00} ");
errorInf = strNoChangeMeg.ToString();
return noChangeNum++;
}
tempChangeCache[i] = outputTemp[i];
}
//只要数据不同,就可以复位计数和缓存
strNoChangeMeg.Clear();
noChangeNum = 0;
return 0;
}
}
}
@@ -0,0 +1,152 @@
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.SCCore;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps.Filters;
using System;
using Aitex.Core.RT.Log;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps;
public sealed class TempDataFilter
{
#region Variables
private readonly string _scBase;
private readonly MoveAverageFilter _mafFilter;
private readonly KalmanFilter _kalmanFilter;
private IFilter _activeFilter = null;
private FilterTypes _filterType = FilterTypes.None;
#endregion
#region Ctor
public TempDataFilter(string module, string sensorName, double pollIntervalMs, double minimalTemp = 600,
string scBasePath = "TempSensors")
{
Module = module;
SensorName = sensorName;
_scBase = scBasePath;
_mafFilter =
new MoveAverageFilter(module, $"{module}.Temp.Filter.{sensorName}.MAF", $"{scBasePath}.Filters.MAF");
_kalmanFilter = new KalmanFilter(module, $"{module}.Temp.Filter.{sensorName}.Kalman",
$"{scBasePath}.Filters.Kalman", pollIntervalMs);
}
#endregion
#region Properties
public string Module { get; }
public string SensorName { get; }
public FilterTypes FilterType
{
get => _filterType;
private set
{
switch (value)
{
case FilterTypes.None:
_activeFilter = null;
break;
case FilterTypes.MAF:
_activeFilter = _mafFilter;
break;
case FilterTypes.Kalman:
_activeFilter = _kalmanFilter;
break;
}
if (_filterType != value)
{
// 如果切换滤波器类型,重置当前滤波器,以防止滤波结果包含很久以前的数据导致滤波错误。
_activeFilter?.Reset();
}
_filterType = value;
}
}
/// <summary>
/// 返回测温原始温度值。
/// </summary>
internal double Raw { get; private set; }
/// <summary>
/// 返回滤波后的温度。
/// </summary>
internal double Filtered { get; private set; }
#endregion
#region Methods
public bool Initialize(out string reason)
{
reason = "";
DATA.Subscribe($"{Module}.Temp.Filter.{SensorName}.FilterType", () => (int)FilterType);
DATA.Subscribe($"{Module}.Temp.Filter.{SensorName}.RAW", () => Raw);
DATA.Subscribe($"{Module}.Temp.Filter.{SensorName}.Filtered", () => Filtered);
var scName = $"{_scBase}.FilterType";
FilterType = ConvertToFilterType(SC.SafeGetStringValue(scName, "None"));
SC.RegisterValueChangedCallback(scName, value =>
{
if (value is string filterType)
FilterType = ConvertToFilterType(filterType);
else
LOG.Error($"{SensorName} Invalid value for Filter Type: {value}. Expected an string.");
});
var isFilterInitSucceeded = true;
if (!_mafFilter.Initialize(out var reasonMaf))
{
LOG.Error($"{SensorName} Move Average Filter initialization failed: {reasonMaf}");
isFilterInitSucceeded = false;
}
if (!_kalmanFilter.Initialize(out var reasonKalman))
{
LOG.Error($"{SensorName} Move Kalman Filter initialization failed: {reasonKalman}");
isFilterInitSucceeded = false;
}
if (!isFilterInitSucceeded)
{
reason = $"{SensorName} Filter initialization failed, see log for details";
return false;
}
return true;
}
/// <summary>
/// 添加一个新温度值。
/// </summary>
/// <param name="temp"></param>
public void Update(double temp)
{
Raw = temp;
Filtered = _activeFilter?.Update(temp) ?? Raw;
}
#endregion
private FilterTypes ConvertToFilterType(string type)
{
if (Enum.TryParse<FilterTypes>(type, true, out var ft))
return ft;
else
{
LOG.Error($"{this} Unable to convert {type} to filter type.");
return FilterTypes.None;
}
}
}
@@ -0,0 +1,22 @@
using System;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps;
public class TempPoint
{
public TempPoint(double value)
{
Value = value;
TimeStamp = DateTime.Now.Ticks;
}
/// <summary>
/// 返回温度值。
/// </summary>
public double Value { get; }
/// <summary>
/// 返回时间戳。
/// </summary>
public long TimeStamp { get; }
}
@@ -0,0 +1,230 @@
using System;
using System.Diagnostics;
using System.Xml;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Temps;
public abstract class TempSensorBase : BaseDevice, IDevice, IConnection, ITempSensor
{
#region Variables
protected readonly bool IsSimMode;
protected bool IsEnableLog;
protected TempBasFunction TempBasFunction;
private readonly Random _rndTempGen = new();
private readonly R_TRIG _rTrigReadTempFailed = new();
private PeriodicJob _tReadTemp;
//private Misc.FilterTypes _filterType;
//private TempDataFilter[] _tempFilters;
private readonly Stopwatch _swSimSineWave = new ();
private const double SINE_T = 5.0;
private const double SINE_F = 2.0 * Math.PI * (1 / SINE_T);
#endregion
#region Ctor
protected TempSensorBase(string module, XmlElement node, string ioModule = "")
: base(module, node, ioModule)
{
IsSimMode = SC.SafeGetValue("System.IsSimulatorMode", false);
RTrigs.Add(_rTrigReadTempFailed);
var maxChStr = node.GetAttribute("MaxChannels");
if (!string.IsNullOrEmpty(maxChStr) && int.TryParse(maxChStr, out var maxCh))
MaxChannels = maxCh;
else
MaxChannels = 4;
var minTempStr = node.GetAttribute("MinimalTemp");
if (!string.IsNullOrEmpty(minTempStr) && double.TryParse(minTempStr, out var minTemp))
MinimalTemp = minTemp;
else
MinimalTemp = 600.0;
if(IsSimMode)
_swSimSineWave.Start();
}
#endregion
#region Properties
public virtual string Address { get; protected set; }
public virtual bool IsConnected { get; }
public double MinimalTemp { get; }
public int MaxChannels { get; }
public double[] Temp { get; private set; }
#endregion
#region Methods
/// <summary>
/// 生成随机温度。
/// </summary>
/// <returns></returns>
private double[] RandomTemps(double baseTemp = 800, double peakPeak = 200, double jitter = 50.0)
{
var rndTemps = new double[MaxChannels];
for (var i = 0; i < MaxChannels; i++)
{
var t = _swSimSineWave.Elapsed.TotalSeconds; // current moment
var tempSine = peakPeak * Math.Sin(SINE_F * t + (i * Math.PI / 3)); //temperature following sine wave with 60 deg(π/3 rad) phase-diff per channel
tempSine += baseTemp + tempSine + _rndTempGen.NextDouble() * jitter; // add jitter
rndTemps[i] = tempSine;
}
return rndTemps;
}
private bool DoTempReadThread()
{
// get temp. points according to the "IsSimulatorMode" system config.
var temps = IsSimMode ? RandomTemps() : HandleReadTemp();
_rTrigReadTempFailed.CLK = temps == null || temps.Length != MaxChannels;
if (_rTrigReadTempFailed.Q)
{
LOG.Error(temps != null
? $"{this} {MaxChannels} temperature data wanted but {temps.Length} points read."
: $"{this} None temperature data read from controller.");
}
// Too less temp. points read from the sensor.
if (_rTrigReadTempFailed.M)
return true;
// Get the right temp value from the filter
for (var i = 0; i < MaxChannels; i++)
{
Temp[i] = temps[i];
//_tempFilters[i].AddRawTemp(temps![i]);
//Temp[i] = _filterType switch
//{
// Misc.FilterTypes.None => _tempFilters[i].Raw,
// Misc.FilterTypes.MAF => _tempFilters[i].FilteredMAF,
// _ => _tempFilters[i].Raw
//};
}
return true;
}
private void InitTempDataFilter()
{
//_tempFilters = new TempDataFilter[MaxChannels];
Temp = new double[MaxChannels];
for (var i = 0; i < MaxChannels; i++)
{
//_tempFilters[i] = new TempDataFilter(this, (i + 1).ToString(), MinimalTemp, ScBasePath);
Temp[i] = MinimalTemp;
var ch = i;
DATA.Subscribe($"TempSensor.{Name}.CH{ch + 1}", () => Temp[ch]);
//DATA.Subscribe($"TempSensor.{Name}.CH{ch + 1}MAF", () => _tempFilters[ch].FilteredMAF);
//DATA.Subscribe($"TempSensor.{Name}.CH{ch + 1}Raw", () => _tempFilters[ch].Raw);
}
}
protected virtual double[] HandleReadTemp()
{
return new double[MaxChannels];
}
protected virtual bool HandleInitialize()
{
return true;
}
public bool Initialize()
{
try
{
if (!SC.GetValue<bool>($"{ScBasePath}.{Name}.EnableDevice"))
{
IsEnabled = false;
return true;
}
IsEnableLog = SC.SafeGetValue($"TempSensors.EnableLogMessage", false);
//_filterType = ConvertToFilterType(SC.SafeGetStringValue($"{ScBasePath}.FilterType", "None"));
var pollInvMs = SC.SafeGetValue($"{ScBasePath}.PollInterval", 100);
// 系统参数变更回调
SC.RegisterValueChangedCallback($"{ScBasePath}.PollInterval",
(obj) => { _tReadTemp.ChangeInterval((int)obj); });
//SC.RegisterValueChangedCallback($"{ScBasePath}.FilterType",
// (obj) => { _filterType = ConvertToFilterType(obj?.ToString() ?? ""); });
SC.RegisterValueChangedCallback($"TempSensors.EnableLogMessage",
(obj) =>
{
IsEnableLog = bool.TryParse(obj.ToString(), out var en) && en;
});
TempBasFunction = new TempBasFunction(Name, MinimalTemp, MaxChannels);
TempBasFunction.SetPm1Pm2IoForInterlock(false);
InitTempDataFilter();
// 执行派生类初始化方法
var userInit = HandleInitialize();
_tReadTemp = new PeriodicJob(pollInvMs, DoTempReadThread, $"{Name}", true);
return userInit;
}
catch (Exception e)
{
LOG.Error(e.Message, e);
return false;
}
}
public virtual bool Connect()
{
return true;
}
public virtual bool Disconnect()
{
return true;
}
public virtual void Terminate()
{
}
public virtual void Reset()
{
foreach (var rt in RTrigs)
rt.RST = true;
}
public override string ToString()
{
return $"{Module}.{Name}";
}
#endregion
}