refactor: 将Framework库和RT、UI放在同一个解决方案中。

This commit is contained in:
SL
2026-06-01 17:48:28 +08:00
parent 1948f4290d
commit b73d39a6b1
4331 changed files with 506148 additions and 49363 deletions
@@ -0,0 +1,579 @@
using System;
using System.Collections.Generic;
using System.IO.Ports;
using Aitex.Core.Common.DeviceData;
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 MECF.Framework.Common.Device.Bases;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFs.AE
{
public class AeRfPower : RfPowerBase
{
public override bool IsError { get; set; }
public override bool IsPowerOn
{
get { return _isOn; }
}
public override EnumRfPowerRegulationMode RegulationMode
{
get { return _regulationMode; }
}
public override float ForwardPower
{
get { return _forwardPower; }
}
public override float ReflectPower
{
get { return _reflectPower; }
}
public override float PowerSetPoint
{
get { return _powerSetPoint; }
}
public override float Frequency { get; set; }
public override float PulsingFrequency { get; set; }
public override float PulsingDutyCycle { get; set; }
public override AITRfPowerData DeviceData
{
get
{
AITRfPowerData data = new AITRfPowerData()
{
DeviceName = Name,
DeviceSchematicId = DeviceID,
DisplayName = Display,
ForwardPower = ForwardPower,
ReflectPower = ReflectPower,
PowerSetPoint = PowerSetPoint,
RegulationMode = RegulationMode,
IsRfOn = IsPowerOn,
Frequency = Frequency,
PulsingFrequency = PulsingFrequency,
PulsingDutyCycle = PulsingDutyCycle,
};
return data;
}
}
public AeRfPowerConnection Connection
{
get { return _connection; }
}
private AeRfPowerConnection _connection;
private byte _deviceAddress ;
private float _powerSetPoint;
private float _reflectPower;
private bool _isOn;
private float _forwardPower;
private EnumRfPowerRegulationMode _regulationMode;
private EnumRfPowerCommunicationMode _commMode;
private RD_TRIG _trigRfOnOff = new RD_TRIG();
private R_TRIG _trigError = new R_TRIG();
private R_TRIG _trigWarningMessage = new R_TRIG();
private R_TRIG _trigCommunicationError = new R_TRIG();
private R_TRIG _trigRetryConnect = new R_TRIG();
private PeriodicJob _thread;
private LinkedList<HandlerBase> _lstHandler = new LinkedList<HandlerBase>();
private object _locker = new object();
private bool _enableLog = true;
private bool _isHaloInstalled;
public AeRfPower(string module, string name) : base(module, name)
{
}
public override bool Initialize()
{
base.Initialize();
string portName = SC.GetStringValue($"{ScBasePath}.{Name}.Address");
int bautRate = SC.GetValue<int>($"{ScBasePath}.{Name}.BaudRate");
int dataBits = SC.GetValue<int>($"{ScBasePath}.{Name}.DataBits");
Enum.TryParse(SC.GetStringValue($"{ScBasePath}.{Name}.Parity"), out Parity parity);
Enum.TryParse(SC.GetStringValue($"{ScBasePath}.{Name}.StopBits"), out StopBits stopBits);
_deviceAddress = (byte)SC.GetValue<int>($"{ScBasePath}.{Name}.DeviceAddress");
_enableLog = SC.GetValue<bool>($"{ScBasePath}.{Name}.EnableLogMessage");
_connection = new AeRfPowerConnection(portName, bautRate, dataBits, parity, stopBits);
_connection.EnableLog(_enableLog);
if (_connection.Connect())
{
EV.PostInfoLog(Module, $"{Module}.{Name} connected");
}
_thread = new PeriodicJob(100, OnTimer, $"{Module}.{Name} MonitorHandler", true);
OP.Subscribe($"{Module}.{Name}.WaveModulation", (out string reason, int time, object[] args) =>
{
reason = "";
//if (!Enum.TryParse((string)args[0], out EnumRpsControlMode mode))
//{
// EV.PostAlarmLog(Module, $"{Module}.{Name} Can not mode, {args[0]} is not a valid mode value");
// return false;
//}
if (!PerformWaveModulation(out reason, time, ""))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set mode to {args[0]}");
return true;
});
OP.Subscribe($"{Module}.{Name}.PowerMode", (out string reason, int time, object[] args) =>
{
reason = "";
string mode = (string)args[0];
if (!PerformPowerMode(out reason, time, mode))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set mode to {mode}");
return true;
});
OP.Subscribe($"{Module}.{Name}.SetHighPower", (out string reason, int time, object[] args) =>
{
reason = "";
float value = Convert.ToSingle((string)args[0]);
if (!PerformSetHighPower(out reason, time, value))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set high power to {value}");
return true;
});
OP.Subscribe($"{Module}.{Name}.SetLowPower", (out string reason, int time, object[] args) =>
{
reason = "";
float value = Convert.ToSingle((string)args[0]);
if (!PerformSetLowPower(out reason, time, value))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set low power to {value}");
return true;
});
OP.Subscribe($"{Module}.{Name}.PulseFreq", (out string reason, int time, object[] args) =>
{
reason = "";
float value = Convert.ToSingle((string)args[0]);
if (!PerformPulseFreq(out reason, time, value))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set pulse frequency to {value}");
return true;
});
OP.Subscribe($"{Module}.{Name}.PulseDutyCycle", (out string reason, int time, object[] args) =>
{
reason = "";
float value = Convert.ToSingle((string)args[0]);
if (!PerformPulseDutyCycle(out reason, time, value))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set pulse duty cycle to {value}");
return true;
});
OP.Subscribe($"{Module}.{Name}.RampMode", (out string reason, int time, object[] args) =>
{
reason = "";
if (!PerformRampMode(out reason, time, ""))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set ramp mode to ");
return true;
});
OP.Subscribe($"{Module}.{Name}.RampUp", (out string reason, int time, object[] args) =>
{
reason = "";
if (!PerformRampUp(out reason, time, ""))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set ramp up");
return true;
});
OP.Subscribe($"{Module}.{Name}.RampDown", (out string reason, int time, object[] args) =>
{
reason = "";
if (!PerformRampDown(out reason, time, ""))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set ramp down");
return true;
});
OP.Subscribe($"{Module}.{Name}.WarningPower", (out string reason, int time, object[] args) =>
{
reason = "";
float value = Convert.ToSingle((string)args[0]);
if (!PerformWarningPower(out reason, time, value))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set warning power to {value}");
return true;
});
OP.Subscribe($"{Module}.{Name}.AlarmPower", (out string reason, int time, object[] args) =>
{
reason = "";
float value = Convert.ToSingle((string)args[0]);
if (!PerformAlarmPower(out reason, time, value))
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Can not set mode, {reason}");
return false;
}
EV.PostInfoLog(Module, $"{Module}.{Name} set alarm power to {value}");
return true;
});
return true;
}
private bool PerformWaveModulation(out string reason, int time, string mode)
{
reason = string.Empty;
return true;
}
private bool PerformAlarmPower(out string reason, int time, float value)
{
reason = string.Empty;
return true;
}
private bool PerformWarningPower(out string reason, int time, float value)
{
reason = string.Empty;
return true;
}
private bool PerformPowerMode(out string reason, int time, string mode)
{
reason = string.Empty;
return true;
}
private bool PerformSetHighPower(out string reason, int time, float value)
{
reason = string.Empty;
return true;
}
private bool PerformSetLowPower(out string reason, int time, float value)
{
reason = string.Empty;
return true;
}
private bool PerformPulseFreq(out string reason, int time, float value)
{
reason = string.Empty;
return true;
}
private bool PerformPulseDutyCycle(out string reason, int time, float value)
{
reason = string.Empty;
return true;
}
private bool PerformRampMode(out string reason, int time, string v)
{
reason = string.Empty;
return true;
}
private bool PerformRampUp(out string reason, int time, string mode)
{
reason = string.Empty;
return true;
}
private bool PerformRampDown(out string reason, int time, string mode)
{
reason = string.Empty;
return true;
}
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($"{ScBasePath}.{Name}.Address"));
if (!_connection.Connect())
{
EV.PostAlarmLog(Module, $"Can not connect with {_connection.Address}, {Module}.{Name}");
}
else
{
_lstHandler.AddLast(new AeRfPowerQueryPinHandler(this, _deviceAddress));
_lstHandler.AddLast(new AeRfPowerSetCommModeHandler(this, _deviceAddress, EnumRfPowerCommunicationMode.Host));
}
}
return true;
}
HandlerBase handler = null;
if (!_connection.IsBusy)
{
lock (_locker)
{
if (_lstHandler.Count == 0)
{
_lstHandler.AddLast(new AeRfPowerQueryCommModeHandler(this, _deviceAddress));
_lstHandler.AddLast(new AeRfPowerQueryForwardPowerHandler(this, _deviceAddress));
_lstHandler.AddLast(new AeRfPowerQueryReflectPowerHandler(this, _deviceAddress));
_lstHandler.AddLast(new AeRfPowerQueryStatusHandler(this, _deviceAddress));
_lstHandler.AddLast(new AeRfPowerQuerySetPointHandler(this, _deviceAddress));
}
if (_lstHandler.Count > 0)
{
handler = _lstHandler.First.Value;
_lstHandler.RemoveFirst();
}
}
if (handler != null)
{
_connection.Execute(handler);
}
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
return true;
}
public override void Monitor()
{
try
{
_connection.EnableLog(_enableLog);
_trigRfOnOff.CLK = _isOn;
if (_trigRfOnOff.R)
{
EV.PostInfoLog(Module, $"{Module}.{Name} is on");
}
if (_trigRfOnOff.T)
{
EV.PostInfoLog(Module, $"{Module}.{Name} is off");
}
//_trigError.CLK = IsError;
//if (_trigError.Q)
//{
// EV.PostAlarmLog(Module, $"{Module}.{Name} is error, error code {_errorCode:D3}");
//}
_trigCommunicationError.CLK = _connection.IsCommunicationError;
if (_trigCommunicationError.Q)
{
EV.PostAlarmLog(Module, $"{Module}.{Name} communication error, {_connection.LastCommunicationError}");
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
}
public override void Reset()
{
_trigError.RST = true;
_trigWarningMessage.RST = true;
_connection.SetCommunicationError(false, "");
_trigCommunicationError.RST = true;
_enableLog = SC.GetValue<bool>($"{ScBasePath}.{Name}.EnableLogMessage");
_trigRetryConnect.RST = true;
base.Reset();
}
public override void SetPower(float power)
{
lock (_locker)
{
_lstHandler.AddLast(new AeRfPowerSetPowerHandler(this, _deviceAddress, _isHaloInstalled ? (int)(power*10) : (int)power));
}
}
public override bool SetPowerOnOff(bool isOn, out string reason)
{
reason = "";
lock (_locker)
{
_lstHandler.AddLast(new AeRfPowerSwitchOnOffHandler(this, _deviceAddress, isOn));
}
return true;
}
public override void SetRegulationMode(EnumRfPowerRegulationMode mode)
{
lock (_locker)
{
_lstHandler.AddLast(new AeRfPowerSetRegulationModeHandler(this, _deviceAddress, mode));
}
}
internal void NoteError(string reason)
{
_trigWarningMessage.CLK = true;
if (_trigWarningMessage.Q)
{
EV.PostWarningLog(Module, $"{Module}.{Name} error, {reason}");
}
}
internal void NoteReflectPower(float reflect)
{
_reflectPower = reflect;
}
internal void NoteCommMode(EnumRfPowerCommunicationMode mode)
{
_commMode = mode;
}
internal void NoteStatus(byte[] data)
{
_isOn = (data[0] & 0x40) == 0x40;
}
internal void NoteRegulationModeSetPoint(EnumRfPowerRegulationMode regMode)
{
_regulationMode = regMode;
}
internal void NotePowerSetPoint(int power)
{
_powerSetPoint = power;
}
internal void NoteForwardPower(int power)
{
_forwardPower = power;
}
internal void NoteHaloInstalled(bool isInstalled)
{
_isHaloInstalled = isInstalled;
}
}
public enum EnumRfPowerCommunicationMode
{
Undefined,
Host = 2,
UserPort = 4, //Analog
Diagnostic = 8,
DeviceNet = 16,
EtherCat32 = 32,
}
}
@@ -0,0 +1,95 @@
using System.Collections.Generic;
using System.IO.Ports;
using Aitex.Core.RT.Log;
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFs.AE
{
public class AeRfPowerMessage : BinaryMessage
{
public byte Header { get; set; }
public byte CommandNumber { get; set; }
public byte OptionLength { get; set; }
public byte[] Data { get; set; }
public byte CheckSum { get; set; }
public int Address { get; set; }
public int DataLength { get; set; }
public int MessageLength { get; set; }
}
public class AeRfPowerConnection : SerialPortConnectionBase
{
private List<byte> _lstCacheBuffer = new List<byte>();
public AeRfPowerConnection(string portName, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One)
: base(portName, baudRate, dataBits, parity, stopBits, "\r", false)
{
}
public override bool SendMessage(byte[] message)
{
_lstCacheBuffer.Clear();
return base.SendMessage(message);
}
protected override MessageBase ParseResponse(byte[] rawBuffer)
{
_lstCacheBuffer.AddRange(rawBuffer);
AeRfPowerMessage msg = new AeRfPowerMessage();
msg.RawMessage = rawBuffer;
if (_lstCacheBuffer.Count >= 1 && _lstCacheBuffer[0] == 0x06)
{
msg.IsAck = true;
_lstCacheBuffer.RemoveAt(0);
}
if (_lstCacheBuffer.Count < 4)
{
return msg;
}
msg.Header = _lstCacheBuffer[0];
msg.CommandNumber = _lstCacheBuffer[1];
msg.OptionLength = _lstCacheBuffer[2];
msg.Address = _lstCacheBuffer[0] >> 3;
msg.DataLength = (byte)(0x07 & _lstCacheBuffer[0]);
msg.MessageLength = 3 + msg.DataLength ;//3=包头+Cmd+校验
if (msg.DataLength >= 7)
{
msg.DataLength = _lstCacheBuffer[2];
msg.MessageLength = 4 + msg.DataLength ;//4=包头+Cmd+length+校验
}
if (_lstCacheBuffer.Count < msg.MessageLength)
return msg;
msg.Data = _lstCacheBuffer.GetRange(msg.DataLength >= 7 ? 3 : 2, msg.DataLength).ToArray();
byte sum = 0x00;
for (var i = 0; i < msg.MessageLength - 1; i++)
{
sum ^= _lstCacheBuffer[i];
}
if (_lstCacheBuffer[msg.MessageLength - 1] != sum)
{
LOG.Error($"check sum failed, ");
msg.IsFormatError = true;
_lstCacheBuffer.Clear();
return msg;
}
msg.IsResponse = true;
_lstCacheBuffer.RemoveRange(0, msg.MessageLength);
return msg;
}
}
}
@@ -0,0 +1,440 @@
using System.Collections.Generic;
using Aitex.Core.Common.DeviceData;
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFs.AE
{
public abstract class AeRfPowerHandler : HandlerBase
{
public AeRfPower Device { get; }
private byte _address;
private byte _command;
protected AeRfPowerHandler(AeRfPower device, byte address, byte command, byte[] data)
: base(BuildMessage(address, command, data))
{
Device = device;
_address = address;
_command = command;
}
private static byte[] BuildMessage(byte address, byte command, byte[] data)
{
List<byte> buffer = new List<byte>();
buffer.Add((byte)((address << 3) + (data == null ? 0 : data.Length)));
buffer.Add(command);
if (data != null && data.Length > 0)
{
buffer.AddRange(data);
}
buffer.Add(CalcSum(buffer, buffer.Count));
return buffer.ToArray();
}
//host->unit, unit->host(ack), unit->host(csr), host->unit(ack)
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
AeRfPowerMessage response = msg as AeRfPowerMessage;
ResponseMessage = msg;
if (response.IsAck)
{
SetState(EnumHandlerState.Acked);
}
if (response.Address != _address || response.CommandNumber != _command)
{
transactionComplete = false;
return false;
}
if (response.IsResponse)
{
if (response.DataLength >= 1)
{
ParseData(response);
}
SendAck();
SetState(EnumHandlerState.Completed);
transactionComplete = true;
return true;
}
transactionComplete = false;
return false;
}
protected virtual void ParseData(AeRfPowerMessage msg)
{
if (msg.Data[0] != 0)
{
var reason = TranslateCsrCode(msg.Data[0]);
Device.NoteError(reason);
}
}
public void SendAck()
{
Device.Connection.SendMessage(new byte[] { 0x06 });
}
private static byte CalcSum(List<byte> data, int length)
{
byte ret = 0x00;
for (var i = 0; i < length; i++)
{
ret ^= data[i];
}
return ret;
}
protected string TranslateCsrCode(int csrCode)
{
string ret = csrCode.ToString();
switch (csrCode)
{
case 0:
ret = null;//"Command accepted";
break;
case 1:
ret = "Control Code Is Incorrect";
break;
case 2:
ret = "Output Is On(Change Not Allowed)";
break;
case 4:
ret = "Data Is Out Of Range";
break;
case 7:
ret = "Active Fault(s) Exist";
break;
case 9:
ret = "Data Byte Count Is Incorrect";
break;
case 19:
ret = "Recipe Is Active(Change Not Allowed)";
break;
case 50:
ret = "The Frequency Is Out Of Range";
break;
case 51:
ret = "The Duty Cycle Is Out Of Range";
break;
case 53:
ret = "The Device Controlled By The Command Is Not Detected";
break;
case 99:
ret = "Command Not Accepted(There Is No Such Command)";
break;
default:
break;
}
return ret;
}
}
//1 off, 2 on
public class AeRfPowerSwitchOnOffHandler : AeRfPowerHandler
{
public AeRfPowerSwitchOnOffHandler(AeRfPower device, byte address, bool isOn)
: base(device, address, isOn ? (byte)0x02 : (byte)0x01, null)
{
Name = "Switch " + (isOn ? "On" : "Off");
}
}
//3 regulation mode
public class AeRfPowerSetRegulationModeHandler : AeRfPowerHandler
{
public AeRfPowerSetRegulationModeHandler(AeRfPower device, byte address, EnumRfPowerRegulationMode mode)
: base(device, address, 3, new byte[]{ GetMode(mode) })
{
Name = "set regulation mode";
}
private static byte GetMode(EnumRfPowerRegulationMode mode)
{
switch (mode)
{
case EnumRfPowerRegulationMode.DcBias:
return 8;
case EnumRfPowerRegulationMode.Forward:
return 6;
case EnumRfPowerRegulationMode.Load:
return 7;
case EnumRfPowerRegulationMode.VALimit:
return 9;
}
return 0;
}
}
//8 set power
public class AeRfPowerSetPowerHandler : AeRfPowerHandler
{
public AeRfPowerSetPowerHandler(AeRfPower device, byte address, int power)
: base(device, address, 8, BuildData(power))
{
Name = "set power";
}
private static byte[] BuildData(int power)
{
return new byte[]{(byte)power, (byte)(power >> 8)};
}
}
//14 set communication mode
public class AeRfPowerSetCommModeHandler : AeRfPowerHandler
{
public AeRfPowerSetCommModeHandler(AeRfPower device, byte address, EnumRfPowerCommunicationMode mode)
: base(device, address, 14, BuildData(mode))
{
Name = "set communication mode";
}
private static byte[] BuildData(EnumRfPowerCommunicationMode mode)
{
byte value = 0;
switch (mode)
{
case EnumRfPowerCommunicationMode.DeviceNet:
value = 16;
break;
case EnumRfPowerCommunicationMode.Diagnostic:
value = 8;
break;
case EnumRfPowerCommunicationMode.EtherCat32:
value = 32;
break;
case EnumRfPowerCommunicationMode.Host:
value = 2;
break;
case EnumRfPowerCommunicationMode.UserPort:
value = 4;
break;
}
return new byte[] { value };
}
}
//13 set caps control mode
public class AeRfPowerSetCapsCtrlModeHandler : AeRfPowerHandler
{
public AeRfPowerSetCapsCtrlModeHandler(AeRfPower device, byte address, byte mode)
: base(device, address, 13, BuildData(mode))
{
Name = "set caps control mode";
}
private static byte[] BuildData(byte mode)
{
return new byte[] { mode == 0x01 ? (byte)0x01 : (byte)0x00 };
}
}
//112 set load
public class AeRfPowerSetLoadHandler : AeRfPowerHandler
{
public AeRfPowerSetLoadHandler(AeRfPower device, byte address, int data)
: base(device, address, 112, BuildData(data))
{
Name = "set load";
}
private static byte[] BuildData(int data)
{
return new byte[] { (byte)data, (byte)(data >> 8) };
}
}
//122 set tune
public class AeRfPowerSetTuneHandler : AeRfPowerHandler
{
public AeRfPowerSetTuneHandler(AeRfPower device, byte address, int data)
: base(device, address, 122, BuildData(data))
{
Name = "set tune";
}
private static byte[] BuildData(int data)
{
return new byte[] { (byte)data, (byte)(data >> 8) };
}
}
//155 query comm mode
public class AeRfPowerQueryCommModeHandler : AeRfPowerHandler
{
public AeRfPowerQueryCommModeHandler(AeRfPower device, byte address)
: base(device, address, 155, null)
{
Name = "query comm mode";
}
protected override void ParseData(AeRfPowerMessage response)
{
if (response.DataLength != 1)
{
Device.NoteError($"{Name}, return data length {response.DataLength}");
}
else
{
EnumRfPowerCommunicationMode mode = EnumRfPowerCommunicationMode.Undefined;
switch (response.Data[0])
{
case 2:
mode = EnumRfPowerCommunicationMode.Host;
break;
case 4:
mode = EnumRfPowerCommunicationMode.UserPort;
break;
case 8:
mode = EnumRfPowerCommunicationMode.Diagnostic;
break;
case 16:
mode = EnumRfPowerCommunicationMode.DeviceNet;
break;
case 32:
mode = EnumRfPowerCommunicationMode.EtherCat32;
break;
}
Device.NoteCommMode(mode);
}
}
}
//162 query status
public class AeRfPowerQueryStatusHandler : AeRfPowerHandler
{
public AeRfPowerQueryStatusHandler(AeRfPower device, byte address)
: base(device, address, 162, null)
{
Name = "query status";
}
protected override void ParseData(AeRfPowerMessage response)
{
if (response.DataLength != 4)
{
Device.NoteError($"{Name}, return data length {response.DataLength}");
}
else
{
Device.NoteStatus(response.Data);
}
}
}
//164 query setpoint
public class AeRfPowerQuerySetPointHandler : AeRfPowerHandler
{
public AeRfPowerQuerySetPointHandler(AeRfPower device, byte address)
: base(device, address, 164, null)
{
Name = "query setpoint";
}
protected override void ParseData(AeRfPowerMessage response)
{
if (response.DataLength != 3)
{
Device.NoteError($"{Name}, return data length {response.DataLength}");
}
else
{
EnumRfPowerRegulationMode regMode = EnumRfPowerRegulationMode.Undefined;
switch (response.Data[2])
{
case 6:
regMode = EnumRfPowerRegulationMode.Forward;
break;
case 7:
regMode = EnumRfPowerRegulationMode.Load;
break;
case 8:
regMode = EnumRfPowerRegulationMode.DcBias;
break;
case 9:
regMode = EnumRfPowerRegulationMode.VALimit;
break;
}
Device.NoteRegulationModeSetPoint(regMode);
Device.NotePowerSetPoint(response.Data[0] + (response.Data[1] << 8));
}
}
}
//165 forward power
public class AeRfPowerQueryForwardPowerHandler : AeRfPowerHandler
{
public AeRfPowerQueryForwardPowerHandler(AeRfPower device, byte address)
: base(device, address, 165, null)
{
Name = "Query forward power";
}
protected override void ParseData(AeRfPowerMessage response)
{
if (response.DataLength != 2)
{
Device.NoteError($"query forward power, return data length {response.DataLength}");
}
else
{
Device.NoteForwardPower( response.Data[0] + (response.Data[1] << 8));
}
}
}
//166 reflect power
public class AeRfPowerQueryReflectPowerHandler : AeRfPowerHandler
{
public AeRfPowerQueryReflectPowerHandler(AeRfPower device, byte address)
: base(device, address, 166, null)
{
Name = "Query reflect power";
}
protected override void ParseData(AeRfPowerMessage response)
{
if (response.DataLength != 2)
{
Device.NoteError($"{Name}, return data length {response.DataLength}");
}
else
{
Device.NoteReflectPower(response.Data[0] + (response.Data[1] << 8));
}
}
}
//221 query PIN number
public class AeRfPowerQueryPinHandler : AeRfPowerHandler
{
public AeRfPowerQueryPinHandler(AeRfPower device, byte address)
: base(device, address, 221, null)
{
Name = "Query PIN number";
}
protected override void ParseData(AeRfPowerMessage response)
{
if (response.DataLength != 32)
{
Device.NoteError($"query pin number, return data length {response.DataLength}");
}
else
{
Device.NoteHaloInstalled(response.Data[20]==0x31);
}
}
}
}
@@ -0,0 +1,451 @@
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
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 MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Common;
using Newtonsoft.Json;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFs.TruPlasmaRF
{
public class TruPlasmaRF : SerialPortDevice, IConnection
{
public string Address { get; }
public bool IsConnected { get; }
public bool Connect()
{
return true;
}
public bool Disconnect()
{
return true;
}
public string PortStatus { get; set; } = "Closed";
private TruPlasmaRFConnection _connection;
public TruPlasmaRFConnection Connection
{
get { return _connection; }
}
private R_TRIG _trigError = new R_TRIG();
private R_TRIG _trigCommunicationError = new R_TRIG();
private R_TRIG _trigRetryConnect = new R_TRIG();
private PeriodicJob _thread;
private LinkedList<HandlerBase> _lstHandler = new LinkedList<HandlerBase>();
private LinkedList<HandlerBase> _lstMonitorHandler = new LinkedList<HandlerBase>();
public List<IOResponse> IOResponseList { get; set; } = new List<IOResponse>();
private object _locker = new object();
private bool _enableLog;
private string _scRoot;
public TruPlasmaRF(string module, string name, string scRoot, string portName) : base(module, name)
{
_scRoot = scRoot;
PortName = portName;
}
private void ResetPropertiesAndResponses()
{
foreach (var ioResponse in IOResponseList)
{
ioResponse.ResonseContent = null;
ioResponse.ResonseRecievedTime = DateTime.Now;
}
}
public override bool Initialize(string portName)
{
base.Initialize(portName);
ResetPropertiesAndResponses();
if (_connection != null && _connection.IsConnected && PortName == portName)
return true;
if (_connection != null && _connection.IsConnected)
_connection.Disconnect();
PortName = portName;
_enableLog = SC.GetValue<bool>($"{_scRoot}.{Module}.{Name}.EnableLogMessage");
_connection = new TruPlasmaRFConnection(PortName);
_connection.EnableLog(_enableLog);
if (_connection.Connect())
{
PortStatus = "Open";
EV.PostInfoLog(Module, $"{Module}.{Name} connected");
}
_thread = new PeriodicJob(100, OnTimer, $"{Module}.{Name} MonitorHandler", true);
return true;
}
public bool InitConnection(string portName, int bautRate, int dataBits, Parity parity, StopBits stopBits)
{
_connection = new TruPlasmaRFConnection(portName, bautRate, dataBits, parity, stopBits);
if (_connection.Connect())
{
EV.PostInfoLog(Module, $"{Module}.{Name} connected");
}
_thread = new PeriodicJob(100, OnTimer, $"{Module}.{Name} MonitorHandler", true);
return true;
}
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($"{ScBasePath}.{Name}.Address"));
if (!_connection.Connect())
{
EV.PostAlarmLog(Module, $"Can not connect with {_connection.Address}, {Module}.{Name}");
}
else
{
//_lstHandler.AddLast(new TruPlasmaRFQueryPinHandler(this, _deviceAddress));
//_lstHandler.AddLast(new TruPlasmaRFSetCommModeHandler(this, _deviceAddress, EnumRfPowerCommunicationMode.Host));
}
}
return true;
}
HandlerBase handler = null;
if (!_connection.IsBusy)
{
lock (_locker)
{
if (_lstHandler.Count == 0)
{
foreach (var monitorHandler in _lstMonitorHandler)
{
_lstHandler.AddLast(monitorHandler);
}
}
if (_lstHandler.Count > 0)
{
handler = _lstHandler.First.Value;
_lstHandler.RemoveFirst();
}
}
if (handler != null)
{
_connection.Execute(handler);
}
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
return true;
}
internal void NoteInterfaceActived(bool actived)
{
InterfaceActived = actived;
}
internal void NoteAnyCommandResult(string result)
{
AnyCommandResult = result;
}
public override void Monitor()
{
try
{
//_connection.EnableLog(_enableLog);
_trigCommunicationError.CLK = _connection.IsCommunicationError;
if (_trigCommunicationError.Q)
{
EV.PostAlarmLog(Module, $"{Module}.{Name} communication error, {_connection.LastCommunicationError}");
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
}
public override void Reset()
{
_trigError.RST = true;
_connection.SetCommunicationError(false, "");
_trigCommunicationError.RST = true;
//_enableLog = SC.GetValue<bool>($"{ScBasePath}.{Name}.EnableLogMessage");
_trigRetryConnect.RST = true;
base.Reset();
}
public override bool Home(out string reason)
{
return base.Home(out reason);
}
#region Command Functions
public void PerformRawCommand(string command, string comandArgument)
{
lock (_locker)
{
_lstHandler.AddLast(new TruPlasmaRFRawCommandHandler(this, command, comandArgument));
}
}
internal void NotePiValue(int value)
{
PiValue = value;
}
internal void NoteSetPiValueCompleted(bool value)
{
SetPiValueCompleted = value;
}
public void PerformRawCommand(string command)
{
lock (_locker)
{
_lstHandler.AddLast(new TruPlasmaRFRawCommandHandler(this, command));
}
}
public void GetControl()
{
lock (_locker)
{
_lstHandler.AddLast(new TruPlasmaRFGetControlHandler(this));
}
}
public void ReleaseControl()
{
lock (_locker)
{
_lstHandler.AddLast(new TruPlasmaRFReleaseControlHandler(this));
}
}
public void PreSetPiValue(string piValue)
{
PreSetPiValue(int.Parse(piValue));
}
public void PreSetPiValue(int piValue)
{
lock (_locker)
{
_lstHandler.AddLast(new TruPlasmaRFPreSetPiValueHandler(this, piValue));
}
}
public void ReadPiValue(bool isSelected)
{
lock (_locker)
{
var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(TruPlasmaRFReadPiValueHandler));
if (isSelected)
{
if (!existHandlers.Any())
_lstMonitorHandler.AddFirst(new TruPlasmaRFReadPiValueHandler(this));
}
else
{
if (existHandlers.Any())
{
_lstMonitorHandler.Remove(existHandlers.First());
}
}
}
}
public void ExecuteAnyCommand(TruPlasmaRFArugment rfArg)
{
lock (_locker)
{
_lstHandler.AddLast(new TruPlasmaRFExecuteAnyCommandHandler(this, JsonConvert.SerializeObject(rfArg)));
}
}
public void ExecuteAnyCommand(object rfArg)
{
lock (_locker)
{
_lstHandler.AddLast(new TruPlasmaRFExecuteAnyCommandHandler(this, rfArg.ToString()));
}
}
public void MonitorRawCommand(bool isSelected, string command, string comandArgument)
{
lock (_locker)
{
var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(TruPlasmaRFRawCommandHandler) && ((TruPlasmaRFHandler)handler)._command == command);
if (isSelected)
{
if (!existHandlers.Any())
_lstMonitorHandler.AddFirst(new TruPlasmaRFRawCommandHandler(this, command, comandArgument));
}
else
{
if (existHandlers.Any())
{
_lstMonitorHandler.Remove(existHandlers.First());
}
}
}
}
public void MonitorRawCommand(bool isSelected, string command)
{
lock (_locker)
{
var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(TruPlasmaRFRawCommandHandler) && ((TruPlasmaRFHandler)handler)._command == command);
if (isSelected)
{
if (!existHandlers.Any())
_lstMonitorHandler.AddFirst(new TruPlasmaRFRawCommandHandler(this, command));
}
else
{
if (existHandlers.Any())
{
_lstMonitorHandler.Remove(existHandlers.First());
}
}
}
}
#endregion
#region Properties
public string Error { get; private set; }
public bool InterfaceActived { get; private set; }
public string AnyCommandResult { get; private set; }
public int PiValue { get; private set; }
public bool SetPiValueCompleted { get; private set; }
#endregion
#region Note Functions
private R_TRIG _trigWarningMessage = new R_TRIG();
public void NoteError(string reason)
{
if (reason != null)
{
_trigWarningMessage.CLK = true;
if (_trigWarningMessage.Q)
{
EV.PostWarningLog(Module, $"{Module}.{Name} error, {reason}");
}
Error = reason;
}
else
{
Error = null;
}
}
internal void NoteRawCommandInfo(string command, string data)
{
var curIOResponse = IOResponseList.Find(res => res.SourceCommandName == command);
if (curIOResponse != null)
{
IOResponseList.Remove(curIOResponse);
}
IOResponseList.Add(new IOResponse() { SourceCommand = command, ResonseContent = data, ResonseRecievedTime = DateTime.Now });
}
#endregion
}
public class DOB
{
/// <summary>
///
/// </summary>
public string Index { get; set; }
/// <summary>
///
/// </summary>
public string SubIndex { get; set; }
/// <summary>
///
/// </summary>
public string Status { get; set; }
/// <summary>
///
/// </summary>
public string Type { get; set; }
/// <summary>
///
/// </summary>
public string Data { get; set; }
}
public class TruPlasmaRFArugment
{
public string Command { get; set; }
/// <summary>
///
/// </summary>
public List<DOB> DOBList { get; set; }
}
}
@@ -0,0 +1,102 @@
using System.IO.Ports;
using System.Linq;
using Aitex.Core.RT.Log;
using MECF.Framework.Common.Communications;
using MECF.Framework.Common.Utilities;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFs.TruPlasmaRF
{
public class TruPlasmaRFMessage : BinaryMessage
{
public string Command { get; set; }
public string ErrorCode { get; set; }
public byte[] Data { get; set; }
}
public class TruPlasmaRFConnection : SerialPortConnectionBase
{
private static byte _start = 0xAA;
//private static byte _address = 0x02;
//private static byte _GS = 0x00;
private static byte _stop = 0x55;
private static byte _ack = 0x06;
public TruPlasmaRFConnection(string portName, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One)
: base(portName, baudRate, dataBits, parity, stopBits, "", false)
{
}
public override bool SendMessage(byte[] message)
{
return base.SendMessage(message);
}
protected override MessageBase ParseResponse(byte[] rawMessage)
{
TruPlasmaRFMessage msg = new TruPlasmaRFMessage();
msg.RawMessage = rawMessage;
//msg.Data = rawMessage;
if (rawMessage.Length == 1 && rawMessage[0] == _ack)
{
msg.IsResponse = true;
msg.IsAck = true;
return msg;
}
if (rawMessage.Length < 11)
{
msg.IsFormatError = true;
LOG.Error($"invalid response");
return msg;
}
if (rawMessage[0] != _start )
{
msg.IsFormatError = true;
LOG.Error($"invalid start byte");
return msg;
}
if (rawMessage.Last() != _stop)
{
msg.IsFormatError = true;
LOG.Error($"invalid stop byte");
return msg;
}
var contentBuffer = rawMessage.Skip(3).Take(rawMessage.Length - 6).ToArray();
var checkSum = Crc16.Crc16Ccitt(contentBuffer);
var recSum = rawMessage[rawMessage.Length - 3] * 256 + rawMessage[rawMessage.Length - 2];
//if(recSum != checkSum)
//{
// LOG.Error($"check sum failed,");
// msg.IsFormatError = true;
// return msg;
//}
if (rawMessage[8] != 0xFF)
{
msg.IsError = true;
msg.ErrorCode = rawMessage[8].ToString("X2");
}
//var msgArray = rawMessage.Select(bt => bt.ToString("X2")).ToArray();
//string msgCommand = string.Join(",", msgArray, 4, 4);
//msg.Command = msgCommand;
//if(rawMessage.Length > 11)
// msg.Data = rawMessage.Skip(8).Take(rawMessage.Length - 11).ToArray();
msg.IsResponse = true;
msg.IsAck = true;
msg.IsComplete = true;
return msg;
}
}
}
@@ -0,0 +1,268 @@
using MECF.Framework.Common.Communications;
using MECF.Framework.Common.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFs.TruPlasmaRF
{
public abstract class TruPlasmaRFHandler : HandlerBase
{
public TruPlasmaRF Device { get; }
public string _command;
protected string _parameter;
protected TruPlasmaRFHandler(TruPlasmaRF device, string command, string parameter = null)
: base(BuildMessage(ToByteArray(command), ToByteArray(parameter)))
{
Device = device;
_command = command;
_parameter = parameter;
Name = command;
}
protected TruPlasmaRFHandler(TruPlasmaRF device, string command, byte[] parameter)
: base(BuildMessage(ToByteArray(command), parameter))
{
Device = device;
_command = command;
//_parameter = parameter;
Name = command;
}
private static byte _start = 0xAA;
private static byte _address = 0x02;
private static byte _GS = 0x00;
private static byte _stop = 0x55;
private static byte[] BuildMessage(byte[] commandArray, byte[] argumentArray)
{
List<byte> buffer = new List<byte>();
buffer.Add(_start);
buffer.Add(_address);
int length = 1 + (commandArray != null ? commandArray.Length : 0) + (argumentArray != null ? argumentArray.Length : 0);
buffer.Add((byte)length);
buffer.Add(_GS);
if (commandArray != null && commandArray.Length > 0)
{
//skip ManualExecuteCommand
if (!(commandArray.Length == 1 && commandArray[0] == 0))
{
buffer.AddRange(commandArray);
}
}
if (argumentArray != null && argumentArray.Length > 0)
{
buffer.AddRange(argumentArray);
}
var contentBuffer = buffer.Skip(3).Take(buffer.Count - 3).ToArray();
//var checkSum = Crc16.CRC16_CCITT(contentBuffer);
var checkSum = Crc16.Crc16Ccitt(contentBuffer);
buffer.AddRange(BitConverter.GetBytes(checkSum));
buffer.Add(_stop);
return buffer.ToArray();
}
protected static string BuildCommandParameter(string jsonParameter)
{
var truArgObject = JsonConvert.DeserializeObject<TruPlasmaRFArugment>(jsonParameter);
JObject jsonObject = JObject.Parse(jsonParameter);
List<string> commandList = new List<string>();
commandList.Add(truArgObject.Command);
foreach(var dob in truArgObject.DOBList)
{
if(dob.Index != null)
{
commandList.Add(dob.Index.Substring(0,2));
commandList.Add(dob.Index.Substring(2));
}
if (dob.SubIndex != null)
{
commandList.Add(dob.SubIndex);
}
if (dob.Status != null)
{
commandList.Add(dob.Status);
}
if (dob.Type != null)
{
commandList.Add(dob.Type);
}
if (dob.Data != null)
{
var charArray = dob.Data.ToArray();
for (int i = 0; i < charArray.Length - 1; i += 2)
{
commandList.Add(charArray[i].ToString() + charArray[i + 1].ToString());
}
}
}
return string.Join(",", commandList.ToArray());
}
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
TruPlasmaRFMessage response = msg as TruPlasmaRFMessage;
ResponseMessage = msg;
if (response.IsError)
{
Device.NoteError(response.ErrorCode);
}
else
{
Device.NoteError(null);
}
if (response.IsAck)
{
SetState(EnumHandlerState.Acked);
}
if (this.IsAcked && response.IsComplete)
{
SetState(EnumHandlerState.Completed);
transactionComplete = true;
return true;
}
transactionComplete = false;
return false;
}
protected static byte[] ToByteArray(string parameter)
{
if (parameter == null)
return new byte[] { };
return parameter.Split(',').Select(para => Convert.ToByte(para, 16)).ToArray();
}
protected static byte[] IntToByteArray(int num)
{
byte[] bytes = BitConverter.GetBytes(num);
return bytes;
}
protected int ByteArrayToInt(byte[] bytes)
{
int temp = BitConverter.ToInt32(bytes, 0);
return temp;
}
}
public class TruPlasmaRFExecuteAnyCommandHandler : TruPlasmaRFHandler
{
public TruPlasmaRFExecuteAnyCommandHandler(TruPlasmaRF device, string jsonParameter)
: base(device, BuildCommandParameter(jsonParameter))
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (base.HandleMessage(msg, out handled))
{
var result = msg as TruPlasmaRFMessage;
Device.NoteAnyCommandResult(string.Join(",", result.RawMessage.Select(bt => bt.ToString("X2")).ToArray()));
}
return true;
}
}
public class TruPlasmaRFRawCommandHandler : TruPlasmaRFHandler
{
public TruPlasmaRFRawCommandHandler(TruPlasmaRF device, string command, string parameter = null)
: base(device, command, parameter)
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if(base.HandleMessage(msg, out handled))
{
var result = msg as TruPlasmaRFMessage;
Device.NoteRawCommandInfo(_command, string.Join(",", result.RawMessage.Select(bt => bt.ToString("X2")).ToArray()));
}
return true;
}
}
public class TruPlasmaRFGetControlHandler : TruPlasmaRFHandler
{
public TruPlasmaRFGetControlHandler(TruPlasmaRF device)
: base(device, "05,01,00,00", "FF")
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (base.HandleMessage(msg, out handled))
{
var result = msg as TruPlasmaRFMessage;
Device.NoteInterfaceActived(true);
}
return true;
}
}
public class TruPlasmaRFReleaseControlHandler : TruPlasmaRFHandler
{
public TruPlasmaRFReleaseControlHandler(TruPlasmaRF device)
: base(device, "05,02,00,00", "FF")
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (base.HandleMessage(msg, out handled))
{
var result = msg as TruPlasmaRFMessage;
Device.NoteInterfaceActived(false);
}
return true;
}
}
public class TruPlasmaRFPreSetPiValueHandler : TruPlasmaRFHandler
{
public TruPlasmaRFPreSetPiValueHandler(TruPlasmaRF device, int piValue)
: base(device, "02,06,00,01", IntToByteArray(piValue))
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (base.HandleMessage(msg, out handled))
{
var result = msg as TruPlasmaRFMessage;
Device.NoteSetPiValueCompleted(true);
}
return true;
}
}
public class TruPlasmaRFReadPiValueHandler : TruPlasmaRFHandler
{
public TruPlasmaRFReadPiValueHandler(TruPlasmaRF device)
: base(device, "01,12,00,01", "FF")
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (base.HandleMessage(msg, out handled))
{
var result = msg as TruPlasmaRFMessage;
Device.NotePiValue(ByteArrayToInt(result.RawMessage.Skip(10).Take(4).ToArray()));
}
return true;
}
}
}