首次上传

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,62 @@
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.HST
{
public class HstMessage : AsciiMessage
{
public string Data { get; set; }
}
public class HstConnection:HstConnectionBase
{
public HstConnection(string addr) : base(addr)
{
}
public void EnableLog(bool enable)
{
}
protected override void OnDataReceived(string oneLineMessage)
{
MessageBase msg = ParseResponse(oneLineMessage);
if (msg.IsFormatError)
{
SetCommunicationError(true, "received invalid response message.");
}
lock (_lockerActiveHandler)
{
if (_activeHandler != null)
{
if (msg.IsFormatError || (_activeHandler.HandleMessage(msg, out bool completed) && completed))
{
_activeHandler = null;
}
}
}
}
protected override MessageBase ParseResponse(string rawText)
{
HstMessage msg = new HstMessage();
msg.IsResponse = false;
msg.IsAck = false;
msg.IsComplete = false;
string tempdata = rawText.Replace("\r", "").Replace("\n", "");
msg.RawMessage = rawText;
if(tempdata.Contains("Welcome")) msg.IsAck = true;
if (tempdata == "1") msg.IsAck = true;
else if (tempdata.Length == 1) msg.IsNak = true;
else
{
msg.IsResponse = true;
msg.Data = rawText;
}
return msg;
}
}
}
@@ -0,0 +1,224 @@
using System.Text;
using System.Threading;
using Aitex.Core.RT.Log;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Robot;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.HST
{
public abstract class HstConnectionBase : IConnection
{
public string Address
{
get { return _address; }
}
public bool IsConnected
{
get { return _socket == null ? false : _socket.IsConnected; }
}
public bool Connect()
{
if (_socket == null)
return true;
if (_socket.IsConnecting)
return true;
Disconnect();
if (!string.IsNullOrEmpty(_address))
{
_socket = new AsyncSocket(_address, "\r\n");
_socket.OnDataChanged += new AsyncSocket.MessageHandler(OnDataReceived);
_socket.OnErrorHappened += new AsyncSocket.ErrorHandler(OnErrorHappened);
}
_socket.Connect(_address);
return true;
}
public bool Disconnect()
{
if (_socket != null)
{
_socket.Dispose();
_socket = null;
}
return true;
}
public bool IsBusy
{
get { return _activeHandler != null; }
}
public bool IsCommunicationError { get; private set; }
public string LastCommunicationError { get; private set; }
protected AsyncSocket _socket;
protected HandlerBase _activeHandler; //set, control,
protected object _lockerActiveHandler = new object();
private string _address;//ip:port
private RD_TRIG _trigCommunicationError = new RD_TRIG();
public bool EnableRetry { get; set; }
public R_TRIG _trigRetryConnect = new R_TRIG();
public int MaxRetryCount { get; set; }
public HstConnectionBase(string addr)
{
_address = addr;
if (!string.IsNullOrEmpty(addr))
{
_socket = new AsyncSocket(addr, "\r\n");
_socket.OnDataChanged += new AsyncSocket.MessageHandler(OnDataReceived);
_socket.OnErrorHappened += new AsyncSocket.ErrorHandler(OnErrorHappened);
_socket.EnableLog = true;
}
}
private void OnErrorHappened(ErrorEventArgs args)
{
}
public void Execute(HandlerBase handler)
{
if (_activeHandler != null)
return;
if (handler == null)
return;
if (IsConnected)
{
lock (_lockerActiveHandler)
{
_activeHandler = handler;
_activeHandler.SetState(EnumHandlerState.Sent);
}
if (!_socket.Write(Encoding.ASCII.GetString(handler.SendBinary)+"\r\n"))
{
lock (_lockerActiveHandler)
{
_activeHandler = null;
}
IsCommunicationError = true;
}
}
}
protected abstract MessageBase ParseResponse(string rawMessage);
protected virtual void OnEventArrived(MessageBase msg)
{
}
protected abstract void OnDataReceived(string oneLineMessage);
public HandlerBase MonitorTimeout()
{
HandlerBase result = null;
lock (_lockerActiveHandler)
{
if (_activeHandler != null && _activeHandler.CheckTimeout())
{
result = _activeHandler;
_activeHandler = null;
SetCommunicationError(true, "receive response timeout");
}
}
return result;
}
/// <summary>
///
/// </summary>
/// <param name="retryConnectMaxCount">-1 keep retry, 0 no retry</param>
public void MonitorConnection(int retryMaxCount, out bool retried)
{
retried = false;
_trigRetryConnect.CLK = IsCommunicationError || !IsConnected;
if (_trigRetryConnect.Q)
{
int retry = 0;
while (retry < retryMaxCount || retryMaxCount < 0)
{
LOG.Write($"Retry connect with {_address} for the {retry + 1} time.");
Connect();
Thread.Sleep(retry * 1000);
retried = true;
lock (_lockerActiveHandler)
{
_activeHandler = null;
}
if (IsConnected)
break;
retry++;
//break;
}
}
SetCommunicationError(false, "retried");
}
/// <summary>
/// receive invalid packet
/// send out timeout
/// receive response timeout
/// </summary>
/// <param name="isError"></param>
/// <param name="reason"></param>
public void SetCommunicationError(bool isError, string reason)
{
IsCommunicationError = isError;
LastCommunicationError = reason;
_trigCommunicationError.CLK = isError;
if (_trigCommunicationError.R)
{
LOG.Write($"{Address} communication error, {reason}");
}
if (_trigCommunicationError.T)
{
LOG.Write($"{Address} communication error recovered, {reason}");
}
}
public void Reset()
{
_trigRetryConnect.RST = true;
}
public void SetEnableLog(bool value)
{
_socket.EnableLog = value;
}
}
}
@@ -0,0 +1,128 @@
using Aitex.Core.RT.Log;
using MECF.Framework.Common.Communications;
using MECF.Framework.Common.Equipment;
using System.Collections.Generic;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.HST
{
public abstract class HstHandler : HandlerBase
{
protected ModuleName _target;
protected int _slot;
public HstOcrReader OCRDevice { get; set; }
public string Command;
protected HstHandler(HstOcrReader device,string command,string para): base(BuildMessage(command,para))
{
OCRDevice = device;
Command = command;
//_isSimulator = SC.GetValue<bool>("System.IsSimulatorMode");
}
public static byte[] BuildMessage(string command, string para)
{
List<byte> ret = new List<byte>();
foreach (char c in command)
{
ret.Add((byte)c);
}
//cmd.Add((byte)(':')); //3A
if (!string.IsNullOrEmpty(para))
foreach (char c in para)
{
ret.Add((byte)c);
}
return ret.ToArray();
}
public virtual void Update()
{
}
}
public class OnlineHandler: HstHandler
{
public OnlineHandler(HstOcrReader reader,bool online):base(reader,"SO",online?"1":"0")
{
OCRDevice = reader;
Command = "SO";
}
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
HstMessage response = msg as HstMessage;
ResponseMessage = msg;
if(response.IsAck) SetState(EnumHandlerState.Acked);
if(response.IsNak) SetState(EnumHandlerState.Completed);
transactionComplete = true;
return true;
}
}
public class LoadJobHandler : HstHandler
{
public LoadJobHandler(HstOcrReader reader, string jobfile) : base(reader, "LF", jobfile)
{
OCRDevice = reader;
Command = string.Format("LF{0}.job", jobfile);
}
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
HstMessage response = msg as HstMessage;
ResponseMessage = msg;
if (response.IsAck) SetState(EnumHandlerState.Acked);
if (response.IsNak) SetState(EnumHandlerState.Completed);
transactionComplete = true;
return true;
}
}
public class ReadLMHandler : HstHandler
{
public ReadLMHandler(HstOcrReader reader) : base(reader, "SM\"READ\"0 ", null)
{
OCRDevice = reader;
Command = "SM\"READ\"0 ";
}
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
HstMessage response = msg as HstMessage;
ResponseMessage = msg;
if (response.IsAck)
{
SetState(EnumHandlerState.Acked);
transactionComplete = false;
return true;
}
if (response.IsNak) SetState(EnumHandlerState.Completed);
if (response.IsResponse)
{
SetState(EnumHandlerState.Completed);
string[] items = response.Data.TrimStart('[').TrimEnd(']').Split(',');
if (OCRDevice.ReadLaserMaker)
{
OCRDevice.LaserMaker = items[0];
OCRDevice.LaserMark1 = items[0];
if (items.Length > 1) OCRDevice.LaserMark1Score = items[1];
if (items.Length > 2) OCRDevice.LaserMark1ReadTime = items[2];
LOG.Write($"{OCRDevice.Name} laser mark1 updated to {OCRDevice.LaserMaker}");
}
else
{
OCRDevice.T7Code = items[0];
OCRDevice.LaserMark2 = items[0];
if (items.Length > 1) OCRDevice.LaserMark2Score = items[1];
if (items.Length > 2) OCRDevice.LaserMark2ReadTime = items[2];
LOG.Write($"{OCRDevice.Name} laser mark2 updated to {OCRDevice.T7Code}");
}
OCRDevice.ReadOK = double.Parse(items[1]) >= 0;
}
transactionComplete = true;
return true;
}
}
}
@@ -0,0 +1,320 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using Aitex.Sorter.Common;
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.HST
{
public class HstOcrReader : BaseDevice, IDevice
{
#region properties
public DeviceState State
{
get
{
if (!Initalized)
{
return DeviceState.Unknown;
}
if (Error)
{
return DeviceState.Error;
}
if (Busy)
return DeviceState.Busy;
return DeviceState.Idle;
}
}
public bool Initalized { get; set; }
public Guid OCRGuid { get; set; }
public bool Busy
{
get { return _lstHandler.Count > 0 || _connection.IsBusy; }
}
public bool Error
{
get
{
return _commErr || ExeError|| _connection.IsCommunicationError||!_connection.IsConnected;
}
}
public bool ExeError { get; set; } = false;
public bool ReadLaserMaker { get; set; }
public string JobName { get; set; }
public string LaserMaker { get; set; }
public string T7Code { get; set; }
public string LaserMark1 { get; set; }
public string LaserMark1Score { get; set; }
public string LaserMark1ReadTime { get; set; }
public string LaserMark2 { get; set; }
public string LaserMark2Score { get; set; }
public string LaserMark2ReadTime { get; set; }
public bool ReadOK { get; set; }
public string ImageFileName { get; set; }
public string ImageStorePath { get; set; }
#endregion
#region fields
private HstConnection _connection;
private string _address;
private PeriodicJob _thread;
private LinkedList<HandlerBase> _lstHandler = new LinkedList<HandlerBase>();
private object _lockerHandlerList = new object();
private R_TRIG _trigError = new R_TRIG();
private R_TRIG _trigWarningMessage = new R_TRIG();
private bool _enableLog;
#endregion
public const string delimiter = "\r\n";
private bool _commErr = false;
public HstOcrReader(string module, string name, string display, string deviceId, string address)
: base(module, name, display, deviceId)
{
_address = address;
Initalized = false;
}
public bool Initialize()
{
_address = SC.GetStringValue($"{Module}.{Name}.Address");
_enableLog = SC.GetValue<bool>($"{Module}.{Name}.EnableLogMessage");
_lstHandler.Clear();
_connection = new HstConnection(_address);
if (CheckAddressPort(_address))
{
if (_connection.Connect())
{
EV.PostInfoLog(Module, $"{Module}.{Name} connected");
}
}
else EV.PostWarningLog(Module, $"{Module}.{Name} Adress is illegal");
_thread = new PeriodicJob(50, OnTimer, $"{Module} MonitorHandler", true);
DEVICE.Register(String.Format("{0}.{1}", Name, "ReadWaferID"), (out string reason, int time, object[] param) =>
{
bool bLaser = bool.Parse((string)param[0]);
string jobName = (string)param[1];
bool ret = Read(bLaser, jobName, out reason);
if (ret)
{
reason = string.Format("{0}", Name, "读WaferID");
return true;
}
return false;
});
DATA.Subscribe(Name, "WRIDReaderState", () => State);
DATA.Subscribe(Name, "WRIDReaderBusy", () => Busy);
DATA.Subscribe(Name, "LaserMaker1", () => LaserMark1);
DATA.Subscribe(Name, "LaserMaker2", () => LaserMark2);
Initalized = true;
_lstHandler.AddLast(new OnlineHandler(this, true));
return true;
}
//int queryintervalcount = 0;
private bool OnTimer()
{
try
{
_connection.MonitorTimeout();
//if (!_connection.IsConnected || _connection.IsCommunicationError)
if (_connection.IsCommunicationError)
{
_lstHandler.Clear();
return true;
}
if (_connection.IsBusy)
return true;
HandlerBase handler = null;
lock (_lockerHandlerList)
{
if (_lstHandler.Count > 0)
{
handler = _lstHandler.First.Value;
if (handler != null) _connection.Execute(handler);
_lstHandler.RemoveFirst();
}
//else
//{
// if (queryintervalcount > 100)
// {
// _lstHandler.AddLast(new OnlineHandler(this, true));
// _lstHandler.AddLast(new OnlineHandler(this, false));
// queryintervalcount = 0;
// }
// else
// queryintervalcount++;
//}
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
return true;
}
static bool CheckAddressPort(string s)
{
bool isLegal;
Regex regex = new Regex(@"^((2[0-4]\d|25[0-5]|[1]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[1]?\d\d?)\:([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-6][0-5][0-5][0-3][0-5])$");//CheckAddressPort
Match match = regex.Match(s);
if (match.Success)
{
isLegal = true;
}
else
{
isLegal = false;
}
return isLegal;
}
public void Terminate()
{
}
public void Monitor()
{
//if (!_onlineInited && _socket.IsConnected)
//{
// _onlineInited = true;
// string error = string.Empty;
// Online(true, out error);
//}
}
public void Reset()
{
_trigError.RST = true;
_trigWarningMessage.RST = true;
_lstHandler.Clear();
if(_connection.IsCommunicationError ||!_connection.IsConnected)
{
_connection.Connect();
}
_connection.SetCommunicationError(false, "");
//_trigCommunicationError.RST = true;
_enableLog = SC.GetValue<bool>($"{Module}.{Name}.EnableLogMessage");
//_trigRetryConnect.RST = true;
ExeError = false;
}
#region Command
public bool Read(bool bLaserMaker, string jobName, out string reason)
{
lock(_lockerHandlerList)
{
_lstHandler.AddLast(new OnlineHandler(this, false));
_lstHandler.AddLast(new LoadJobHandler(this, ConvetJobName(jobName)));
_lstHandler.AddLast(new OnlineHandler(this, true));
_lstHandler.AddLast(new ReadLMHandler(this));
}
ReadOK = false;
ReadLaserMaker = bLaserMaker;
reason = "";
return true;
}
public bool ReadOnHostMode(bool bLaserMaker, string[] jobnames, out string reason)
{
lock (_lockerHandlerList)
{
_lstHandler.AddLast(new OnlineHandler(this, false));
_lstHandler.AddLast(new LoadJobHandler(this, ConvetJobName(jobnames[0])));
_lstHandler.AddLast(new OnlineHandler(this, true));
_lstHandler.AddLast(new ReadLMHandler(this));
}
ReadOK = false;
ReadLaserMaker = bLaserMaker;
reason = "";
return true;
}
#endregion
private string[] GetJobName(bool bLaserMark1)
{
string jobs = string.Empty;
if (bLaserMark1)
{
jobs = SC.GetStringValue("OcrReader.ReaderJob1Main");
}
else
{
jobs = SC.GetStringValue("OcrReader.ReaderJob2Main");
}
return jobs.Split(';');
}
public void OnLaskerMarkerRead()
{
}
private string ConvetJobName(string name)
{
name = name.Substring(name.LastIndexOf("\\") + 1); //remove dir
name = name.Substring(0, name.LastIndexOf(".")); //remove expand
return name;
}
}
}