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,873 @@
using System;
using System.Collections.Generic;
using System.Linq;
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.RT.EquipmentLibrary.HardwareUnits.Common;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.SMIFs.Brooks
{
public class BrooksSMIF : SerialPortDevice, IConnection
{
public string Address { get { return _address; } }
public bool IsConnected { get; }
public bool Connect()
{
return true;
}
public bool Disconnect()
{
return true;
}
public string PortStatus { get; set; } = "Closed";
private BrooksSMIFConnection _connection;
public BrooksSMIFConnection Connection
{
get { return _connection; }
}
public List<IOResponse> IOResponseList { get; set; } = new List<IOResponse>();
public int Axis { get; private set; }
public bool IsIdle { get; private set; }
public bool IsHomed { get; private set; }
public bool IsPodPresent { get; private set; }
public bool IsArmRetract { get; private set; }
public bool IsAlarm { get; private set; }
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>();
private object _locker = new object();
private bool _enableLog;
private string _errorCode="";
private DeviceTimer _setStatusTimer = new DeviceTimer();
private int SetStatusTime = 800;
private string _scRoot;
public BrooksSMIF(string module, string name, string scRoot) : base(module, name)
{
_scRoot = scRoot;
}
private void ResetPropertiesAndResponses()
{
Connected = null;
RobotStatus = null;
IsOnLine = null;
IsManual = null;
IsES = null;
MovingCompleted = null;
ACalCompleted = null;
AddressOutSide = null;
PositionOutSide = null;
EmergencyStop = null;
XLowerSide = null;
XUpperSide = null;
YLowerSide = null;
YUpperSide = null;
ZLowerSide = null;
ZUpperSide = null;
foreach (var ioResponse in IOResponseList)
{
ioResponse.ResonseContent = null;
ioResponse.ResonseRecievedTime = DateTime.Now;
}
}
internal void OnEventArrived(string eventData)
{
if (eventData == "POD_ARRIVED")
{
PodArrived = true;
}
else if (eventData == "POD_REMOVED")
{
PodRemoved = true;
}
else if (eventData == "BEGIN_FETCH")
{
FetchBegun = true;
}
else if (eventData == "CMPL_FETCH")
{
FetchCompleted = true;
}
else if (eventData == "BEGIN_LOAD")
{
LoadBegun = true;
}
else if (eventData == "ABORT_LOAD")
{
LoadAbort = true;
}
else if (eventData == "CMPL_LOAD")
{
LoadCompleted = true;
}
else if (eventData == "BEGIN_RECV_CASSETTE")
{
UnloadBegun = true;
}
else if (eventData == "ABORT_UNLOAD")
{
UnloadAbort = true;
}
else if (eventData == "RECV_CASSETTE")
{
UnloadCompleted = true;
}
else if (eventData == "BEGIN_HOME")
{
HomeBegun = true;
}
else if (eventData == "REACH_HOME")
{
HomeCompleted = true;
}
else if (eventData == "BEGIN_OPEN")
{
OpenBegun = true;
}
else if (eventData == "CMPL_OPEN")
{
OpenCompleted = true;
}
else if (eventData == "BEGIN_UNLOAD")
{
CloseBegun = true;
}
else if (eventData == "CMPL_UNLOAD")
{
CloseCompleted = true;
}
}
private static Dictionary<string, string> _RealyMessageDict = new Dictionary<string, string>()
{
{"OK","Comment accepted" },
{"BUSY","Command rejected, LPI is busy" },
{"ALARM","Command rejected, LPI in alarm state" },
{"NO_POD","Command rejected, Pod not on LPI" },
{"NOT_READY","Command rejected, Host interlock not enabled" },
{"INVALID_ARG","Command rejected, at least one invalid parameter" },
{"CANNOT_PERFORM","LPI not in the proper state to perform the Host command" },
{"DENIED","Command rejected for other reason" },
};
private static Dictionary<string, string> _AlarmTimeCodeDict = new Dictionary<string, string>()
{
{"00","No alarm" },
{"41","Alarm occurred during a fetch or open operation" },
{"42","Alarm occurred during a cassette placement on the process tool" },
{"43","Alarm occurred during a returning of the minienvironment to Home" },
{"44","Alarm occurred during a retrieval of the cassette from the Tool" },
{"45","Alarm occurred during a placement of the cassette on the Pod door" },
{"46","Non-recoverable fatal error" }
};
private static Dictionary<string, string> _ErrorCodeDict = new Dictionary<string, string>()
{
{"00","No error" },
{"01","Position following error" },
{"02","LPI not Home" },
{"03","LPI busy" },
{"04","Pod removed/missing elevator door" },
{"05","Aborted by user" },
{"07","Protrusion sensor failure" },
{"08","Slot sensor failure" },
{"09","Wafer presence sensor failure" },
{"10","Flash sensor failure" },
{"11"," Elevator over-travel limit trip" },
{"13","Excessive wafer protrusion" },
{"14","System internal time-out" },
{"15","Servo command error" },
{"16","Pod door open time-out" },
{"17","Pod door close time-out" },
{"18","Pod hold-down open time-out" },
{"19","Pod hold-down close time-out" },
{"20","Wafer seater failed to move toward wafer" },
{"21","Wafer seater failed to return to Home" },
{"22","Elevator failed to reach target position" },
{"24","System error" },
{"27","Loss of configuration data" },
{"28","Cassette not present" },
{"29","Loss of air flow" },
{"31","Gripper open time out" },
{"32","Gripper close time out" },
{"33","Interprocessor communication error" },
{"34","Gripper overtravel" },
{"35","Cassette found during unload" },
};
internal void OnAlarmArrived(string alarmData)
{
var alarmArray = alarmData.Split(' ');
if (alarmArray.Count() != 2)
return;
string alarmTimeCode = alarmArray[0].Substring(0, 2);
string alarmInfoCode = alarmArray[0].Substring(2, 2);
AlarmOccurTime = alarmTimeCode + "=" + _AlarmTimeCodeDict[alarmTimeCode];
AlarmInfo = alarmInfoCode + "=" + alarmArray[1];
IsAlarm = true;
}
public void SetError(string errorCode)
{
string alarmTimeCode = errorCode.Substring(0, 2);
string alarmInfoCode = errorCode.Substring(2, 2);
if (_AlarmTimeCodeDict.ContainsKey(alarmTimeCode))
AlarmOccurTime = _AlarmTimeCodeDict[alarmTimeCode];
else
AlarmOccurTime = alarmTimeCode;
if (_ErrorCodeDict.ContainsKey(alarmInfoCode))
AlarmInfo = _ErrorCodeDict[alarmInfoCode];
else
AlarmInfo = alarmInfoCode;
if(_errorCode != errorCode)
{
EV.PostAlarmLog(Module, $"{Module} {AlarmOccurTime}, for {AlarmInfo}");
}
_errorCode = errorCode;
IsAlarm = true;
}
public void SetStatus(bool isReady, bool isHomed, bool isPodPresent, bool isArmRetract)
{
if(_setStatusTimer.IsIdle() || _setStatusTimer.GetElapseTime() > SetStatusTime)
{
IsIdle = isReady;
IsHomed = isHomed;
IsPodPresent = isPodPresent;
IsArmRetract = isArmRetract;
}
}
private string _address = "";
public override bool Initialize()
{
ResetPropertiesAndResponses();
if (_connection != null && _connection.IsConnected)
return true;
if(string.IsNullOrEmpty(_scRoot))
{
PortName = SC.GetStringValue($"{Module}.DeviceAddress");
_enableLog = SC.GetValue<bool>($"{Module}.EnableLogMessage");
}
else
{
PortName = SC.GetStringValue($"{_scRoot}.{Module}.{Name}.DeviceAddress");
_enableLog = SC.GetValue<bool>($"{_scRoot}.{Module}.{Name}.EnableLogMessage");
}
_connection = new BrooksSMIFConnection(this, PortName);
_connection.EnableLog(_enableLog);
base.Initialize(PortName);
if (_connection.Connect())
{
PortStatus = "Open";
EV.PostInfoLog(Module, $"{Module}.{Name} connected");
}
_thread = new PeriodicJob(400, OnTimer, $"{Module}.{Name} MonitorHandler", true);
RequestStatus();
OP.Subscribe($"{Module}.Home", (string cmd, object[] args) =>
{
HomeSmif(out _);
return true;
});
OP.Subscribe($"{Module}.Abort", (string cmd, object[] args) =>
{
Stop();
return true;
});
OP.Subscribe($"{Module}.Reset", (string cmd, object[] args) =>
{
Reset();
return true;
});
OP.Subscribe($"{Module}.Unload", (string cmd, object[] args) =>
{
UnloadCassette(out _);
return true;
});
OP.Subscribe($"{Module}.Load", (string cmd, object[] args) =>
{
LoadCassette(out _);
return true;
});
return true;
}
internal void NoteConstant(string constantResult)
{
var constantResultArray = constantResult.Split('=');
if(constantResultArray.Count() != 2)
{
return;
}
if(constantResultArray[0] == "P13")
{
MSCInterlockMode = constantResultArray[1];
}
//else if....
}
private bool OnTimer()
{
try
{
//return true;
_connection.MonitorTimeout();
if (!_connection.IsConnected || _connection.IsCommunicationError)
{
lock (_locker)
{
_lstHandler.Clear();
}
_trigRetryConnect.CLK = !_connection.IsConnected;
if (_trigRetryConnect.Q)
{
if (string.IsNullOrEmpty(_scRoot))
{
_connection.SetPortAddress(SC.GetStringValue($"{Module}.DeviceAddress"));
}
else
{
_connection.SetPortAddress(SC.GetStringValue($"{_scRoot}.{Module}.{Name}.DeviceAddress"));
}
if (!_connection.Connect())
{
EV.PostAlarmLog(Module, $"Can not connect with {_connection.Address}, {Module}");
}
else
{
//_lstHandler.AddLast(new BrooksSMIFQueryPinHandler(this, _deviceAddress));
//_lstHandler.AddLast(new BrooksSMIFSetCommModeHandler(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 NoteStatus(string formCode, string status)
{
if(formCode == "FSD0")
{
SmifStatus = status;
}
else if (formCode == "FSD2")
{
CassetteMapInfo = status;
}
}
internal void NoteEnable(string parameter, bool isEnable)
{
if(parameter == "FETCH")
{
FetchEnable = isEnable;
}
else if (parameter == "LOAD")
{
LoadEnable = isEnable;
}
else if (parameter == "HOME")
{
HomeEnable = isEnable;
}
else if (parameter == "OPEN")
{
OpenEnable = isEnable;
}
else if (parameter == "UNLOAD")
{
UnloadEnable = isEnable;
}
else if (parameter == "CLOSE")
{
CloseEnable = isEnable;
}
}
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;
if(IsAlarm)
{
lock (_locker)
{
_lstHandler.AddFirst(new BrooksSMIFResetHandler(this));
}
}
IsAlarm = false;
base.Reset();
}
public override bool Home(out string reason)
{
return base.Home(out reason);
}
#region Command Functions
public void PerformRawCommand(string commandType,string command, string completeEvent, string comandArgument)
{
lock (_locker)
{
_lstHandler.AddLast(new BrooksSMIFRawCommandHandler(this, commandType, command, completeEvent, comandArgument));
}
}
public void EnableAction(string action, string isEnable)
{
lock (_locker)
{
_lstHandler.AddLast(new BrooksSMIFEnableActionHandler(this, action, bool.Parse(isEnable)));
}
}
public void FetchCassette()
{
lock (_locker)
{
if(!PodArrived || !FetchEnable )
{
EV.PostAlarmLog(Module, $"{Module}.{Name} Fetch Cassette conditon error");
return;
}
_lstHandler.AddFirst(new BrooksSMIFFetchCassetteHandler(this));
}
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
_setStatusTimer.Start(0);
}
public bool LoadCassette(out string reason)
{
reason = string.Empty;
if (!IsIdle)
{
reason = $"{Module} is busy";
return false;
}
lock (_locker)
{
//if (!LoadEnable)
//{
// EV.PostAlarmLog(Module, $"{Module}.{Name} Load Cassette conditon error");
// return;
//}
_lstHandler.AddFirst(new BrooksSMIFLoadCassetteHandler(this));
}
IsIdle = false;
IsArmRetract = false;
IsPodPresent = false;
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
_setStatusTimer.Start(0);
return true;
}
public bool HomeSmif(out string reason)
{
reason = string.Empty;
if(!IsIdle)
{
reason = $"{Module} is busy";
return false;
}
lock (_locker)
{
//if (!HomeEnable)
//{
// EV.PostAlarmLog(Module, $"{Module}.{Name} Home conditon error");
// return;
//}
//_lstHandler.AddLast(new BrooksSMIFHomeHandler(this));
_lstHandler.AddFirst(new BrooksSMIFRecoveryHandler(this));
}
IsIdle = false;
IsArmRetract = false;
IsHomed = false;
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
_setStatusTimer.Start(0);
return true;
}
public void Stop()
{
lock (_locker)
{
_lstHandler.AddFirst(new BrooksSMIFStopHandler(this));
}
IsIdle = false;
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
}
public void OpenPod()
{
lock (_locker)
{
if (!PodArrived || !OpenEnable)
{
EV.PostAlarmLog(Module, $"{Module}.{Name} OpenPod conditon error");
return;
}
_lstHandler.AddFirst(new BrooksSMIFOpenPodHandler(this));
}
IsIdle = false;
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
_setStatusTimer.Start(0);
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
_setStatusTimer.Start(0);
}
public bool UnloadCassette(out string reason)
{
reason = string.Empty;
if (!IsIdle)
{
reason = $"{Module} is busy";
return false;
}
lock (_locker)
{
//if (!UnloadEnable)
//{
// EV.PostAlarmLog(Module, $"{Module}.{Name} Unload Cassette conditon error");
// return;
//}
_lstHandler.AddFirst(new BrooksSMIFUnloadCassetteHandler(this));
}
IsIdle = false;
IsArmRetract = false;
IsPodPresent = false;
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
_setStatusTimer.Start(0);
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
_setStatusTimer.Start(0);
return true;
}
public void ClosePod()
{
lock (_locker)
{
if (!CloseEnable)
{
EV.PostAlarmLog(Module, $"{Module}.{Name} ClosePod conditon error");
return;
}
_lstHandler.AddFirst(new BrooksSMIFClosePodHandler(this));
}
IsIdle = false;
if (!_setStatusTimer.IsIdle())
_setStatusTimer.Stop();
_setStatusTimer.Start(0);
}
public void SendEvent(string command)
{
_connection.SendMessage("AERS " + command + "\r\n");
}
public void MonitorRawCommand(bool isSelected, string commandType, string command, string commandArgument)
{
lock (_locker)
{
var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(BrooksSMIFRawCommandHandler)
&& ((BrooksSMIFRawCommandHandler)handler)._commandType == commandType
&& ((BrooksSMIFRawCommandHandler)handler)._command == command
);
if (isSelected)
{
if (!existHandlers.Any())
_lstMonitorHandler.AddFirst(new BrooksSMIFRawCommandHandler(this, commandType, command, commandArgument));
}
else
{
if (existHandlers.Any())
{
_lstMonitorHandler.Remove(existHandlers.First());
}
}
}
}
public void RequestConstant(bool isSelected, string constantId)
{
lock (_locker)
{
var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(BrooksSMIFRequestConstantHandler));
if (isSelected)
{
if (!existHandlers.Any())
_lstMonitorHandler.AddFirst(new BrooksSMIFRequestConstantHandler(this, constantId));
}
else
{
if (existHandlers.Any())
{
_lstMonitorHandler.Remove(existHandlers.First());
}
}
}
}
public void RequestStatus(bool isSelected = true)
{
lock (_locker)
{
var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(BrooksSMIFRequestStatusHandler)
&& ((BrooksSMIFRequestStatusHandler)handler)._parameter.Contains("0"));
if (isSelected)
{
if (!existHandlers.Any())
_lstMonitorHandler.AddFirst(new BrooksSMIFRequestStatusHandler(this, 0));
}
else
{
if (existHandlers.Any())
{
_lstMonitorHandler.Remove(existHandlers.First());
}
}
}
}
public void RequestCassetteMap(bool isSelected)
{
lock (_locker)
{
var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(BrooksSMIFRequestStatusHandler)
&& ((BrooksSMIFRequestStatusHandler)handler)._parameter.Contains("2"));
if (isSelected)
{
if (!existHandlers.Any())
_lstMonitorHandler.AddFirst(new BrooksSMIFRequestStatusHandler(this, 2));
}
else
{
if (existHandlers.Any())
{
_lstMonitorHandler.Remove(existHandlers.First());
}
}
}
}
#endregion
#region Properties
public string Connected { get; private set; }
public string RobotStatus { get; private set; }
public string IsOnLine { get; private set; }
public string IsManual { get; private set; }
public string IsStop { get; private set; }
public string IsES { get; private set; }
public string MovingCompleted { get; private set; }
public string ACalCompleted { get; private set; }
public string AddressOutSide { get; private set; }
public string PositionOutSide { get; private set; }
public string EmergencyStop { get; private set; }
public string XLowerSide { get; private set; }
public string XUpperSide { get; private set; }
public string YLowerSide { get; private set; }
public string YUpperSide { get; private set; }
public string ZLowerSide { get; private set; }
public string ZUpperSide { get; private set; }
public bool PodArrived { get; private set; }
public bool PodRemoved { get; private set; }
public bool FetchBegun { get; private set; }
public bool FetchCompleted { get; private set; }
public bool FetchEnable { get; private set; }
public bool LoadEnable { get; private set; }
public bool LoadBegun { get; private set; }
public bool LoadAbort { get; private set; }
public bool LoadCompleted { get; private set; }
public bool UnloadEnable { get; private set; }
public bool UnloadBegun { get; private set; }
public bool UnloadAbort { get; private set; }
public bool UnloadCompleted { get; private set; }
public bool HomeEnable { get; private set; }
public bool HomeBegun { get; private set; }
public bool HomeCompleted { get; private set; }
public bool OpenEnable { get; private set; }
public bool OpenBegun { get; private set; }
public bool OpenCompleted { get; private set; }
public bool CloseEnable { get; private set; }
public bool CloseBegun { get; private set; }
public bool CloseCompleted { get; private set; }
public string AlarmOccurTime { get; private set; }
public string AlarmInfo { get; private set; }
public string MSCInterlockMode { get; private set; }
public string SmifStatus { get; private set; }
public string CassetteMapInfo { get; private set; }
#endregion
#region Note Functions
private R_TRIG _trigWarningMessage = new R_TRIG();
public void NoteError(string errorData)
{
if (errorData != null)
{
_trigWarningMessage.CLK = true;
if (_trigWarningMessage.Q)
{
EV.PostWarningLog(Module, $"{Module} error, {(_RealyMessageDict.ContainsKey(errorData) ? _RealyMessageDict[errorData] : errorData)}");
}
if (errorData.ToUpper() == "ALARM")
IsAlarm = true;
}
}
internal void NoteRawCommandInfo(string commandType, string command, string data, bool isAck)
{
var curIOResponse = IOResponseList.Find(res => res.SourceCommandType == commandType && res.SourceCommand == command);
if (curIOResponse != null)
{
IOResponseList.Remove(curIOResponse);
}
IOResponseList.Add(new IOResponse() { SourceCommandType = commandType, SourceCommand = command, ResonseContent = data, IsAck = isAck, ResonseRecievedTime = DateTime.Now });
}
#endregion
}
}
@@ -0,0 +1,102 @@
using System.IO.Ports;
using Aitex.Core.RT.Log;
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.SMIFs.Brooks
{
public class BrooksSMIFMessage : AsciiMessage
{
public string Data { get; set; }
public string ErrorText { get; set; }
public bool IsAlarm { get; set; }
}
public class BrooksSMIFConnection : SerialPortConnectionBase
{
//private bool _isAckMode = false;//should read from config file
private string _cachedBuffer = string.Empty;
BrooksSMIF _device;
public BrooksSMIFConnection(BrooksSMIF device, string portName, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One)
: base(portName, baudRate, dataBits, parity, stopBits, "\r\n", true)
{
_device = device;
}
public override bool SendMessage(byte[] message)
{
return base.SendMessage(message);
}
protected override MessageBase ParseResponse(string rawText)
{
BrooksSMIFMessage msg = new BrooksSMIFMessage();
msg.RawMessage = rawText;
rawText = rawText.Replace("\r","").Replace("\n", "");
if (rawText.Length <= 4)
{
LOG.Error($"empty response,");
msg.IsFormatError = true;
return msg;
}
msg.MessagePart = rawText.Split(' ');
if (msg.MessagePart.Length < 2)
{
LOG.Error($"too short response,");
msg.IsFormatError = true;
return msg;
}
if(msg.MessagePart[0] == "HCA")
{
if(msg.MessagePart[1] == "OK")
{
msg.IsAck = true;
}
else
{
msg.IsError = true;
}
msg.Data = msg.MessagePart[1];
}
else if(msg.MessagePart[0] == "AERS")
{
msg.IsEvent = true;
msg.Data = msg.MessagePart[1];
}
else if (msg.MessagePart[0] == "ARS")
{
if(msg.MessagePart[1] != "0000") //0000 means no alarm
{
msg.IsAlarm = true;
OnAlarmArrived(msg);
}
msg.Data = msg.MessagePart[1];
}
else if (msg.MessagePart[0] == "ECD")
{
msg.Data = msg.MessagePart[1];
}
else if (msg.MessagePart[0].Contains("FSD"))
{
msg.Data = rawText.Substring(5);
}
return msg;
}
protected override void OnEventArrived(MessageBase msg)
{
BrooksSMIFMessage message = msg as BrooksSMIFMessage;
_device.OnEventArrived(message.Data);
}
private void OnAlarmArrived(BrooksSMIFMessage msg)
{
_device.OnAlarmArrived(msg.Data);
}
}
}
@@ -0,0 +1,341 @@
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.SMIFs.Brooks
{
public abstract class BrooksSMIFHandler : HandlerBase
{
public BrooksSMIF Device { get; }
public string _commandType;
public string _command;
public string _parameter;
protected string _completeEvent;
protected BrooksSMIFHandler(BrooksSMIF device, string commandType,string command, string completeEvent = null,string parameter = null)
: base(BuildMessage(commandType, command, parameter))
{
Device = device;
_commandType = commandType;
_command = command;
_completeEvent = completeEvent;
_parameter = parameter;
Name = command;
}
private static string BuildMessage(string commandType, string command, string parameter)
{
string commandStr = commandType;
if(command != null)
{
commandStr += " " + command;
}
if (parameter != null)
{
commandStr += " " + parameter;
}
return commandStr + "\r\n";
}
protected static string F2S(float value)
{
return value < 0 ? value.ToString() : " " + value.ToString();
}
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
BrooksSMIFMessage response = msg as BrooksSMIFMessage;
ResponseMessage = msg;
if (msg.IsError)
{
Device.NoteError(response.Data);
}
else
{
Device.NoteError(null);
if(msg.IsAck)
{
this.SetState(EnumHandlerState.Acked);
}
if (_completeEvent == null)
{
if (this.IsAcked)
{
SetState(EnumHandlerState.Completed);
transactionComplete = true;
return true;
}
}
else if (this.IsAcked && msg.IsEvent && _completeEvent == response.Data)
{
SetState(EnumHandlerState.Completed);
transactionComplete = true;
return true;
}
}
transactionComplete = false;
return false;
}
}
public class BrooksSMIFRawCommandHandler : BrooksSMIFHandler
{
public BrooksSMIFRawCommandHandler(BrooksSMIF device, string commandType, string command, string completeEvent,string parameter = null)
: base(device, commandType, command, completeEvent,parameter)
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (base.HandleMessage(msg, out handled))
{
var result = msg as BrooksSMIFMessage;
Device.NoteRawCommandInfo(_commandType,_command, result.RawMessage, msg.IsAck);
ResponseMessage = msg;
handled = true;
}
return true;
}
}
public class BrooksSMIFEnableActionHandler : BrooksSMIFHandler
{
public BrooksSMIFEnableActionHandler(BrooksSMIF device, string action, bool isEnable)
: base(device, "HCS", isEnable? "ENABLE":"DISABLE",null, action)
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (base.HandleMessage(msg, out handled))
{
var result = msg as BrooksSMIFMessage;
Device.NoteEnable(_parameter, _command == "ENABLE");
}
return true;
}
}
public class BrooksSMIFFetchCassetteHandler : BrooksSMIFHandler
{
public BrooksSMIFFetchCassetteHandler(BrooksSMIF device)
: base(device, "HCS", "FETCH", "CMPL_FETCH")
{
}
}
public class BrooksSMIFLoadCassetteHandler : BrooksSMIFHandler
{
public BrooksSMIFLoadCassetteHandler(BrooksSMIF device)
: base(device, "HCS", "LOAD", null)
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
if (!base.HandleMessage(msg, out handled))
{
BrooksSMIFMessage response = msg as BrooksSMIFMessage;
if (response.Data.Contains("ABORT_LOAD"))
{
Device.NoteError("ABORT_LOAD");
handled = true;
}
}
return true;
}
}
public class BrooksSMIFHomeHandler : BrooksSMIFHandler
{
public BrooksSMIFHomeHandler(BrooksSMIF device)
: base(device, "HCS", "HOME", null)
{
}
}
public class BrooksSMIFRecoveryHandler : BrooksSMIFHandler
{
public BrooksSMIFRecoveryHandler(BrooksSMIF device)
: base(device, "HCS", "RECOVERY", null)
{
}
}
public class BrooksSMIFStopHandler : BrooksSMIFHandler
{
public BrooksSMIFStopHandler(BrooksSMIF device)
: base(device, "HCS", "STOP", null)
{
}
}
public class BrooksSMIFResetHandler : BrooksSMIFHandler
{
public BrooksSMIFResetHandler(BrooksSMIF device)
: base(device, "HCS", "RESET", null)
{
}
}
public class BrooksSMIFOpenPodHandler : BrooksSMIFHandler
{
public BrooksSMIFOpenPodHandler(BrooksSMIF device)
: base(device, "HCS", "OPEN", "CMPL_OPEN")
{
}
}
public class BrooksSMIFUnloadCassetteHandler : BrooksSMIFHandler
{
public BrooksSMIFUnloadCassetteHandler(BrooksSMIF device)
: base(device, "HCS", "UNLOAD", null)
{
}
//mabye need and the guide document miss this info ??
//public override bool HandleMessage(MessageBase msg, out bool handled)
//{
// if (!base.HandleMessage(msg, out handled))
// {
// BrooksSMIFMessage response = msg as BrooksSMIFMessage;
// if (response.Data.Contains("ABORT_UNLOAD"))
// {
// Device.NoteError("ABORT_UNLOAD");
// handled = true;
// }
// }
// return true;
//}
}
public class BrooksSMIFClosePodHandler : BrooksSMIFHandler
{
public BrooksSMIFClosePodHandler(BrooksSMIF device)
: base(device, "HCS", "CLOSE", "CMPL_UNLOAD")
{
}
}
public class BrooksSMIFRequestConstantHandler : BrooksSMIFHandler
{
public BrooksSMIFRequestConstantHandler(BrooksSMIF device, string constantId)
: base(device, "ECR", null, null, constantId)
{
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as BrooksSMIFMessage;
if (result.MessagePart[0] == "ECD")
{
msg.IsAck = true;
}
else
{
handled = false;
return false;
}
if (base.HandleMessage(msg, out handled))
{
Device.NoteConstant(result.MessagePart[1]);
}
return true;
}
}
public class BrooksSMIFRequestStatusHandler : BrooksSMIFHandler
{
int _formCode;
string AlarmId = "ALMID";//0000 = No alarm
string Mode = "MODE";//AUTO,MANUAL
string PodPresent = "PIP";//FALSE=no pod present,TRUE=pod present
string PortStatus = "PRTST";//UNLK=port unlocked,LOCK=port locked,OTHER=none of the above
string GripperStatus = "GRPST";//OPEN=gripper opened;CLOSE=gripper closed;OT=overtraveled;OTHER=none of the above
string Ready = "READY";//FALSE=busy;TRUE=ready for new command
string Home = "HOME";//FALSE=not home;TRUE=home
string Elevator = "ELUP";//FALSE=elevator not at home limit;TRUE=elevator at home limit
string ArmRetract = "ARM_RETR";//TRUE=arm retract;FALSE=arm not retract
public BrooksSMIFRequestStatusHandler(BrooksSMIF device, int formCode)
: base(device, "FSR", null, null, "FC="+formCode.ToString())
{
_formCode = formCode;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as BrooksSMIFMessage;
if (result.MessagePart[0].Contains($"FSD{_formCode}"))
{
msg.IsAck = true;
}
else
{
handled = false;
return false;
}
bool isPodPresent = false;
bool isReady = false;
bool isArmRetract = false;
bool isHomed = false;
for (int i = 0;i< result.MessagePart.Length;i++)
{
var statusArray = result.MessagePart[i].Split('=');
if (statusArray.Length != 2)
continue;
if (statusArray[0] == AlarmId)
{
if (statusArray[1] != "0000")
Device.SetError(statusArray[1]);
}
else if (statusArray[0] == Mode)
{
}
else if (statusArray[0] == PodPresent)
{
if (statusArray[1].ToUpper() == "TRUE")
isPodPresent = true;
}
else if (statusArray[0] == PortStatus)
{
}
else if (statusArray[0] == GripperStatus)
{
}
else if (statusArray[0] == Ready)
{
if (statusArray[1].ToUpper() == "TRUE")
isReady = true;
}
else if (statusArray[0] == Home)
{
if (statusArray[1].ToUpper() == "TRUE")
isHomed = true;
}
else if (statusArray[0] == Elevator)
{
}
else if (statusArray[0] == ArmRetract)
{
if (statusArray[1].ToUpper() == "TRUE")
isArmRetract = true;
}
}
Device.SetStatus(isReady, isHomed, isPodPresent, isArmRetract);
if (base.HandleMessage(msg, out handled))
{
Device.NoteStatus(result.MessagePart[0], result.Data);
}
return true;
}
}
}
@@ -0,0 +1,435 @@
using Aitex.Core.Common;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.SubstrateTrackings;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.SMIFs.Fortrend
{
public class FortrendSMIF : SMIFBase
{
private PeriodicJob _monitorJob;
public FortrendSMIF(string module, XmlElement node, string ioModule = "")
{
var attrModule = node.GetAttribute("module");
Module = string.IsNullOrEmpty(attrModule) ? module : attrModule;
Name = node.GetAttribute("id");
Display = node.GetAttribute("display");
DeviceID = node.GetAttribute("schematicId");
_diReady = ParseDiNode("diReady", node, ioModule);
_diPodInPlace = ParseDiNode("diPodInPlace", node, ioModule);
//暂时无用处
//_diAlarm = ParseDiNode("diAlarm", node, ioModule);
//_diReadyToUnload = ParseDiNode("diReadyToUnload", node, ioModule);
DoUnloadEnable = ParseDoNode("doUnloadEnable", node, ioModule);
DoStartRun = ParseDoNode("doStartRun", node, ioModule);
DoPortLock = ParseDoNode("doPodLock", node, ioModule);
DoLoadEnable = ParseDoNode("doLoadEnable", node, ioModule);
DoHomeEnable = ParseDoNode("doHomeEnable", node, ioModule);
if (SC.GetStringValue("System.InchType") == "Inch6")
{
_diCassetteExist = ParseDiNode("diCassette6", node, ioModule);
}
else
{
_diCassetteExist = ParseDiNode("diCassette8", node, ioModule);
}
DataSubscribe();
OpSubscribe();
}
public override bool Initialize()
{
base.Initialize();
if (IsInstalled)
{
_monitorJob = new PeriodicJob(1000, OnMonitor, $"{Module}Monitior", true);
}
return true;
}
private void DataSubscribe()
{
DATA.Subscribe($"{Module}.Mode", () => Mode);
DATA.Subscribe($"{Module}.IsSMIFReady", () => IsSMIFReady);
DATA.Subscribe($"{Module}.IsSMIFAlarm", () => IsSMIFAlarm);
DATA.Subscribe($"{Module}.IsHomed", () => IsHomed);
DATA.Subscribe($"{Module}.IsPodPresent", () => IsPodPresent);
DATA.Subscribe($"{Module}.PortStatus", () => PortStatus);
}
private void OpSubscribe()
{
OP.Subscribe($"{Module}.SwitchMode", InvokeSwitchMode);
}
public override void OnReceived(string receiveMsg)
{
//从服务器收到信息
string msg = receiveMsg.Replace(Delimiter, "");
if (!msg.StartsWith("FSD"))
EV.PostInfoLog(Module, $"Receive {msg}");
if (msg.StartsWith("HCA"))
{
string result = msg.Replace("HCA ", "");
switch (result)
{
case "OK":
{
}
break;
case "DENIED":
{
EV.PostAlarmLog(Module, "Command rejected not recognized or invalid parameter.");
}
break;
case "BUSY":
{
EV.PostAlarmLog(Module, "Command rejected, PLUS is busy.");
}
break;
case "CANNOT_PERFORM":
{
EV.PostAlarmLog(Module, "Command rejected, PLUS not in the proper state to perform the The Host command. PLUS is busy, PLUS in alarm status or prepositioning requirements not met.");
}
break;
case "NO_POD":
{
EV.PostAlarmLog(Module, "Command rejected, no pod has been placed on PLUS port plate.");
}
break;
case "NOT_READY":
{
EV.PostAlarmLog(Module, "Command rejected, all host ready conditions or interlocks have not been satisfied.");
}
break;
}
IsDone = true;
}
else if (msg.StartsWith("AERS"))
{
//事件
string eventMsg = msg.Replace("AERS ", "");
if (eventMsg == "REACH_HOME")
{
IsHomeDone = true;
}
else if (eventMsg == "CMPL_LOAD")
{
IsLoadDone = true;
}
else if (eventMsg == "CMPL_UNLOAD")
{
IsUnloadDone = true;
}
else if (eventMsg == "CMPL_LOCK")
{
IsLockDone = true;
}
else if (eventMsg == "CMPL_UNLOCK")
{
IsUnLockDone = true;
}
else if (eventMsg == "AUTO_MODE")
{
Mode = "AUTO";
IsSwitchDone = true;
}
else if (eventMsg == "MANUAL_MODE")
{
Mode = "MANUAL";
IsSwitchDone = true;
}
else if (eventMsg.Contains("WAFER_MAPPING_EVT"))
{
//Mapping结果事件
string mapping = eventMsg.Replace("WAFER_MAPPING_EVT ", "");
ModuleName cassModuleName = Module == "SMIFA" ? ModuleName.CassAL : ModuleName.CassAR;
for (int i = 0; i < mapping.Length; i++)
{
if (int.TryParse(mapping[i].ToString(), out int result))
{
//先将对应Wafer删除
WaferManager.Instance.DeleteWafer(cassModuleName, i);
//0-Full Status(未知状态) 1-Wafer Present 2-Empty 4-Cross Slotted
switch (result)
{
case 0:
{
WaferManager.Instance.CreateWafer(cassModuleName, i, WaferStatus.Unknown);
}
break;
case 1:
{
WaferManager.Instance.CreateWafer(cassModuleName, i, WaferStatus.Normal);
}
break;
case 2:
{
WaferManager.Instance.DeleteWafer(cassModuleName, i);
}
break;
case 4:
{
WaferManager.Instance.CreateWafer(cassModuleName, i, WaferStatus.Crossed);
}
break;
}
}
}
}
}
else if (msg.StartsWith("ARS"))
{
//报警 ARS XXYY ZZZZZZ(CR)(LF)
string alarm = msg.Replace("ARS ", "");
int index = alarm.IndexOf(' ');
string alarmCode = alarm.Substring(0, index);
string alarmText = alarm.Substring(index + 1);
EV.PostAlarmLog(Module, $"{Module} Alarm,Alarm Code is {alarmCode},Alarm Text: {alarmText}");
}
//状态查询结果
else if (msg.StartsWith("FSD"))
{
IsDone = true;
string query = msg.Replace("FSD", "");
if (int.TryParse(query.Substring(0, 1), out int formCode))
{
if (formCode == 0)
{
//general status
List<string> resultList = msg.Replace("FSD0 ", "").Split(' ').ToList();
foreach (string item in resultList)
{
if (item.StartsWith("MODE"))
{
Mode = item.Replace("MODE=", "");
}
//else if (item.StartsWith("READY"))
//{
// if (bool.TryParse(item.Replace("READY=", ""), out bool ready))
// {
// IsSMIFReady = ready;
// }
//}
else if (item.StartsWith("HOME"))
{
if (bool.TryParse(item.Replace("HOME=", ""), out bool home))
{
IsHomed = home;
}
}
//else if (item.StartsWith("PIP"))
//{
// if (bool.TryParse(item.Replace("PIP=", ""), out bool isPodPresent))
// {
// IsPodPresent = isPodPresent;
// }
//}
else if (item.StartsWith("PRTST"))
{
PortStatus = item.Replace("PRTST=", "");
}
}
}
else if (formCode == 1)
{
//software part number
}
else if (formCode == 2)
{
//Cassette map status
}
}
}
}
public override void Reset()
{
if (!IsSMIFReady)
{
ClearCmdQueue();
IsDone = true;
SMIFReset();
}
base.Reset();
}
public void SMIFReset()
{
RemoteCommand("RESET");
}
public void Home()
{
//if (!DoHomeEnable.SetValue(true, out string reason))
//{
// EV.PostWarningLog(Module, reason);
// return;
//}
IsHomeDone = false;
RemoteCommand("HOME");
}
private bool InvokeSwitchMode(string arg1, object[] arg2)
{
SwitchMode(arg2[0].ToString());
return true;
}
public void SwitchMode(string mode)
{
IsSwitchDone = false;
RemoteCommand(mode);
}
public void PortLock()
{
IsLockDone = false;
//RemoteCommand("LOCK");
if (!DoPortLock.SetValue(true, out string reason))
{
EV.PostWarningLog(Module, reason);
return;
}
}
public void PortUnLock()
{
IsUnLockDone = false;
//RemoteCommand("UNLOCK");
if (!DoPortLock.SetValue(false, out string reason))
{
EV.PostWarningLog(Module, reason);
return;
}
}
public void Load()
{
if (!IsHomed)
{
EV.PostAlarmLog(Module, "SMIF has not home!");
return;
}
if (_diCassetteExist.Value)
{
EV.PostAlarmLog(Module, "Cassette Exist,can not Load!");
return;
}
IsLoadDone = false;
//RemoteCommand("LOAD");
if (!DoStartRun.SetValue(true, out string reason))
{
EV.PostWarningLog(Module, reason);
return;
}
}
public void Unload()
{
if (!IsHomed)
{
EV.PostAlarmLog(Module, "SMIF has not home!");
return;
}
if (!_diCassetteExist.Value)
{
EV.PostAlarmLog(Module, "Cassette not Exist,can not Unload!");
return;
}
IsUnloadDone = false;
//RemoteCommand("UNLOAD");
if (!DoStartRun.SetValue(true, out string reason))
{
EV.PostWarningLog(Module, reason);
}
}
public void CloseDoStart()
{
if (!DoStartRun.SetValue(false, out string reason))
{
EV.PostWarningLog(Module, reason);
return;
}
}
public void QueryState(int code)
{
AddActionToQueue($"FSR FC={code}\r\n");
}
private bool OnMonitor()
{
if (IsConnected && IsDone)
QueryState(0);
return true;
}
public void Abort()
{
ClearCmdQueue();
IsDone = true;
}
//远程命令
public void RemoteCommand(string command,string param = "")
{
if (IsConnected)
{
string msg = $"HCS {command}";
if (!string.IsNullOrEmpty(param))
{
msg += $" {param}";
}
msg += "\r\n";
AddActionToQueue(msg);
}
}
}
}
@@ -0,0 +1,217 @@
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.IOCore;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using System;
using System.Collections.Concurrent;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.SMIFs.Fortrend
{
public abstract class SMIFBase : BaseDevice, IDevice
{
protected bool IsInstalled;
private string _scRoot;
private bool _enableLog;
//完成标志
public bool IsDone = true;
public bool IsHomeDone;
public bool IsLoadDone;
public bool IsUnloadDone;
public bool IsLockDone;
public bool IsUnLockDone;
public bool IsSwitchDone;
public bool IsCassetteExist => _diCassetteExist != null ? _diCassetteExist.Value : false;
public string Mode;
public string PortStatus;
public bool IsPodPresent => _diPodInPlace != null ? _diPodInPlace.Value : false;
public bool IsSMIFReady => _diReady != null ? _diReady.Value : false;
public bool IsSMIFAlarm => _diAlarm != null ? _diAlarm.Value : true;
public bool IsHomed;
//当前错误码
public int CurErrorCode;
protected DIAccessor _diReady = null;
protected DIAccessor _diAlarm = null;
protected DIAccessor _diPodInPlace = null;
protected DIAccessor _diReadyToUnload = null;
protected DIAccessor _diCassetteExist = null;
public DOAccessor DoUnloadEnable = null;
public DOAccessor DoStartRun = null;
public DOAccessor DoPortLock = null;
public DOAccessor DoLoadEnable = null;
public DOAccessor DoHomeEnable = null;
private SerialPortEx _serialPort;
public bool IsConnected => _serialPort != null ? _serialPort.IsOpen : false;
private R_TRIG _trigger = new R_TRIG();
public string Delimiter => _serialPort?.Delimiter;
private readonly object _locker = new object();
private ConcurrentQueue<string> _actionQueue = new ConcurrentQueue<string>();
public SMIFBase()
{
}
public SMIFBase(string module, string name)
{
Module = module;
Name = name;
}
public virtual bool Initialize()
{
IsInstalled = SC.GetValue<bool>($"System.SetUp.Is{Module}Installed");
if(IsInstalled )
{
InitSerialPort();
}
return true;
}
private void InitSerialPort()
{
try
{
string portName = string.Empty;
if (string.IsNullOrEmpty(_scRoot))
{
portName = SC.GetStringValue($"{Name}.PortName");
_enableLog = SC.GetValue<bool>($"{Name}.EnableLogMessage");
}
else
{
portName = SC.GetStringValue($"{_scRoot}.{Module}.{Name}.PortName");
_enableLog = SC.GetValue<bool>($"{_scRoot}.{Module}.{Name}.EnableLogMessage");
}
_serialPort = new SerialPortEx(portName);
_serialPort.Delimiter = "\r\n";
_serialPort.OnReceivedEvent += OnReceived;
_serialPort.Connect();
}
catch (Exception ex)
{
EV.PostAlarmLog(Module, $"{Module} connect IP:{_serialPort.PortName} failed");
LOG.Error(ex.Message, ex);
}
}
public virtual void OnReceived(string msg)
{
}
protected void AddActionToQueue(string msg)
{
if (IsConnected)
_actionQueue.Enqueue(msg);
}
protected void ClearCmdQueue()
{
lock (_locker)
{
//ConcurrentQueue<T>是线程安全的,所以它不会暴露或提供Clear方法清空
while (_actionQueue.TryDequeue(out _))
{
}
}
}
protected override void HandleMonitor()
{
if(!IsInstalled)
{
return;
}
//断连后将指令队列清空
_trigger.CLK = !_serialPort.IsOpen;
if (_trigger.Q)
{
ClearCmdQueue();
EV.PostAlarmLog(Module, $"{_serialPort.PortName} Disconnected!");
}
lock (_locker)
{
//连接成功 && SMIF不是Alarm && SMIF 空闲状态
if (_serialPort != null && _serialPort.IsOpen /*&& IsSMIFReady*/ && IsDone)
{
if (_actionQueue.Count > 0 && _actionQueue.TryDequeue(out string msg))
{
IsDone = false;
SendMessage(msg);
}
}
}
}
private void SendMessage(string msg)
{
try
{
if (IsConnected)
{
_serialPort.Send(msg);
if (!msg.StartsWith("FSR"))
EV.PostInfoLog(Module, $"向{Name}发送指令:{msg.Replace("\r", "").Replace("\n", "")}");
}
}
catch (Exception ex)
{
LOG.Error(ex.Message);
}
}
public virtual void Reset()
{
_serialPort?.Reset();
}
public virtual void Terminate()
{
_serialPort?.Close();
}
}
}
@@ -0,0 +1,303 @@
using Aitex.Core.RT.Log;
using Aitex.Core.Util;
using System;
using System.IO.Ports;
using System.Text;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.SMIFs.Fortrend
{
public class SerialPortEx
{
#region 变量属性
private bool _retryConnect = true;
private SerialPort _serialPort = new SerialPort();
public event Action<string> OnReceivedEvent;
//串口号
private string _portName = "COM1";
//波特率
private int _baudRate = 9600;
//校验位
private Parity _parity = Parity.None;
//停止位
private StopBits _stopBits = StopBits.One;
//数据位
private int _dataBits = 8;
//分隔符
public string Delimiter = "\r\n";
private StringBuilder _buffer = new StringBuilder();
private PeriodicJob _monitorThread;
/// <summary>
/// 串口号
/// </summary>
public string PortName
{
get { return _portName; }
set { _portName = value; }
}
/// <summary>
/// 波特率
/// </summary>
public int BaudRate
{
get { return _baudRate; }
set { _baudRate = value; }
}
/// <summary>
/// 奇偶校验位
/// </summary>
public Parity Parity
{
get { return _parity; }
set { _parity = value; }
}
/// <summary>
/// 数据位
/// </summary>
public int DataBits
{
get { return _dataBits; }
set { _dataBits = value; }
}
/// <summary>
/// 停止位
/// </summary>
public StopBits StopBits
{
get { return _stopBits; }
set { _stopBits = value; }
}
#endregion
#region 串口关闭/打开
/// <summary>
/// 端口是否已经打开
/// </summary>
public bool IsOpen => _serialPort != null ? _serialPort.IsOpen : false;
#region 构造函数
/// <summary>
/// 无参构造函数
/// </summary>
public SerialPortEx()
{
BoundEvents();
}
public SerialPortEx(string portName)
{
this._portName = portName;
BoundEvents();
}
/// <summary>
/// 参数构造函数(使用枚举参数构造)
/// </summary>
/// /// <param name="portName">串口号</param>
/// <param name="baudRate">波特率</param>
/// <param name="parity">奇偶校验位</param>
/// <param name="stopBits">停止位</param>
/// <param name="dataBits">数据位</param>
public SerialPortEx(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
this._portName = portName;
this._baudRate = baudRate;
this._parity = parity;
this._dataBits = dataBits;
this._stopBits = stopBits;
BoundEvents();
}
/// <summary>
/// 参数构造函数(使用字符串参数构造)
/// </summary>
/// /// <param name="portName">串口号</param>
/// <param name="baudRate">波特率</param>
/// <param name="parity">奇偶校验位</param>
/// <param name="stopBits">停止位</param>
/// <param name="dataBits">数据位</param>
public SerialPortEx(string portName, int baudRate, string parity, int dataBits, string stopBits)
{
this._portName = portName;
this._baudRate = baudRate;
this._dataBits = dataBits;
this._parity = (Parity)Enum.Parse(typeof(Parity), parity);
this._stopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBits);
BoundEvents();
}
private void BoundEvents()
{
_serialPort.DataReceived += new SerialDataReceivedEventHandler(OnDataReceived);
_serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(OnErrorReceived);
_monitorThread = new PeriodicJob(3000, OnMonitor,$"{_serialPort.PortName}", true);
}
#endregion
public void Reset()
{
_retryConnect = true;
}
private bool OnMonitor()
{
try
{
if (_serialPort != null && !_serialPort.IsOpen)
{
if (_retryConnect)
{
_retryConnect = false;
_serialPort.Open();
if (_serialPort.IsOpen)
{
LOG.Info($"Retry Connect PortName : {_serialPort?.PortName} success");
}
}
}
}
catch (Exception)
{
}
return true;
}
#region 事件处理函数
/// <summary>
/// 数据接收处理
/// </summary>
private void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
{
// 读取所有可用数据
string data = _serialPort.ReadExisting();
_buffer.Append(data);
string bufferContent = _buffer.ToString();
int delimiterIndex;
// 循环处理所有完整的消息
while ((delimiterIndex = bufferContent.IndexOf(Delimiter)) != -1)
{
string msg = bufferContent.Substring(0, delimiterIndex + Delimiter.Length);
// 移除处理过的数据和分隔符
_buffer.Remove(0, delimiterIndex + Delimiter.Length);
// 更新缓冲区内容
bufferContent = _buffer.ToString();
// 处理消息(注意跨线程调用)
OnReceivedEvent?.Invoke(msg);
}
}
/// <summary>
/// 错误处理函数
/// </summary>
public virtual void OnErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
LOG.Error($"{_serialPort.PortName}" + e.ToString());
}
#endregion
/// <summary>
/// 打开端口
/// </summary>
/// <returns></returns>
public void Connect()
{
try
{
if (_serialPort.IsOpen)
{
_serialPort.Close();
}
_serialPort.PortName = _portName;
_serialPort.BaudRate = _baudRate;
_serialPort.Parity = _parity;
_serialPort.DataBits = _dataBits;
_serialPort.StopBits = _stopBits;
_serialPort.ReadBufferSize = 4096;
_serialPort.WriteBufferSize = 4096;
_serialPort.Open();
}
catch (Exception ex)
{
LOG.Error(ex.Message, ex);
}
}
/// <summary>
/// 关闭端口
/// </summary>
public void Close()
{
try
{
if (_serialPort.IsOpen)
{
_serialPort.Close();
}
}
catch (Exception ex)
{
LOG.Error(ex.Message, ex);
}
}
/// <summary>
/// 丢弃来自串行驱动程序的接收和发送缓冲区的数据
/// </summary>
public void DiscardBuffer()
{
_serialPort.DiscardInBuffer();
_serialPort.DiscardOutBuffer();
}
#endregion
#region 写入数据
public bool Send(string sendMsg)
{
try
{
if (_serialPort.IsOpen)
{
byte[] sendBytes = Encoding.UTF8.GetBytes(sendMsg);
_serialPort.Write(sendBytes, 0, sendBytes.Length);
return true;
}
else
{
LOG.Error($"{_serialPort.PortName} is not open");
return false;
}
}
catch (Exception ex)
{
LOG.Error(ex.Message,ex);
return false;
}
}
#endregion
}
}