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,283 @@
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using MECF.Framework.Common.Equipment;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.Cognex
{
public class CognexAsyncSocket : ICommunication, IDisposable
{
public delegate void ErrorHandler(ErrorEventArgs args);
public event ErrorHandler OnErrorHappened;
public delegate void MessageHandler(string message);
public event MessageHandler OnDataChanged;
private static Object _locker = new Object();
public class ClientStateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public static int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
public ClientStateObject(int bufferSize = 256)
{
BufferSize = bufferSize;
buffer = new byte[bufferSize];
}
}
public string NewLine { get; set; }
public bool NeedLog { get; set; } = true;
private Socket _socket;
private string _ip;
private int _port;
private string _address;
private int _bufferSize = 256;
public bool IsConnected { get { return (_socket != null && _socket.Connected); } } //&& !_socket.Poll(100, SelectMode.SelectRead)); } }
public bool IsHstConnected { get { return (_socket != null && IsSocketConnected(_socket)); } }
private bool IsSocketConnected(Socket client)
{
try
{
byte[] tmp = new byte[] { 0x0 };
//int a= newclient.Receive(tmp);
int a = client.Send(tmp);
if (a == 1)
return true;
else
return false;
}
catch (SocketException e)
{
LOG.Write(e.Message);
return false;
}
}
public CognexAsyncSocket(string address, string newline = "\r")
{
// Connect(address);
_socket = null;
NewLine = newline;
_address = address;
}
public CognexAsyncSocket(string address, int bufferSize, string newline = "\r")
{
_socket = null;
NewLine = newline;
_address = address;
_bufferSize = bufferSize;
}
~CognexAsyncSocket()
{
Dispose();
}
public void Connect(string address)
{
try
{
_ip = address.Split(':')[0];
_port = int.Parse(address.Split(':')[1]);
IPAddress ipAddress = IPAddress.Parse(_ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, _port);
lock (_locker)
{
//Dispose current socket and create a TCP/IP socket.
Dispose();
if (_socket == null)
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
_socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _socket);
}
}
catch (Exception e)
{
LOG.Write(e);
throw new Exception(e.ToString());
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
EV.PostMessage(ModuleName.Robot.ToString(), EventEnum.TCPConnSucess, _ip, _port.ToString());
// Receive the response from the remote device.
Receive(_socket);
}
catch (Exception e)
{
LOG.Write(e);
string reason = string.Format("Communication {0}:{1:D} {2}.", _ip, _port, e.Message);
LOG.Error(reason);
// EV.PostMessage(UnitName.Transfer.ToString(), EventEnum.RobotCommandFailed, reason);
//OnErrorHappened(new ErrorEventArgs(reason));
Thread.Sleep(1000);
Connect(_address);
}
}
private void Receive(Socket client)
{
try
{
// Create the state object.
ClientStateObject state = new ClientStateObject(_bufferSize);
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
LOG.Write(e);
string reason = string.Format("TCP connection error:{0}", e.Message);
LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
OnErrorHappened(new ErrorEventArgs(reason));
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
if (!IsConnected) { return; }
// Retrieve the state object and the client socket
// from the asynchronous state object.
ClientStateObject state = (ClientStateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
if (state.sb.Length > NewLine.Length)
{
if (state.sb.ToString().Substring(state.sb.Length - NewLine.Length).Equals(NewLine))
{
string msg = state.sb.ToString();
if (NeedLog)
LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, msg.TrimEnd('\n').TrimEnd('\r')));
OnDataChanged(state.sb.ToString());
state.sb.Clear();
}
}
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
}
catch (Exception ex)
{
LOG.Write(ex);
string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
OnErrorHappened(new ErrorEventArgs(reason));
}
}
public bool Write(string data)
{
try
{
lock (_locker)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
_socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
}
return true;
}
catch (Exception ex)
{
LOG.Write(ex);
LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, data));
string reason = string.Format("Send command failed:{0}", ex.Message);
OnErrorHappened(new ErrorEventArgs(reason));
}
return false;
}
private void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
}
catch (Exception ex)
{
LOG.Write(ex);
string reason = string.Format("Send command failed:{0}", ex.Message);
OnErrorHappened(new ErrorEventArgs(reason));
}
}
/// <summary>
/// 释放资源(Dispose)
/// </summary>
public void Dispose()
{
try
{
if (_socket != null)
{
if (IsConnected)
{
_socket.Shutdown(SocketShutdown.Both);
}
_socket.Close();
_socket.Dispose();
_socket = null;
}
}
catch (Exception ex)
{
LOG.Write(ex);
string reason = string.Format("释放socket资源失败:{0}", ex.Message);
OnErrorHappened(new ErrorEventArgs(reason));
}
}
}
}
@@ -0,0 +1,73 @@
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.Cognex
{
public class CognexOCRMessage : AsciiMessage
{
public string Data { get; set; }
}
public class CognexOCRConnection : TCPPortConnectionBase
{
private CognexWaferIDReader _reader;
public CognexOCRConnection(string addr,CognexWaferIDReader reader) : base(addr,"")
{
_reader = reader;
}
protected override MessageBase ParseResponse(string rawText)
{
if (rawText.Contains("User:") && _reader.DeviceState != OCRReaderStateEnum.Error)
{
SendMessage("admin\r\n");
}
if (rawText.Contains("Password:") && _reader.DeviceState != OCRReaderStateEnum.Error)
{
SendMessage("\r\n");
}
if (rawText.Contains("User Logged In") && _reader.DeviceState != OCRReaderStateEnum.Error)
{
_reader.IsLogined = true;
}
if (rawText.Contains("Invalid Password") && _reader.DeviceState != OCRReaderStateEnum.Error)
{
_reader.IsLogined = false;
_reader.OnError(rawText);
}
CognexOCRMessage msg = new CognexOCRMessage();
msg.IsResponse = false;
msg.IsAck = false;
msg.IsComplete = false;
string tempdata = rawText.Replace("\r", "").Replace("\n", "");
msg.RawMessage = rawText;
msg.Data = rawText;
if (tempdata.Contains("Welcome")) msg.IsAck = true;
if (tempdata == "1") msg.IsAck = true;
//else if (tempdata.Length == 1)
//{
// msg.IsNak = true;
// if(IsBusy)
// _reader.OnError("Received response:" + rawText);
//}
else
{
msg.IsNak = true;
msg.IsResponse = true;
msg.Data = rawText;
}
return msg;
}
}
}
@@ -0,0 +1,243 @@
using Aitex.Core.RT.Log;
using MECF.Framework.Common.Communications;
using MECF.Framework.Common.Equipment;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.Cognex
{
public abstract class CognexHandler : HandlerBase
{
protected ModuleName _target;
protected int _slot;
public CognexWaferIDReader OCRDevice { get; set; }
public string Command;
protected CognexHandler(CognexWaferIDReader device, string command, string para) : base(BuildMessage(command, para))
{
OCRDevice = device;
Command = command;
//_isSimulator = SC.GetValue<bool>("System.IsSimulatorMode");
}
public static string BuildMessage(string command, string para)
{
return command + (string.IsNullOrEmpty(para)?"":para ) + "\r\n";
}
public virtual void Update()
{
}
}
public class OnlineHandler : CognexHandler
{
public OnlineHandler(CognexWaferIDReader reader, bool online) : base(reader, "SO", online ? "1" : "0")
{
OCRDevice = reader;
Command = "SO";
}
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
CognexOCRMessage response = msg as CognexOCRMessage;
ResponseMessage = msg;
if (response.IsAck) SetState(EnumHandlerState.Acked);
if (response.IsNak) SetState(EnumHandlerState.Completed);
transactionComplete = true;
return true;
}
}
public class LoadJobHandler : CognexHandler
{
public LoadJobHandler(CognexWaferIDReader 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)
{
CognexOCRMessage response = msg as CognexOCRMessage;
ResponseMessage = msg;
if (response.IsAck) SetState(EnumHandlerState.Acked);
if (response.IsNak) SetState(EnumHandlerState.Completed);
transactionComplete = true;
return true;
}
}
public class ReadWaferIDHandler : CognexHandler
{
public ReadWaferIDHandler(CognexWaferIDReader reader) : base(reader, "SM\"READ\"0 ", null)
{
OCRDevice = reader;
Command = "SM\"READ\"0 ";
}
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
CognexOCRMessage response = msg as CognexOCRMessage;
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.Replace("\r","").Replace("\n","").TrimStart('[').TrimEnd(']').Replace("[","").Replace("]","").Split(',');
if (OCRDevice.IsReadLaserMark1)
{
OCRDevice.LaserMark1ReadResult = response.Data;
OCRDevice.LaserMark1 = items[0];
OCRDevice.CurrentLaserMark = 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.LaserMark1}");
}
else
{
OCRDevice.LaserMark2ReadResult = response.Data;
OCRDevice.LaserMark2 = items[0];
OCRDevice.CurrentLaserMark = 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.LaserMark2}");
}
OCRDevice.ReadOK = true;
}
transactionComplete = true;
return true;
}
}
public class GetJobListHandler: CognexHandler
{
public GetJobListHandler(CognexWaferIDReader reader) : base(reader, "Get Filelist", "")
{
OCRDevice = reader;
Command = "Get Filelist";
reader.JobFileList = new List<string>();
reader.JobFileList.Clear();
fileCount = -2;
tempCount = 0;
}
private int fileCount;
private int tempCount;
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
CognexOCRMessage response = msg as CognexOCRMessage;
ResponseMessage = msg;
if (response.IsAck) SetState(EnumHandlerState.Acked);
if (response.IsNak) SetState(EnumHandlerState.Completed);
if (response.IsResponse|| response.IsAck)
{
SetState(EnumHandlerState.Completed);
var data = Regex.Split(response.Data, "\r\n");
tempCount += data.Length;
if (fileCount == -1) //Second Message
{
fileCount = Convert.ToInt32(data[0].Trim());
}
if (fileCount == -2) // First Time get message
{
if (data[0] != "1")
{
OCRDevice.OnError($"Response Error:{response.Data}");
transactionComplete = true;
return true;
}
if (data.Length ==2 )
{
fileCount = -1;
}
else
{
fileCount = Convert.ToInt32(data[1].Trim());
}
}
var job = data.Where(i => i.Contains(".job")).ToList();
OCRDevice.JobFileList.AddRange(job);
transactionComplete = false;
if(tempCount >= fileCount+2 && fileCount>=0)
transactionComplete = true;
return true;
}
transactionComplete = false;
return true;
}
}
public class SavePictureHandler: CognexHandler
{
private int _imageLength;
private StringBuilder _stringBuilder;
private string _filename;
public SavePictureHandler(CognexWaferIDReader reader,string filename) : base(reader, "RI", "")
{
OCRDevice = reader;
Command = "RI";
_imageLength = 0;
_stringBuilder = new StringBuilder();
_filename= filename;
}
public override bool HandleMessage(MessageBase msg, out bool transactionComplete)
{
CognexOCRMessage response = msg as CognexOCRMessage;
if(response.IsAck)
{
var data = Regex.Split(response.Data, "\r\n");
if (data.Length == 2 && data[0].Trim() == "1" && int.TryParse(data[1], out _imageLength))
{
}
else
{
OCRDevice.OnError("Invalid data");
transactionComplete = true;
return true;
}
}
if(response.IsResponse)
{
foreach(string str in Regex.Split(response.Data, "\r\n"))
_stringBuilder?.Append(str.Trim());
if (_stringBuilder.Length >= _imageLength)
{
string strimage = _stringBuilder?.ToString().Substring(0, _imageLength);
OCRDevice.SaveImage(_filename,strimage);
transactionComplete = true;
return true;
}
}
transactionComplete = false;
return true;
}
}
}
@@ -0,0 +1,339 @@
using Aitex.Common.Util;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.Cognex
{
public class CognexWaferIDReader:OCRReaderBaseDevice, IConnection
{
private CognexOCRConnection _connection;
private static readonly object _lockerHandlerList = new object();
private string _scRoot;
private PeriodicJob _thread;
private LinkedList<HandlerBase> _lstHandler = new LinkedList<HandlerBase>();
private R_TRIG _trigError = new R_TRIG();
private R_TRIG _trigWarningMessage = new R_TRIG();
private R_TRIG _trigActionDone = new R_TRIG();
private bool _enableLog;
private string _imageStorePath;
private DateTime _dtActionStart;
public override string CurrentImageFileName
{
get
{
if (SC.ContainsItem($"OCRReader.{Name}.TempImageFilePath"))
{
return SC.GetStringValue($"OCRReader.{Name}.TempImageFilePath");
}
return "";
}
}
public bool IsLogined { get; set; }
public CognexWaferIDReader(string module,string name,string scRoot):base(module,name)
{
_scRoot = scRoot;
InitializeCognex();
CheckToPostMessage((int)OCRReaderMsg.StartInit, null);
}
public void InitializeCognex()
{
Address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
_enableLog = SC.GetValue<bool>($"{_scRoot}.{Name}.EnableLogMessage");
TimeLimitForRead = SC.GetValue<int>($"{_scRoot}.{Name}.TimeLimitForWID");
_lstHandler.Clear();
_connection = new CognexOCRConnection(Address,this);
if (CheckAddressPort(Address))
{
if (_connection.Connect())
{
EV.PostInfoLog(Module, $"{Module}.{Name} connected");
}
}
else EV.PostWarningLog(Module, $"{Module}.{Name} Adress is illegal");
ConnectionManager.Instance.Subscribe(Name, this);
_thread = new PeriodicJob(50, OnTimer, $"{Module}.{Name} MonitorHandler", true);
var fileInfo = new FileInfo(PathManager.GetDirectory($"Logs\\{Name}"));
if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
fileInfo.Directory.Create();
if (fileInfo.Directory != null)
_imageStorePath = fileInfo.FullName;
ConnectionManager.Instance.Subscribe($"{Name}", this);
}
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;
}
private bool OnTimer()
{
try
{
_connection.MonitorTimeout();
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();
}
}
_trigActionDone.CLK = (_lstHandler.Count == 0 && !_connection.IsBusy);
if (_trigActionDone.Q)
OnActionDone(null);
}
catch (Exception ex)
{
LOG.Write(ex);
}
return true;
}
public string Address { get; private set; }
public bool IsConnected => _connection.IsConnected ;
public bool Connect()
{
_connection.Connect();
return true;
}
public bool Disconnect()
{
_connection.Disconnect();
return true;
}
protected override bool fStartInit(object[] param)
{
return true;
}
protected override bool fStartReadWaferID(object[] param)
{
string job = param[0].ToString();
int lasermarkindex = (int)param[1];
IsReadLaserMark1 = lasermarkindex == 0;
lock (_lockerHandlerList)
{
_lstHandler.AddLast(new OnlineHandler(this,false));
_lstHandler.AddLast(new LoadJobHandler(this, job));
_lstHandler.AddLast(new OnlineHandler(this, true));
_lstHandler.AddLast(new ReadWaferIDHandler(this));
}
_dtActionStart = DateTime.Now;
return true;
}
protected override bool fMonitorReading(object[] param)
{
IsBusy = false;
if(DateTime.Now - _dtActionStart >TimeSpan.FromSeconds(TimeLimitForRead))
{
EV.Notify(AlarmWIDReadTimeout);
ReadOK = false;
if(IsReadLaserMark1)
{
LaserMark1 = "******";
LaserMark1Score = "0";
LaserMark1ReadTime = (DateTime.Now - _dtActionStart).TotalSeconds.ToString();
}
Reset();
return true;
}
return false;
}
protected override bool fStartReadParameter(object[] param)
{
readparameter = param[0].ToString();
switch (readparameter)
{
case "JobList":
if (SC.ContainsItem($"{ _scRoot}.{ Name}.DirectoryForJob") && !string.IsNullOrEmpty(SC.GetStringValue($"{ _scRoot}.{ Name}.DirectoryForJob")))
{
string jobpath = SC.GetStringValue($"{ _scRoot}.{ Name}.DirectoryForJob");
string[] files = Directory.GetFiles(jobpath);
JobFileList = new List<string>();
JobFileList.Clear();
foreach(string strfile in files)
{
FileInfo f = new FileInfo(strfile);
if(f.Extension == ".job")
{
JobFileList.Add(f.Name);
}
}
}
else
{
lock (_lockerHandlerList)
{
_lstHandler.AddLast(new GetJobListHandler(this));
}
}
break;
default:
break;
}
return true; ;
}
private string readparameter = "";
protected override bool fMonitorReadParameter(object[] param)
{
if (readparameter == "JobList" && SC.ContainsItem($"{ _scRoot}.{ Name}.DirectoryForJob") && !string.IsNullOrEmpty(SC.GetStringValue($"{ _scRoot}.{ Name}.DirectoryForJob")))
{
return true;
}
return base.fMonitorReadParameter(param);
}
protected override bool fStartReset(object[] param)
{
_trigError.RST = true;
_trigWarningMessage.RST = true;
_lstHandler.Clear();
_connection.ForceClear();
if (_connection.IsCommunicationError || !_connection.IsConnected)
{
Address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
_enableLog = SC.GetValue<bool>($"{_scRoot}.{Name}.EnableLogMessage");
_connection = new CognexOCRConnection(Address, this);
_connection.Connect();
}
_connection.SetCommunicationError(false, "");
//_trigCommunicationError.RST = true;
_enableLog = SC.GetValue<bool>($"{_scRoot}.{Name}.EnableLogMessage");
return true;
}
protected override bool fStartSetParameter(object[] param)
{
string paraname = param[0].ToString();
switch(paraname)
{
case "SetOnline":
break;
}
return true; ;
}
protected override bool fSetParameterComplete(object[] param)
{
return true;
}
public override string[] GetJobFileList()
{
lock(_lockerHandlerList)
{
_lstHandler.AddLast(new GetJobListHandler(this));
}
int delaytime = 0;
while((_lstHandler.Count !=0 || _connection.IsBusy)&& delaytime<10)
{
Thread.Sleep(500);
delaytime++;
}
return JobFileList.ToArray();
}
protected override bool fStartSavePicture(object[] param)
{
lock(_lockerHandlerList)
{
}
return true;
}
public void SaveImage(string filename,string imgString)
{
DeleteEarlyImageFile();
var byBitmap = HexStringToBytes(imgString);
var bmp = new Bitmap(new MemoryStream(byBitmap));
bmp.Save($"{_imageStorePath}{filename}.bmp", ImageFormat.Bmp);
EV.PostInfoLog("WIDReader", $"Picture saved, file name is {filename}.bmp");
}
private void DeleteEarlyImageFile()
{
string[] fpath = Directory.GetFiles(_imageStorePath, "*.bmp", SearchOption.TopDirectoryOnly);
Dictionary<string, DateTime> fCreateDate = new Dictionary<string, DateTime>();
for (int i = 0; i < fpath.Length; i++)
{
FileInfo fi = new FileInfo(fpath[i]);
fCreateDate[fpath[i]] = fi.CreationTime;
}
fCreateDate = fCreateDate.OrderBy(f => f.Value).ToDictionary(f => f.Key, f => f.Value);
int fCount = fCreateDate.Count;
while (fCount > 99)
{
string strFile = fCreateDate.First().Key;
File.Delete(strFile);
fCreateDate.Remove(strFile);
fCount = fCreateDate.Count;
}
}
private static byte[] HexStringToBytes(string hex)
{
byte[] data = new byte[hex.Length / 2];
int j = 0;
for (int i = 0; i < hex.Length; i += 2)
{
data[j] = Convert.ToByte(hex.Substring(i, 2), 16);
++j;
}
return data;
}
protected override void OnWaferIDRead(string wid, string score, string readtime)
{
if(DeviceState == OCRReaderStateEnum.ReadWaferID)
base.OnWaferIDRead(wid, score, readtime);
}
}
}
@@ -0,0 +1,504 @@
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders
{
public enum CongnexHandlerType
{
None,
LoginUsername,
LoginPassword,
ReadLM,
Online,
ReadImage,
GetJob,
GetJobList,
LoadJob,
}
public enum CongnexHandlerState
{
None,
CMDSend,
CMDSuccess,
CMDFail,
ExecuteComplete,
Error,
Timeout,
}
public class CongexHandler : IHandler
{
private static readonly int retry_time = 1;
private readonly IReaderMsg _imp;
private readonly object[] _objs;
private int retry_count = retry_time;
public CongexHandler(IReaderMsg imp, params object[] objs)
{
_imp = imp;
_objs = objs;
}
public int ID { get; set; }
public int Unit { get; set; }
public bool IsBackground => _imp.background;
public bool Execute<TPort>(ref TPort port) where TPort : ICommunication
{
retry_count = retry_time;
//return port.Write(string.Format("{0}\r", _imp.package(this._objs)));
return port.Write(string.Format("{0}\r\n", _imp.package(_objs)));
}
/// <summary>
/// return value: bhandle
/// </summary>
/// <typeparam name="TPort"></typeparam>
/// <param name="port"></param>
/// <param name="msg"></param>
/// <param name="completed"></param>
/// <returns></returns>
public bool OnMessage<TPort>(ref TPort port, string message, out bool completed) where TPort : ICommunication
{
completed = false;
try
{
var msg = message.Trim();
if (string.IsNullOrWhiteSpace(msg)) return true;
if(msg.Equals("-1"))
{
if (retry_count-- <= 0)
{
var warning = string.Format("retry over {0} times", retry_time);
LOG.Warning(warning);
if (!IsBackground)
{
throw new ExcuteFailedException(warning);
}
completed = true;
return true;
}
port.Write(string.Format("{0}\r\n", _imp.package(_objs)));
}
//msg = message.Trim().Trim("[]".ToCharArray());
var data = Regex.Split(msg, "\r\n");
completed = _imp.unpackage("", data);
return true;
}
catch (ExcuteFailedException e)
{
throw e;
}
catch (Exception ex)
{
LOG.Write(ex);
throw new InvalidPackageException(message);
}
}
}
public class CognexUserNameHandler : IReaderMsg //common move
{
private readonly CognexOcrReader _device;
public CognexUserNameHandler(CognexOcrReader device)
{
_device = device;
background = true;
}
public bool background { get; }
public string package(params object[] args)
{
_device.CurrentHandlerType = CongnexHandlerType.LoginUsername;
return "admin";
}
public void SetExeError()
{
_device.Error = true; ;
}
public bool unpackage(string type, string[] items)
{
if (items.Length != 1) return false;
if (items[0].Contains("Password"))
{
_device.CurrentHandlerState = CongnexHandlerState.ExecuteComplete;
return true;
}
else
{
_device.CurrentHandlerState = CongnexHandlerState.CMDFail;
return false;
}
}
}
public class CognexPasswordHandler : IReaderMsg //common move
{
private readonly CognexOcrReader _device;
public CognexPasswordHandler(CognexOcrReader device)
{
_device = device;
background = true;
}
public bool background { get; }
public string package(params object[] args)
{
_device.CurrentHandlerType = CongnexHandlerType.LoginPassword;
return "";
}
public void SetExeError()
{
_device.Error = true; ;
}
public bool unpackage(string type, string[] items)
{
if (items.Length != 1) return false;
if(items[0].Contains("User Logged In"))
{
_device.CurrentHandlerState = CongnexHandlerState.ExecuteComplete;
_device.IsLogined = true;
return true;
}
if(items[0].Contains("Invalid Password"))
{
_device.CurrentHandlerState = CongnexHandlerState.CMDFail;
_device.IsLogined = false;
return false;
}
return false;
}
}
public class CognexReadHandler : IReaderMsg //common move
{
private readonly CognexOcrReader _device;
public CognexReadHandler(CognexOcrReader device)
{
_device = device;
background = true;
}
public void SetExeError()
{
_device.Error = true; ;
}
public bool background { get; }
public string package(params object[] args)
{
_device.CurrentHandlerType = CongnexHandlerType.ReadLM;
return "SM\"READ\"0 ";
}
public bool unpackage(string type, string[] items)
{
string[] stritems;
if(items[0] == "1" && items.Length == 1)
{
_device.CurrentHandlerState = CongnexHandlerState.CMDSuccess;
return true;
}
if(items[0] == "1" && items.Length == 2)
{
stritems = items[1].Trim("[]".ToCharArray()).Split(',');
}
else stritems = items[0].Trim("[]".ToCharArray()).Split(',');
if (_device.ReadLaserMaker) {
_device.LaserMark1ReadResult = "";
foreach(string item in stritems)
{
_device.LaserMark1ReadResult = _device.LaserMark1ReadResult + item + ",";
}
_device.LaserMark1 = stritems[0].Trim("[]".ToCharArray());
_device.CurrentLaserMark = _device.LaserMark1;
_device.LaserMark1Score = 0;
if (stritems.Length > 1 && double.TryParse(stritems[1], out double score))
{
_device.LaserMark1Score = score;
}
else _device.LaserMark1ReadResult = _device.LaserMark1ReadResult + "Failed!";
if (stritems.Length > 2) _device.LaserMark1ReadTime = stritems[2];
EV.PostInfoLog("WIDReader",$"Wafer laser mark1 read : {stritems[0]}, score:{_device.LaserMark1Score},time:{_device.LaserMark1ReadTime}.");
}
else
{
_device.LaserMark2ReadResult = "";
foreach (string item in stritems)
{
_device.LaserMark2ReadResult = _device.LaserMark2ReadResult + item + ",";
}
_device.LaserMark2 = stritems[0].Trim("[]".ToCharArray());
_device.CurrentLaserMark = _device.LaserMark2;
_device.LaserMark2Score = 0;
if (stritems.Length > 1 && double.TryParse(stritems[1], out double score))
_device.LaserMark2Score = score;
else _device.LaserMark2ReadResult = _device.LaserMark2ReadResult + "Failed!";
if (stritems.Length > 2) _device.LaserMark2ReadTime = stritems[2];
EV.PostInfoLog("WIDReader",$"Wafer laser mark2 read : {stritems[0]}, score:{_device.LaserMark2Score},time:{_device.LaserMark2ReadTime}.");
}
_device.ReadOK = true;
_device.CurrentHandlerState = CongnexHandlerState.ExecuteComplete;
return true;
}
}
public class CognexOnlineHandler : IReaderMsg //common move
{
private CognexOcrReader _device;
private bool _online;
public CognexOnlineHandler(CognexOcrReader device)
{
_device = device;
background = false;
}
public void SetExeError()
{
_device.Error = true; ;
}
public bool background { get; }
public string package(params object[] args)
{
_device.CurrentHandlerType = CongnexHandlerType.Online;
_online = (bool) args[0];
if (_online)
return "SO1";
return "SO0";
}
public bool unpackage(string type, string[] items)
{
if(items.Length ==1 && items[0].Trim() =="1")
{
_device.CurrentHandlerState = CongnexHandlerState.ExecuteComplete;
_device.IsOnline = _online;
}
return true;
}
}
public class CognexReadImageHandler : IReaderMsg
{
private readonly CognexOcrReader _device;
//private bool _readStart;
private int _imageLength;
private StringBuilder _stringBuilder;
public CognexReadImageHandler(CognexOcrReader device)
{
_device = device;
background = true;
//_readStart = false;
_imageLength = 0;
_stringBuilder = new StringBuilder();
}
public void SetExeError()
{
_device.Error = true; ;
}
public bool background { get; }
public string package(params object[] args)
{
_device.CurrentHandlerType = CongnexHandlerType.ReadImage;
_device.NeedSocketLog = false;
return "RI";
}
public bool unpackage(string type, string[] items)
{
if(_device.CurrentHandlerState == CongnexHandlerState.CMDSend)
{
if (items.Length>=2 && items[0].Trim() == "1" && int.TryParse(items[1], out _imageLength))
{
_device.CurrentHandlerState = CongnexHandlerState.CMDSuccess;
}
else _device.CurrentHandlerState = CongnexHandlerState.CMDFail;
return true;
}
if(_device.CurrentHandlerState == CongnexHandlerState.CMDSuccess)
{
foreach(string str in items)
{
_stringBuilder?.Append(str.Trim());
}
if (_stringBuilder.Length >= _imageLength)
{
string strimage = _stringBuilder?.ToString().Substring(0, _imageLength);
_device.SaveImage(strimage);
_device.CurrentHandlerState = CongnexHandlerState.ExecuteComplete;
_device.NeedSocketLog = true;
}
}
return true;
}
}
public class CognexGetJobHandler : IReaderMsg
{
private readonly CognexOcrReader _device;
public void SetExeError()
{
_device.Error = true; ;
}
public CognexGetJobHandler(CognexOcrReader device)
{
_device = device;
background = true;
}
public bool background { get; }
public string package(params object[] args)
{
_device.CurrentHandlerType = CongnexHandlerType.GetJob;
return "GF";
}
public bool unpackage(string type, string[] items)
{
if (items[0].Trim() == "1")
{
if (items.Length > 1) _device.CurrentJobName = items[1].Trim();
else _device.CurrentJobName = "";
_device.CurrentHandlerState = CongnexHandlerState.ExecuteComplete;
}
else
{
_device.CurrentHandlerState = CongnexHandlerState.CMDFail;
}
return true;
}
}
public class CognexGetJobListHandler : IReaderMsg
{
private readonly CognexOcrReader _device;
public void SetExeError()
{
_device.Error = true; ;
}
public CognexGetJobListHandler(CognexOcrReader device)
{
_device = device;
background = true;
}
public bool background { get; }
public string package(params object[] args)
{
_device.CurrentHandlerType = CongnexHandlerType.GetJobList;
return "Get Filelist";
}
public bool unpackage(string type, string[] items)
{
if (items[0].Trim() == "1" && items.Length >=2)
{
int filecount;
int.TryParse(items[1].Trim(), out filecount);
var job = items.Where(i => i.Contains(".job")).ToList();
_device.JobFileList = job;
_device.CurrentHandlerState = CongnexHandlerState.ExecuteComplete;
}
else
{
_device.CurrentHandlerState = CongnexHandlerState.CMDFail;
}
return true;
}
}
public class CognexLoadJobHandler : IReaderMsg //common move
{
private readonly CognexOcrReader _device;
private string _job;
public CognexLoadJobHandler(CognexOcrReader device)
{
_device = device;
background = false;
}
public void SetExeError()
{
_device.Error = true; ;
}
public bool background { get; }
public string package(params object[] args)
{
_device.CurrentHandlerType = CongnexHandlerType.LoadJob;
_job = (string) args[0]; //full path
// _job = _job.Substring(_job.LastIndexOf("\\") + 1); //remove dir
// _job = _job.Substring(0, _job.LastIndexOf(".")); //remove expand
return $"LF{_job}.job";
}
public bool unpackage(string type, string[] items)
{
if (items[0].Trim() == "1")
{
_device.CurrentJobName = _job;
_device.CurrentHandlerState = CongnexHandlerState.ExecuteComplete;
}
else
{
_device.CurrentHandlerState = CongnexHandlerState.CMDFail;
}
return true;
}
}
}
@@ -0,0 +1,627 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using Aitex.Common.Util;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using Aitex.Sorter.Common;
using MECF.Framework.Common.Communications;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.SubstrateTrackings;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
using ErrorEventArgs = MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts.ErrorEventArgs;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders
{
public class CognexOcrReader : BaseDevice, IDevice, IConnection
{
public const string delimiter = "\r\n";
private static readonly object _locker = new object();
private readonly string _addr;
private IHandler _foregroundHandler; //current handler
private readonly Queue<IHandler> _handlers = new Queue<IHandler>();
public bool IsLogined { get; set; } = false;
public bool IsOnline { get; set; } = false;
public string ImageFileName => _imageFileName;
public string ImageStorePath => _imageStorePath;
private AsyncSocket _socket;
private string _imageStorePath;
private string _imageFileName;
private string _imageString; //Read image in BMP format
//private int _imageLength; //Read image in BMP format
//private StringBuilder _stringBuilder;
//private bool _readStart;
public CongnexHandlerType CurrentHandlerType { get; set; } = CongnexHandlerType.None;
public CongnexHandlerState CurrentHandlerState { get; set; } = CongnexHandlerState.None;
public Guid OCRGuid { get; set; }
public bool CurrentHandlerExcuteResult { get; set; } = true;
public bool CurrentHandlerExcuteComplete { get; set; } = true;
public string CurrentWaferID { get; set; }
private const string EventCMDFail = "CongnexCommandFailed";
private DeviceTimer _timer = new DeviceTimer();
private int _ts;
public bool NeedSocketLog
{
get;set;
}
public string Address => _addr;
public bool IsConnected => _socket.IsConnected;
public CognexOcrReader(string module, string name, string display, string deviceId, string address)
: base(module, name, display, deviceId)
{
_addr = address;
_socket = new AsyncSocket(address,524288, "");
_socket.OnDataChanged += OnDataChanged;
_socket.OnErrorHappened += OnErrorHandler;
//IsReadImage = false;
Initalized = false;
_imageString = "";
}
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 bool Busy => _handlers.Count > 0 || _foregroundHandler != null;
public bool Error { get; set; }
public bool ReadLaserMaker { get; set; }
public string CurrentJobName { get; set; }
public string LaserMark1 { get; set; }
public double LaserMark1Score { get; set; }
public string LaserMark1ReadTime { get; set; } = string.Empty;
public string LaserMark2 { get; set; }
public double LaserMark2Score { get; set; }
public string LaserMark2ReadTime { get; set; } = string.Empty;
public string CurrentLaserMark { get;set; }
public List<string> JobFileList { get; set; }
public bool ReadOK { get; set; }
public string LaserMark1ReadResult { get; set; }
public string LaserMark2ReadResult { get; set; }
public string ImageString => _imageString;
public bool Connect()
{
_socket.Connect(_addr);
return true;
}
public bool Disconnect()
{
_socket.Dispose();
return true;
}
public bool Initialize()
{
ConnectionManager.Instance.Subscribe(Name, this);
JobFileList = new List<string>();
int retry = 0;
while (!_socket.IsConnected && retry<5)
{
_socket.Connect(_addr);
Thread.Sleep(1000);
retry++;
}
DEVICE.Register(string.Format("{0}.{1}", Name, "ReadWaferID"),//DeviceOperationName.ReadWaferID),
(out string reason, int time, object[] param) =>
{
var bLaser = bool.Parse((string) param[0]);
var jobName = (string) param[1];
var ret = Read(bLaser, jobName, out reason);
if (ret)
{
reason = string.Format("{0}", Name, "Read Laser Mark.");
return true;
}
return false;
});
DEVICE.Register(string.Format("{0}.{1}", Name, "ReadLM1"),//DeviceOperationName.ReadWaferID),
(out string reason, int time, object[] param) =>
{
var bLaser =true;
var jobName = (string)param[0];
var ret = Read(bLaser, jobName, out reason);
if (ret)
{
reason = string.Format("{0}", Name, "Read Laser Mark.");
return true;
}
return false;
});
DEVICE.Register(string.Format("{0}.{1}", Name, "ReadLM2"),//DeviceOperationName.ReadWaferID),
(out string reason, int time, object[] param) =>
{
var bLaser = false;
var jobName = (string)param[0];
var ret = Read(bLaser, jobName, out reason);
if (ret)
{
reason = string.Format("{0}", Name, "Read Laser Mark.");
return true;
}
return false;
});
DEVICE.Register($"{Name}.RefreshJobList", (out string reason, int time, object[] param) =>
{
GetJobList(out reason);
return true;
});
DATA.Subscribe(Name, "WRIDReaderState", () => State);
DATA.Subscribe(Name, "WRIDReaderBusy", () => Busy);
DATA.Subscribe(Name, "LaserMaker1", () => LaserMark1);
DATA.Subscribe(Name, "LaserMaker2", () => LaserMark2);
DATA.Subscribe(Name, "LaserMark1Result", () => LaserMark1ReadResult);
DATA.Subscribe(Name, "LaserMark2Result", () => LaserMark2ReadResult);
DATA.Subscribe(Name, "JobFileList", () => JobFileList);
DATA.Subscribe(Name, "CurrentLaserMark", () => CurrentLaserMark);
EV.Subscribe(new EventItem("Event", EventCMDFail, "Congnex command execution failed.", EventLevel.Alarm, Aitex.Core.RT.Event.EventType.HostNotification));
_ts = SC.ContainsItem("OcrReader.TimeLimitForWID") ? SC.GetValue<int>("OcrReader.TimeLimitForWID") : 5;
var fileInfo = new FileInfo(PathManager.GetDirectory($"Logs\\{DeviceID}"));
if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
fileInfo.Directory.Create();
if (fileInfo.Directory != null)
_imageStorePath = fileInfo.FullName;
_handlers.Clear();
Initalized = true;
if(_socket.IsConnected)
Login(out _);
return true;
}
public void Terminate()
{
_socket.Dispose();
}
public void Monitor()
{
var wafer = WaferManager.Instance.GetWafers(ModuleName.Aligner)[0];
if(wafer.IsWaferEmpty) CurrentLaserMark = string.Empty;
//if (IO.DI["DI_PreAlignerWaferOn"].Value) CurrentLaserMark = string.Empty;
}
public void Reset()
{
lock (_locker)
{
_foregroundHandler = null;
_handlers.Clear();
}
if (Error)
{
Error = false;
_socket.Connect(_addr);
}
}
private string[] GetJobName(bool bLaserMark1)
{
var jobs = string.Empty;
if (bLaserMark1)
jobs = SC.GetStringValue("OcrReader.ReaderJob1Main");
else
jobs = SC.GetStringValue("OcrReader.ReaderJob2Main");
return jobs.Split(';');
}
private bool execute(IHandler handler, out string reason)
{
reason = string.Empty;
NeedSocketLog = true;
lock (_locker)
{
CurrentHandlerExcuteComplete = false;
CurrentHandlerExcuteResult = false;
CurrentHandlerState = CongnexHandlerState.CMDSend;
_foregroundHandler = handler;
if (!handler.Execute(ref _socket))
{
EV.Notify(EventCMDFail);
reason = "Communication failed, please recovery it.";
CurrentHandlerState = CongnexHandlerState.CMDFail;
return false;
}
}
return true;
}
private bool execute(out string reason)
{
reason = string.Empty;
NeedSocketLog = true;
lock (_locker)
{
if (_handlers.Count > 0)
{
_foregroundHandler = _handlers.Dequeue();
CurrentHandlerExcuteComplete = false;
CurrentHandlerExcuteResult = false;
CurrentHandlerState = CongnexHandlerState.CMDSend;
if (!_foregroundHandler.Execute(ref _socket))
{
EV.Notify(EventCMDFail);
reason = " communication failed, please recovery it.";
//LOG.Error(reason);
EV.PostMessage(Name, EventEnum.DefaultWarning, "【Reader】" + reason);
CurrentHandlerState = CongnexHandlerState.CMDFail;
return false;
}
}
}
return true;
}
private void OnDataChanged(string package)
{
try
{
if(package.Contains("User:"))
{
_foregroundHandler = null;
_handlers.Clear();
Login(out _);
return;
}
if (_foregroundHandler == null) return;
if (package.Trim() == "") return;
bool completed = false;
lock (_locker)
{
if (_foregroundHandler != null && _foregroundHandler.OnMessage(ref _socket, package.Trim(), out completed))
{
if (CurrentHandlerState == CongnexHandlerState.ExecuteComplete)
{
_foregroundHandler = null;
var reason = string.Empty;
execute(out reason);
}
if (CurrentHandlerState == CongnexHandlerState.CMDFail)
{
EV.Notify(EventCMDFail);
_foregroundHandler = null;
_handlers.Clear();
}
}
}
}
catch (ExcuteFailedException ex)
{
EV.PostMessage(DeviceID, EventEnum.DefaultWarning, ex.Message);
}
catch (InvalidPackageException ex)
{
EV.PostMessage(DeviceID, EventEnum.DefaultWarning, ex.Message);
}
catch (Exception ex)
{
EV.PostMessage(Name, EventEnum.DefaultWarning, "【Reader】has exception:" + ex);
}
}
private void OnErrorHandler(ErrorEventArgs args)
{
Error = true;
Initalized = false;
EV.PostMessage(Module, EventEnum.CommunicationError, Display, args.Reason);
//EV.PostMessage(Name, EventEnum.DefaultWarning, string.Format("{0} Communication failed,please check it.{1}", Name, args.Reason));
}
private string ConvertJobName(string name)
{
name = name.Substring(name.LastIndexOf("\\") + 1); //remove dir
name = name.Substring(0, name.LastIndexOf(".")); //remove expand
return name;
}
public void SaveImage(string imgString)
{
DeleteEarlyImageFile();
var byBitmap = HexStringToBytes(imgString);
var bmp = new Bitmap(new MemoryStream(byBitmap));
_imageFileName = CurrentWaferID + DateTime.Now.ToString("G").Replace('/','_').Replace(':','_');
bmp.Save($"{_imageStorePath}{_imageFileName}.bmp",ImageFormat.Bmp);
EV.PostInfoLog("WIDReader",$"Picture saved, file name is {_imageFileName}.bmp");
}
private void DeleteEarlyImageFile()
{
string[] fpath = Directory.GetFiles(_imageStorePath, "*.bmp", SearchOption.TopDirectoryOnly);
Dictionary<string, DateTime> fCreateDate = new Dictionary<string, DateTime>();
for (int i = 0; i < fpath.Length; i++)
{
FileInfo fi = new FileInfo(fpath[i]);
fCreateDate[fpath[i]] = fi.CreationTime;
}
fCreateDate = fCreateDate.OrderBy(f => f.Value).ToDictionary(f => f.Key, f => f.Value);
int fCount = fCreateDate.Count;
while (fCount > 99)
{
string strFile = fCreateDate.First().Key;
File.Delete(strFile);
fCreateDate.Remove(strFile);
fCount = fCreateDate.Count;
}
}
private static byte[] HexStringToBytes(string hex)
{
byte[] data = new byte[hex.Length /2];
int j = 0;
for (int i = 0; i < hex.Length; i+=2)
{
data[ j ] = Convert.ToByte(hex.Substring(i, 2), 16);
++j;
}
return data;
}
private string ConvetJobName(string name)
{
name = name.Substring(name.LastIndexOf("\\") + 1); //remove dir
name = name.Substring(0, name.LastIndexOf(".")); //remove expand
return name;
}
#region Command
public bool Login(out string reason)
{
_handlers.Clear();
_handlers.Enqueue(new CongexHandler(new CognexUserNameHandler(this))); //UserName
_handlers.Enqueue(new CongexHandler(new CognexPasswordHandler(this))); //Password
return execute(out reason);
}
public bool ReadOnHostMode(bool bLaserMaker, string[] jobnames, out string reason)
{
_handlers.Clear();
string[] jobs = jobnames;
if (jobs.Length == 0 || string.IsNullOrEmpty(jobs[0]))
{
reason = "Job is undefine";
return false;
}
string jobName = ConvetJobName(jobs[0]).Replace(".job","");
if (CurrentJobName != jobName)
{
_handlers.Enqueue(new CongexHandler(new CognexOnlineHandler(this), false)); //offline
_handlers.Enqueue(new CongexHandler(new CognexLoadJobHandler(this), jobName)); //LoadJob
}
_handlers.Enqueue(new CongexHandler(new CognexOnlineHandler(this), true)); //online
_handlers.Enqueue(new CongexHandler(new CognexReadHandler(this))); //Read
//if (jobs.Length > 1)
//{
// for (int i = 1; i < jobs.Length; i++)
// {
// jobName = ConvetJobName(jobs[i]);
// _handlers.Enqueue(new handler(new CognexOnlineHandler(this), false)); //offline
// _handlers.Enqueue(new handler(new CognexLoadJobHandler(this), jobName)); //LoadJob
// _handlers.Enqueue(new handler(new CognexOnlineHandler(this), true)); //online
// _handlers.Enqueue(new handler(new CognexReadHandler(this))); //Read
// }
//}
ReadOK = false;
ReadLaserMaker = bLaserMaker;
return execute(out reason);
}
public bool Read(out string reason)
{
_handlers.Clear();
string[] jobs = GetJobName(true);
if (jobs.Length == 0 || string.IsNullOrEmpty(jobs[0]))
{
reason = "Job is undefine";
return false;
}
string jobName = ConvetJobName(jobs[0]);
if (CurrentJobName != jobName)
{
_handlers.Enqueue(new CongexHandler(new CognexOnlineHandler(this), false)); //offline
_handlers.Enqueue(new CongexHandler(new CognexLoadJobHandler(this), jobName)); //LoadJob
}
_handlers.Enqueue(new CongexHandler(new CognexOnlineHandler(this), true)); //online
_handlers.Enqueue(new CongexHandler(new CognexReadHandler(this))); //Read
//if (jobs.Length > 1)
//{
// for (int i = 1; i < jobs.Length; i++)
// {
// jobName = ConvetJobName(jobs[i]);
// _handlers.Enqueue(new handler(new CognexOnlineHandler(this), false)); //offline
// _handlers.Enqueue(new handler(new CognexLoadJobHandler(this), jobName)); //LoadJob
// _handlers.Enqueue(new handler(new CognexOnlineHandler(this), true)); //online
// _handlers.Enqueue(new handler(new CognexReadHandler(this))); //Read
// }
//}
ReadOK = false;
ReadLaserMaker = true;
return execute(out reason);
}
public bool Read(bool bLaserMaker, out string reason)
{
_handlers.Clear();
string[] jobs = GetJobName(bLaserMaker);
if (jobs.Length == 0 || string.IsNullOrEmpty(jobs[0]))
{
reason = "Job is undefine";
return false;
}
string jobName = ConvetJobName(jobs[0]);
if (CurrentJobName != jobName)
{
_handlers.Enqueue(new CongexHandler(new CognexOnlineHandler(this), false)); //offline
_handlers.Enqueue(new CongexHandler(new CognexLoadJobHandler(this), jobName)); //LoadJob
}
_handlers.Enqueue(new CongexHandler(new CognexOnlineHandler(this), true)); //online
_handlers.Enqueue(new CongexHandler(new CognexReadHandler(this))); //Read
//if (jobs.Length > 1)
//{
// for (int i = 1; i < jobs.Length; i++)
// {
// jobName = ConvetJobName(jobs[i]);
// _handlers.Enqueue(new handler(new CognexOnlineHandler(this), false)); //offline
// _handlers.Enqueue(new handler(new CognexLoadJobHandler(this), jobName)); //LoadJob
// _handlers.Enqueue(new handler(new CognexOnlineHandler(this), true)); //online
// _handlers.Enqueue(new handler(new CognexReadHandler(this))); //Read
// }
//}
ReadOK = false;
ReadLaserMaker = bLaserMaker;
return execute(out reason);
}
public bool Read(bool bLaserMaker, string jobName, out string reason)
{
_handlers.Clear();
if (string.IsNullOrEmpty(jobName))
{
reason = "Job is undefine.";
return false;
}
jobName = ConvertJobName(jobName);
if (CurrentJobName != jobName)
{
_handlers.Enqueue(new CongexHandler(new CognexOnlineHandler(this), false)); //offline
_handlers.Enqueue(new CongexHandler(new CognexLoadJobHandler(this), jobName)); //LoadJob
}
ReadOK = false;
ReadLaserMaker = bLaserMaker;
_handlers.Enqueue(new CongexHandler(new CognexOnlineHandler(this), true)); //online
_handlers.Enqueue(new CongexHandler(new CognexReadHandler(this))); //Read
return execute(out reason);
}
public bool ReadImage(string waferid,out string reason)
{
_handlers.Clear();
this.CurrentWaferID = waferid;
reason = string.Empty;
_handlers.Enqueue(new CongexHandler(new CognexReadImageHandler(this))); //Read
return execute(out reason);
}
public bool ReadJobName(out string reason)
{
reason = string.Empty;
return execute(new CongexHandler(new CognexGetJobHandler(this)), out reason);
}
public bool GetJobList(out string reason)
{
reason = string.Empty;
return execute(new CongexHandler(new CognexGetJobListHandler(this)), out reason);
}
public bool Online(bool online, out string reason)
{
reason = string.Empty;
return execute(new CongexHandler(new CognexOnlineHandler(this), online), out reason);
}
public bool LoadJob(string jobName, out string reason)
{
reason = string.Empty;
return execute(new CongexHandler(new CognexLoadJobHandler(this), jobName), out reason);
}
#endregion
}
}
@@ -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;
}
}
}
@@ -0,0 +1,279 @@
using System;
using System.Text.RegularExpressions;
using Aitex.Core.RT.Log;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders
{
public interface IReaderMsg
{
string package(params object[] args);
/// </summary>
/// return value, completed
/// <param name="type"></param>
/// <param name="cmd"></param>
/// <returns></returns>
bool unpackage(string type, string[] items);
bool background { get; }
void SetExeError();
}
public class handler : IHandler
{
public int ID { get; set; }
public int Unit { get; set; }
public bool IsBackground { get { return _imp.background; } }
private static int retry_time = 1;
private int retry_count = retry_time;
private IReaderMsg _imp ;
private object[] _objs = null;
public handler(IReaderMsg imp, params object[] objs)
{
_imp = imp;
this._objs = objs;
}
public bool Execute<TPort>(ref TPort port) where TPort : ICommunication
{
retry_count = retry_time;
//return port.Write(string.Format("{0}\r", _imp.package(this._objs)));
return port.Write(string.Format("{0}\r\n", _imp.package(this._objs)));
}
/// <summary>
/// return value: bhandle
/// </summary>
/// <typeparam name="TPort"></typeparam>
/// <param name="port"></param>
/// <param name="msg"></param>
/// <param name="completed"></param>
/// <returns></returns>
public bool OnMessage<TPort>(ref TPort port, string message, out bool completed) where TPort : ICommunication
{
completed = false;
try
{
string msg = message.Trim();
//if (msg.IndexOf("WELCOME") >= 0)
//{
// completed = true;
// return true;
//}
//msg = msg.Replace("USER:","");
//if (string.IsNullOrWhiteSpace(msg))
//{
// completed = true;
// return true;
//}
msg = message.TrimStart('[');
msg = msg.TrimEnd(']');
string[] data = Regex.Split(msg, ",");
completed = _imp.unpackage("", data);
//if (msg.Length == 1)
//{
// if (!msg.Equals("1")) //0: command failed
// {
// _imp.SetExeError();
// completed = true;
// }
// if (!IsBackground)
// {
// _imp.unpackage("", null);
// completed = true;
// }
// return true;
//}
//if (IsBackground)
//{
// msg = message.TrimStart('[');
// msg = msg.TrimEnd(']');
// string[] data = Regex.Split(msg, ",");
// completed = _imp.unpackage("", data);
//}
return true;
}
catch (ExcuteFailedException e)
{
throw (e);
}
catch (Exception ex)
{
LOG.Write(ex);
throw (new InvalidPackageException(message));
}
}
}
public class ReadHandler : IReaderMsg //common move
{
public bool background { get; private set; }
private OcrReader _device ;
public ReadHandler(OcrReader device)
{
_device = device;
background = false;
}
public string package(params object[] args)
{
return string.Format("SM\"READ\"0 ");
}
public void SetExeError()
{
_device.ExeError = true;
}
public bool unpackage(string type, string[] items)
{
if(items.Length == 1)
{
if (items[0] != "1" && !items[0].Contains("WELCOME"))
{
SetExeError();
return true;
}
else return false;
}
if (_device.ReadLaserMaker)
{
_device.LaserMaker = items[0];
_device.LaserMark1 = items[0];
if (items.Length > 1) _device.LaserMark1Score = items[1];
if (items.Length > 2) _device.LaserMark1ReadTime = items[2];
LOG.Write($"{_device.Name} laser marker updated to {_device.LaserMaker}");
}
else
{
_device.T7Code = items[0];
_device.LaserMark2 = items[0];
if (items.Length > 1) _device.LaserMark2Score = items[1];
if (items.Length > 2) _device.LaserMark2ReadTime = items[2];
LOG.Write($"{_device.Name} T7 code updated to {_device.T7Code}");
}
_device.ReadOK = double.Parse(items[1]) > 0;
return true;
}
}
public class OnlineHandler : IReaderMsg //common move
{
public bool background { get; private set; }
private OcrReader _device ;
private bool _online = false;
public OnlineHandler(OcrReader device)
{
_device = device;
background = false;
}
public string package(params object[] args)
{
_online = (bool)args[0];
if(_online)
return string.Format("SO1");
return string.Format("SO0");
}
public void SetExeError()
{
_device.ExeError = true;
}
public bool unpackage(string type, string[] items)
{
if (items[0] != "1" && !items[0].Contains("WELCOME"))
SetExeError();
return true;
}
}
public class GetJobHandler : IReaderMsg
{
public bool background { get; private set; }
private OcrReader _device ;
public GetJobHandler(OcrReader device)
{
_device = device;
background = false;
}
public string package(params object[] args)
{
return string.Format("GF");
}
public void SetExeError()
{
_device.ExeError = true;
}
public bool unpackage(string type, string[] items)
{
//if (items[0] != "1")
//{
// SetExeError();
// return true;
//}
//else return false;
_device.JobName = (string)items[0];
return true;
}
}
public class LoadJobHandler : IReaderMsg //common move
{
public bool background { get; private set; }
private OcrReader _device ;
private string _job;
public LoadJobHandler(OcrReader device)
{
_device = device;
background = false;
}
public string package(params object[] args)
{
_job = (string)args[0]; //full path
// _job = _job.Substring(_job.LastIndexOf("\\") + 1); //remove dir
// _job = _job.Substring(0, _job.LastIndexOf(".")); //remove expand
return string.Format("LF{0}.job",_job);
}
public void SetExeError()
{
_device.ExeError = true;
}
public bool unpackage(string type, string[] items)
{
if (items[0] != "1" && !items[0].Contains("WELCOME"))
SetExeError();
else _device.JobName = _job;
return true;
}
}
}
@@ -0,0 +1,304 @@
using Aitex.Common.Util;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.IO;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.IOSS
{
public class IossWidReader: OCRReaderBaseDevice, IConnection
{
public IossWidReader(string module,string name,string scRoot):base(module,name)
{
_scRoot = scRoot;
InitIoss();
CheckToPostMessage((int)OCRReaderMsg.StartInit, null);
}
private void InitIoss()
{
JobFileList = new List<string>();
lib = new Wid110Lib();
Address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
_enableLog = SC.GetValue<bool>($"{_scRoot}.{Name}.EnableLogMessage");
if (!isValidIP(Address))
{
EV.PostAlarmLog("System", $"Invalid IP address for WIDReader:{Name}");
return;
}
if (!lib.FInit(Address))
{
EV.PostAlarmLog("System", $"WIDReader:{Name} initialize failed");
int eno = Wid110LibConst.ecNotInit;
eno = lib.FGetLastError();
if (lib.isException())
LOG.Write("getLastError(): EXCEPTION\r\n" + lib.getLastExcp());
LOG.Write("getLastError(): return " + eno);
return;
}
var fileInfo = new FileInfo(PathManager.GetDirectory($"Logs\\{Name}"));
if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
fileInfo.Directory.Create();
if (fileInfo.Directory != null)
_imageStorePath = fileInfo.FullName;
EV.PostInfoLog("System", $"WIDReader:{Name} initialize successful");
IsConnected = true;
}
private string _imageStorePath;
private bool isValidIP(string ip)
{
char[] sep = { '.' };
string[] adr = ip.Split(sep);
try
{
return (isValidIPPart(Convert.ToInt32(adr[0]))
&& isValidIPPart(Convert.ToInt32(adr[1]))
&& isValidIPPart(Convert.ToInt32(adr[2]))
&& isValidIPPart(Convert.ToInt32(adr[3])));
}
catch (Exception e)
{
LOG.Write("isValidIP( " + ip + " )\r\n"
+ "ERROR: Invalid IP Address\r\n"
+ e.ToString());
return false;
}
}
private bool isValidIPPart(int adr)
{
return (adr >= 0 && adr <= 255);
}
private Wid110Lib lib;
private string _scRoot;
public string Address { get; private set; }
private bool _enableLog;
public bool IsConnected { get; set; }
protected override bool fStartSavePicture(object[] param)
{
return true;
}
protected override bool fStartReset(object[] param)
{
Address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
_enableLog = SC.GetValue<bool>($"{_scRoot}.{Name}.EnableLogMessage");
if (!isValidIP(Address))
{
EV.PostAlarmLog("System", $"Invalid IP address for WIDReader:{Name}");
return false;
}
if (!lib.FInit(Address))
{
EV.PostAlarmLog("System", $"WIDReader:{Name} initialize failed");
int eno = Wid110LibConst.ecNotInit;
eno = lib.FGetLastError();
if (lib.isException())
LOG.Write("getLastError(): EXCEPTION\r\n" + lib.getLastExcp());
LOG.Write("getLastError(): return " + eno);
return false;
}
EV.PostInfoLog("System", $"WIDReader:{Name} initialize successful");
IsConnected = true;
return true; ;
}
protected override bool fStartInit(object[] param)
{
return true;
}
protected override bool fMonitorInit(object[] param)
{
return true;
}
protected override bool fStartSetParameter(object[] param)
{
return true ;
}
private string m_readparameter;
protected override bool fStartReadParameter(object[] param)
{
m_readparameter = param[0].ToString();
switch (m_readparameter)
{
case "JobList":
if (SC.ContainsItem($"{ _scRoot}.{ Name}.DirectoryForJob") && !string.IsNullOrEmpty(SC.GetStringValue($"{ _scRoot}.{ Name}.DirectoryForJob")))
{
string jobpath = SC.GetStringValue($"{ _scRoot}.{ Name}.DirectoryForJob");
string[] files = Directory.GetFiles(jobpath);
JobFileList = new List<string>();
JobFileList.Clear();
foreach (string strfile in files)
{
FileInfo f = new FileInfo(strfile);
if (f.Extension == ".job")
{
JobFileList.Add(f.Name);
}
}
}
break;
default:
break;
}
return true; ;
}
protected override bool fMonitorReadParameter(object[] param)
{
return true;
}
protected override bool fStartReadWaferID(object[] param)
{
string job = param[0].ToString();
int lasermarkindex = (int)param[1];
IsReadLaserMark1 = lasermarkindex == 0;
string path = SC.GetStringValue($"{ _scRoot}.{ Name}.DirectoryForJob");
if(!lib.FLoadRecipes(path + "\\" + job))
{
string le = lib.FGetErrorDescription(lib.FGetLastError());
OnError("Load job failed:"+le);
return false;
}
if (!lib.FProcessRead())
{
string le = lib.FGetErrorDescription(lib.FGetLastError());
OnError("Read laser mark failed:" +le);
return false;
}
return true;
//return lib.FGetWaferId();
}
protected override bool fMonitorReading(object[] param)
{
CurrentLaserMark = lib.FGetWaferId().Replace("READ:","").Trim();
if (IsReadLaserMark1)
{
LaserMark1 = CurrentLaserMark;
LaserMark1Score = lib.FGetCodeQualityOCR().ToString();
LaserMark1ReadTime = lib.FGetCodeTime().ToString();
LaserMark1ReadResult = $"ID:{LaserMark1},Score:{LaserMark1Score},Read time:{LaserMark1ReadTime}";
}
else
{
LaserMark2 = CurrentLaserMark;
LaserMark2 = CurrentLaserMark;
LaserMark2Score = lib.FGetCodeQualityOCR().ToString();
LaserMark2ReadTime = lib.FGetCodeTime().ToString();
LaserMark2ReadResult = $"ID:{LaserMark2},Score:{LaserMark2Score},Read time:{LaserMark2ReadTime}";
}
GetProcessImage();
IsBusy = false;
return true;
}
private void GetProcessImage(int bestOrAll=0)
{
if (!lib.FIsInitialized())
{
string errMsg;
if (lib.CheckError(out errMsg))
{
OnError("ERROR: " + errMsg);
}
return;
}
int counter = 0;
while (true)
{
CurrentImageFileName = Path.GetFullPath(lib.getTmpImage());
if (!lib.FProcessGetImage(CurrentImageFileName, bestOrAll))
{
if (lib.getErrno() == Wid110LibConst.ecNoMoreImg)
{
EV.PostInfoLog("WIDReader",counter.ToString() + " images retrieved after last process trigger.");
return;
}
string errMsg;
if (lib.CheckError(out errMsg))
{
OnError("ERROR: " + errMsg);
}
}
counter++;
}
}
public override string[] GetJobFileList()
{
return JobFileList.ToArray();
}
public bool Connect()
{
throw new NotImplementedException();
}
public bool Disconnect()
{
throw new NotImplementedException();
}
public override void Terminate()
{
try
{
if (!lib.FExit())
{
LOG.Write(lib.FGetErrorDescription(lib.FGetLastError()));
}
}
catch(Exception ex)
{
LOG.Write(ex);
}
}
}
}
@@ -0,0 +1,464 @@
#define TEST_FOR_EXTENSION_OF_LIB
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.IOSS;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.IOSS
{
static partial class Wid110LibConst
{
// ====================================================================
/// <summary>
/// Constants that should be used overall WID110 library software.
/// </summary>
// ====================================================================
// local system resources
//
public static string tmpImage = "testImage_WidLib.bmp";
// return values: these must correspond with 'WID110Dll.h'
// these are return values only for c-function calls
//
// function executed sucessfully
public const int rcNoError = 1; // RETVAL_NO_ERROR
// function failed, calls to FGetLastError()
// and FGetErrorDescription() possible
public const int rcError = 0; // RETVAL_ERROR
// function parameter contained invalid lib handle, call
// to FGetErrorDescription() possible
public const int rcInvObj = -1; // RETVAL_INV_OBJ
// error codes: these must correspond with 'WID110Dll.h'
// these are values for internal lib errors returned by FGetLastError()
// an error description can be retrieved by calling FGetErrorDescription()
//
public static int ecInvObj = -1; // RETVAL_INV_OBJ
public static int ecNone = 0; // ERROR_NONE
public static int ecNotInit = 1; // ERROR_NOT_INIT
public static int ecNotFound = 2; // ERROR_READER_NOTFOUND
public static int ecNetInit = 3; // ERROR_NETWORK_INIT
public static int ecNetIP = 4; // ERROR_NETWORK_IP
public static int ecNetSend = 5; // ERROR_NETWORK_SEND
public static int ecNetRecv = 6; // ERROR_NETWORK_RECEIVE
public static int ecFileName = 7; // ERROR_FILENAME
public static int ecImgSave = 8; // ERROR_IMG_SAVE
public static int ecParLoad = 9; // ERROR_PARAM_LOAD
public static int ecNoProcTrg = 10; // ERROR_NO_PROC_TRIGGERSTR
public static int ecArgBufSz = 11; // ERROR_ARGBUFFERSIZE
public static int ecNoFailSt = 12; // ERROR_NO_FAILSTR
public static int ecNoMoreImg = 13; // ERROR_NO_MORE_IMAGES
public static int ecNoResult = 14; // ERROR_NO_VALID_RESULT
public static int ecNoImage = 15; // ERROR_NO_VALID_IMAGE
public static int ecNoTrgStr = 16; // ERROR_NO_TRIGGERSTRING
public static int ecNoVersPar = 17; // ERROR_VERSION_PARAMETERSET
public static int ecPOutOfRng = 18; // ERROR_PARAMETER_OUTOFRANGE
public static int ecNetTrig = 19; // ERROR_NET_TRIGGERING
public static int ecReaderTimeout = 20; //ERROR_READER_TIMEOUT
public static int ecReaderNotRunning = 21; //ERROR_READER_NOT_RUNNING
// parameter values for FProcessGetImage(type)
// these must correspond with 'WID110Dll.h'
//
public static int pvImgBest = 0; // IMG_PROCESS_BEST
public static int pvImgAll = 1; // IMG_PROCESS_ALL
// dummy results
//
public static string rsltFAIL = "fail";
public static string rsltOK = "OK";
public static string rsltERROR = "no read result";
public static string rsltBLANK = " ";
public static string rsltREAD = "READ: ";
public static string rsltNOREAD = "NOREAD: ";
// return value for FGetCodeQualityX()
// if there is no quality retrieved, call GetLastError() then
public static int rsltNoCodeQuality = -1;
// return value for FGetCodeTime()
// if there is no time retrieved, call GetLastError() then
public static int rsltNoCodeTime = -1;
// dummy error messages
//
public static string errNO = "no error";
public static string errDESC = "ERROR; no error description";
// string buffer sizes
//
public static int errLen = 256;
public static int versLenCS = 63;
public static int versLenC = versLenCS + 1;
public static int rsltLenCS = 259;
public static int rsltLenC = rsltLenCS + 1;
}
}
/**********************************************************************************************//**
* @struct WID_CAPTURE
*
* @brief WID120 Grabbing data
*
* @author Jg
* @date 10.05.2017
**************************************************************************************************/
public struct WID_CAPTURE
{
public int widColor; //!< light color (0..2)
public int widChannel; //!< light channel (0..6)
public int widIntensity; //!< light intensity (0..180) 0=off
public int widRotated; //!< Image Rotated (0..1)
public int widFlipped; //!< Image Flipped (0..1)
};
/**********************************************************************************************//**
* @struct WID_ROI
*
* @brief A wid region of interest
*
* @author Jg
* @date 14.06.2017
**************************************************************************************************/
public struct WID_ROI
{
public int roiXS; //!< X-Start (0..960)
public int roiXL; //!< X-Length (64..960)
public int roiYS; //!< Y-Start (0..304)
public int roiYL; //!< Y-Length (64..368)
};
/**********************************************************************************************//**
* @struct Unsafe WID_OCR
*
* @brief WID120 OCR parameter (Internal used by <see cref="Wid110Lib"/>
*
* @author Jg
* @date 10.05.2017
**************************************************************************************************
* 16.04.2020 MAI Changed char array to fixed byte. Added StructLayout attribute.
[**************************************************************************************************/
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct WID_OCR_Unsafe
{
public fixed byte widFontName[12]; //!< Name of font "semi_5x9","semi_org","semi_lin","ocra"
public fixed byte widFielding[32]; //!< Fielding of String "aannnn-nn-cc"
public fixed byte widFormat[32]; //!< Fielding of String "++++++++++++"
public fixed byte widResult[32]; //!< Result of String "Reading Result"
public int widMinSimilarity; //!< minimum Similarity (50..75)
public int widAccSimilarity; //!< accepted Similarity (85..99)
public int widSpacing; //!< Spacing of Character (80..200)
public int widRotation; //!< Rotation of charactor (..90..)
public int widAdjustSpace; //!< Adjust Spacing (0..1)
public int widAdjustSize; //!< Adjust Size of Characters (0..1)
public int widFilter; //!< Filter (0..40)
public int widCharSizeX; //!< Character Size in X (15.. 60)
public int widCharSizeY; //!< Character Size in Y (27..108)
public int widCharPosX; //!< Character Position in X (64..960)
public int widCharPosY; //!< Character Position in Y (64..304)
public WID_ROI widRoi; //!< Region of Interrest
};
/**********************************************************************************************//**
* @class WID_OCR
*
* @brief WID120 OCR parameter
*
* @author MAI
* @date 16.04.2020
**************************************************************************************************/
public class WID_OCR
{
public string widFontName; //!< Name of font "semi_5x9","semi_org","semi_lin","ocra"
public string widFielding; //!< Fielding of String "aannnn-nn-cc"
public string widFormat; //!< Fielding of String "++++++++++++"
public string widResult; //!< Result of String "Reading Result"
public int widMinSimilarity; //!< minimum Similarity (50..75)
public int widAccSimilarity; //!< accepted Similarity (85..99)
public int widSpacing; //!< Spacing of Character (80..200)
public int widRotation; //!< Rotation of charactor (..90..)
public int widAdjustSpace; //!< Adjust Spacing (0..1)
public int widAdjustSize; //!< Adjust Size of Characters (0..1)
public int widFilter; //!< Filter (0..40)
public int widCharSizeX; //!< Character Size in X (15.. 60)
public int widCharSizeY; //!< Character Size in Y (27..108)
public int widCharPosX; //!< Character Position in X (64..960)
public int widCharPosY; //!< Character Position in Y (64..304)
public WID_ROI widRoi; //!< Region of Interrest
public WID_OCR() { }
public unsafe WID_OCR(WID_OCR_Unsafe s)
{
widFontName = TypeConversion.FixedByteToString(s.widFontName);
widFielding = TypeConversion.FixedByteToString(s.widFielding);
widFormat = TypeConversion.FixedByteToString(s.widFormat);
widResult = TypeConversion.FixedByteToString(s.widResult);
widMinSimilarity = s.widMinSimilarity;
widAccSimilarity = s.widAccSimilarity;
widSpacing = s.widSpacing;
widRotation = s.widRotation;
widAdjustSpace = s.widAdjustSpace;
widAdjustSize = s.widAdjustSize;
widFilter = s.widFilter;
widCharSizeX = s.widCharSizeX;
widCharSizeY = s.widCharSizeY;
widCharPosX = s.widCharPosX;
widCharPosY = s.widCharPosY;
widRoi = s.widRoi;
}
public unsafe WID_OCR_Unsafe ToUnsafeStruct()
{
WID_OCR_Unsafe s = new WID_OCR_Unsafe();
TypeConversion.StringToFixedByte(widFontName, s.widFontName, 12);
TypeConversion.StringToFixedByte(widFielding, s.widFielding, 32);
TypeConversion.StringToFixedByte(widFormat, s.widFormat, 32);
TypeConversion.StringToFixedByte(widResult, s.widResult, 32);
s.widMinSimilarity = widMinSimilarity;
s.widAccSimilarity = widAccSimilarity;
s.widSpacing = widSpacing;
s.widRotation = widRotation;
s.widAdjustSpace = widAdjustSpace;
s.widAdjustSize = widAdjustSize;
s.widFilter = widFilter;
s.widCharSizeX = widCharSizeX;
s.widCharSizeY = widCharSizeY;
s.widCharPosX = widCharPosX;
s.widCharPosY = widCharPosY;
s.widRoi = widRoi;
return s;
}
}
// ====================================================================
/// <summary>
/// Type Conversion class.
/// </summary>
// ====================================================================
public static class TypeConversion
{
// ====================================================================
/// <summary>
/// Convert from unsafe fixed byte array to managed string
/// </summary>
/// <param name="sender">fixed byte array</param>
/// <returns>string</returns>
// ====================================================================
public static unsafe string FixedByteToString(byte* sender)
{
List<byte> data = new List<byte>();
for (byte* counter = sender; *counter != 0; counter++)
{
data.Add(*counter);
}
return System.Text.Encoding.ASCII.GetString(data.ToArray()).Trim('\0');
}
// ====================================================================
/// <summary>
/// Convert from managed string to unsafe fixed byte array
/// </summary>
/// <param name="value">input string</param>
/// <param name="result">fixed byte array (output)</param>
// ====================================================================
public static unsafe void StringToFixedByte(string value, byte* result, int length)
{
if (string.IsNullOrEmpty(value)) value = "";
byte[] valueBytes = System.Text.Encoding.ASCII.GetBytes(value);
byte* counter = result;
for (int index = 0; index < length; index++)
{
if (index < value.Length) *counter = valueBytes[index];
else *counter = 0x00;
counter++;
}
}
}
/**********************************************************************************************//**
* @struct Unsafe WID_BCR
*
* @brief WID120 Barcode Parameter (Internal used by <see cref="Wid110Lib"/>
*
* @author Jg
* @date 10.05.2017
**************************************************************************************************
* 16.04.2020 MAI Changed char array to fixed byte. Added StructLayout attribute.
**************************************************************************************************/
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct WID_BCR_Unsafe
{
public fixed byte widFormat[32]; //!< Format of String "++++++++++++"
public fixed byte widConversion[48]; //!< IBM- Conversion Table ("000102030405060708091011121314151517")
public int widIBM_RtoL; //!< Activate IBM BC412 (0..1)
public int widIBM_LtoR; //!< Activate IBM BC412 (0..1)
public int widIBMConversion; //!< IBM- Conversion (0..2) None,Base 35,Custom A, Custom V, Custom R, Programmable
public int widSemi; //!< Activate Semi Barcode (0..1)
public int widTIConversion; //!< TI Conversion (0..3) None,Base 35, Custom, Custom Checksum
public int widBarCodeLength; //!< Code Length (0..18) 0=auto
public int widSeparator; //!< Separator Character (0..4) none,DASH,POINT,SPACE,HASH
public int widDigits; //!< Wafer Number (0..3) 2 digits, suppress leading zero, 3 digits
public int widEnableAltis; //!< Enable Altis (0..1)
public int widCheckSum; //!< Show Check Character (0..1)
public int widResolution; //!< Resolution of Barcode (0..2) Standard, High Resolution, Standard & High Resolution
public int widLowContrast; //!< Contrast of Barcode (0..1) Activate Low Contrast Codes
public WID_ROI widRoi; //!< Region of Interrest
};
/**********************************************************************************************//**
* @class WID_BCR
*
* @brief WID120 Barcode parameter
*
* @author MAI
* @date 16.04.2020
**************************************************************************************************/
public class WID_BCR
{
public string widFormat; //!< Format of String "++++++++++++"
public string widConversion; //!< IBM- Conversion Table ("000102030405060708091011121314151517")
public int widIBM_RtoL; //!< Activate IBM BC412 (0..1)
public int widIBM_LtoR; //!< Activate IBM BC412 (0..1)
public int widIBMConversion; //!< IBM- Conversion (0..2) None,Base 35,Custom A, Custom V, Custom R, Programmable
public int widSemi; //!< Activate Semi Barcode (0..1)
public int widTIConversion; //!< TI Conversion (0..3) None,Base 35, Custom, Custom Checksum
public int widBarCodeLength; //!< Code Length (0..18) 0=auto
public int widSeparator; //!< Separator Character (0..4) none,DASH,POINT,SPACE,HASH
public int widDigits; //!< Wafer Number (0..3) 2 digits, suppress leading zero, 3 digits
public int widEnableAltis; //!< Enable Altis (0..1)
public int widCheckSum; //!< Show Check Character (0..1)
public int widResolution; //!< Resolution of Barcode (0..2) Standard, High Resolution, Standard & High Resolution
public int widLowContrast; //!< Contrast of Barcode (0..1) Activate Low Contrast Codes
public WID_ROI widRoi; //!< Region of Interrest
public WID_BCR() { }
public unsafe WID_BCR(WID_BCR_Unsafe s)
{
widFormat = TypeConversion.FixedByteToString(s.widFormat);
widConversion = TypeConversion.FixedByteToString(s.widConversion);
widIBM_RtoL = s.widIBM_RtoL;
widIBM_LtoR = s.widIBM_LtoR;
widIBMConversion = s.widIBMConversion;
widSemi = s.widSemi;
widTIConversion = s.widTIConversion;
widBarCodeLength = s.widBarCodeLength;
widSeparator = s.widSeparator;
widDigits = s.widDigits;
widEnableAltis = s.widEnableAltis;
widCheckSum = s.widCheckSum;
widResolution = s.widResolution;
widLowContrast = s.widLowContrast;
widRoi = s.widRoi;
}
public unsafe WID_BCR_Unsafe ToUnsafeStruct()
{
WID_BCR_Unsafe s = new WID_BCR_Unsafe();
TypeConversion.StringToFixedByte(widFormat, s.widFormat, 32);
TypeConversion.StringToFixedByte(widConversion, s.widConversion, 48);
s.widIBM_RtoL = widIBM_RtoL;
s.widIBM_LtoR = widIBM_LtoR;
s.widIBMConversion = widIBMConversion;
s.widSemi = widSemi;
s.widTIConversion = widTIConversion;
s.widBarCodeLength = widBarCodeLength;
s.widSeparator = widSeparator;
s.widDigits = widDigits;
s.widEnableAltis = widEnableAltis;
s.widCheckSum = widCheckSum;
s.widResolution = widResolution;
s.widLowContrast = widLowContrast;
s.widRoi = widRoi;
return s;
}
}
/**********************************************************************************************//**
* @struct Unsafe WID_DMR
*
* @brief WID120 2D-Code Parameter (Internal used by <see cref="Wid110Lib"/>
*
* @author Jg
* @date 10.05.2017
**************************************************************************************************
* 16.04.2020 MAI Changed char array to fixed byte. Added StructLayout attribute.
**************************************************************************************************/
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct WID_DMR_Unsafe
{
public int widSymbol; //!< Activate Code Type (0 = DataMatrix, 1 = QR-Code
public int widLinNrm; //!< linear Code (normal) (0/1) off/on
public int widLinInv; //!< linear Code (invers) (0/1) off/on
public int widDotNrm; //!< Punkt Code (normal) (0/1) off/on
public int widDotInv; //!< Punkt Code (invers) (0/1) off/on
public int widCodeType; //!< Activate Code Type (0/1) normal/mirrored
public int widCodeSize; //!< Module Size of Code (0..3) large, semi, small, tiny
public fixed byte widFormat[32]; //!< Format of String "++++++++++++"
public WID_ROI widRoi; //!< Region of Interrest
};
/**********************************************************************************************//**
* @class WID_DMR
*
* @brief WID120 2D-Code parameter
*
* @author MAI
* @date 16.04.2020
**************************************************************************************************/
public class WID_DMR
{
public int widSymbol; //!< Activate Code Type (0 = DataMatrix, 1 = QR-Code
public int widLinNrm; //!< linear Code (normal) (0/1) off/on
public int widLinInv; //!< linear Code (invers) (0/1) off/on
public int widDotNrm; //!< Punkt Code (normal) (0/1) off/on
public int widDotInv; //!< Punkt Code (invers) (0/1) off/on
public int widCodeType; //!< Activate Code Type (0/1) normal/mirrored
public int widCodeSize; //!< Module Size of Code (0..3) large, semi, small, tiny
public string widFormat; //!< Format of String "++++++++++++"
public WID_ROI widRoi; //!< Region of Interrest
public WID_DMR() { }
public unsafe WID_DMR(WID_DMR_Unsafe s)
{
widSymbol = s.widSymbol;
widLinNrm = s.widLinNrm;
widLinInv = s.widLinInv;
widDotNrm = s.widDotNrm;
widDotInv = s.widDotInv;
widCodeType = s.widCodeType;
widCodeSize = s.widCodeSize;
widFormat = TypeConversion.FixedByteToString(s.widFormat);
widRoi = s.widRoi;
}
public unsafe WID_DMR_Unsafe ToUnsafeStruct()
{
WID_DMR_Unsafe s = new WID_DMR_Unsafe();
s.widSymbol = widSymbol;
s.widLinNrm = widLinNrm;
s.widLinInv = widLinInv;
s.widDotNrm = widDotNrm;
s.widDotInv = widDotInv;
s.widCodeType = widCodeType;
s.widCodeSize = widCodeSize;
TypeConversion.StringToFixedByte(widFormat, s.widFormat, 32);
s.widRoi = widRoi;
return s;
}
}
@@ -0,0 +1,472 @@
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Fsm;
using Aitex.Core.RT.OperationCenter;
using MECF.Framework.Common.DBCore;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.Event;
using MECF.Framework.Common.SubstrateTrackings;
using System;
using System.Collections.Generic;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders
{
public abstract class OCRReaderBaseDevice : Entity, IDevice, IEntity
{
public OCRReaderBaseDevice(string module,string name):base()
{
Module = module;
Name = name;
InitializeOCRReader();
}
public ModuleName InstalledModule { get; set; }
public event Action<bool> ActionDone;
public event Action<string, AlarmEventItem> OnDeviceAlarmStateChanged;
public bool IsBusy = false;
public OCRReaderStateEnum DeviceState => (OCRReaderStateEnum)fsm.State;
public string CurrentJobName { get; set; }
public bool IsReadLaserMark1 { get; set; }
public string LaserMark1 { get; set; } = "";
public string LaserMark1Score { get; set; } = "";
public string LaserMark1ReadTime { get; set; } = string.Empty;
public string LaserMark2 { get; set; } = "";
public string LaserMark2Score { get; set; } = "";
public string LaserMark2ReadTime { get; set; } = string.Empty;
public string CurrentLaserMark { get; set; } = "";
public string CurrentLaserMarkOnWafer
{
get
{
if (WaferManager.Instance.CheckHasWafer(ModuleName.Aligner, 0))
return CurrentLaserMark;
return "";
}
}
public virtual string CurrentImageFileName
{
get; set;
} = "";
public DateTime StartReadTime { get; private set; }
public int TimeLimitForRead { get; set; } = 30;
public List<string> JobFileList { get; set; }
public bool ReadOK { get; set; }
public string AlarmWIDReadTimeout { get => Name.ToString() + "WIDReadTimeout"; }
public string AlarmWIDLostCommunication { get => Name.ToString() + "WIDLostCommunication"; }
public string AlarmWIDLoadJobFail { get => Name.ToString() + "WIDLoadJobFail"; }
public string LaserMark1ReadResult { get; set; }
public string LaserMark2ReadResult { get; set; }
public virtual bool IsReady()
{
if (DeviceState != OCRReaderStateEnum.Idle)
return false;
if (IsBusy)
return false;
return true;
}
private void InitializeOCRReader()
{
BuildTransitionTable();
SubscribeDataVariable();
SubscribeOperation();
SubscribeDeviceOperation();
Running = true;
}
private void SubscribeDeviceOperation()
{
DEVICE.Register(string.Format("{0}.{1}", Name, "ReadWaferID"),//DeviceOperationName.ReadWaferID),
(out string reason, int time, object[] param) =>
{
var bLaser = bool.Parse((string)param[0]);
var jobName = (string)param[1];
var ret = ReadWaferID(jobName, bLaser?0:1);
if (ret)
{
reason = string.Format("{0}", Name, "Read Laser Mark.");
return true;
}
else
reason = string.Format("{0}", Name, "Can't read Laser Mark.");
return false;
});
DEVICE.Register(string.Format("{0}.{1}", Name, "ReadLM1"),//DeviceOperationName.ReadWaferID),
(out string reason, int time, object[] param) =>
{
var jobName = (string)param[0];
var ret = ReadWaferID(jobName, 0);
if (ret)
{
reason = string.Format("{0}", Name, "Read Laser Mark.");
return true;
}
else
reason = string.Format("{0}", Name, "Can't read Laser Mark.");
return false;
});
DEVICE.Register(string.Format("{0}.{1}", Name, "ReadLM2"),//DeviceOperationName.ReadWaferID),
(out string reason, int time, object[] param) =>
{
reason = "";
var jobName = (string)param[0];
var ret = ReadWaferID(jobName,1);
if (ret)
{
reason = string.Format("{0}", Name, "Read Laser Mark.");
return true;
}
else
reason = string.Format("{0}", Name, "Can't read Laser Mark.");
return false;
});
DEVICE.Register($"{Name}.RefreshJobList", (out string reason, int time, object[] param) =>
{
reason = "";
return CheckToPostMessage((int)OCRReaderMsg.ReadParameter, new object[] { "JobList" });
});
DEVICE.Register($"{Name}.Reset", (out string reason, int time, object[] param) =>
{
reason = "";
return CheckToPostMessage((int)OCRReaderMsg.Reset, new object[] { "Reset" });
});
DEVICE.Register($"{Name}.ManualSetLaserMark", (out string reason, int time, object[] param) =>
{
reason = "";
CurrentLaserMark = param[0].ToString();
var wafer = WaferManager.Instance.GetWafer(InstalledModule, 0);
if (!wafer.IsWaferEmpty)
{
//wafer.LaserMarker = CurrentLaserMark;
Guid guid = Guid.NewGuid();
OCRDataRecorder.OcrReadComplete(guid.ToString(), wafer.WaferID, wafer.WaferOriginStation.ToString(),
wafer.OriginCarrierID ?? "", wafer.WaferOriginSlot.ToString(), "0", "0", true, CurrentLaserMark,
"0", "0");
}
return true;
});
}
private void SubscribeOperation()
{
OP.Subscribe($"{Name}.ReadWaferID", (string cmd, object[] param) =>
{
var bLaser = bool.Parse(param[0].ToString());
var jobName = (string)param[1];
var ret = ReadWaferID(jobName, bLaser ? 0 : 1);
if (!ret)
{
EV.PostWarningLog(Module, $"{Name} can not read laser mark.");
return false;
}
EV.PostInfoLog(Module, $"{Name} start read laser mark");
return true;
});
OP.Subscribe($"{Name}.ReadLM1", (string cmd, object[] param) =>
{
var jobName = (string)param[0];
var ret = ReadWaferID(jobName, 0);
if (ret)
{
return true;
}
return false;
});
OP.Subscribe($"{Name}.RefreshJobList", (string cmd, object[] param) =>
{
return CheckToPostMessage((int)OCRReaderMsg.ReadParameter, new object[] { "JobList" });
});
OP.Subscribe($"{Name}.Reset", (out string reason, int time, object[] param) =>
{
reason = "";
return CheckToPostMessage((int)OCRReaderMsg.Reset, new object[] { "Reset" });
});
}
private void SubscribeDataVariable()
{
DATA.Subscribe(Name, "WIDReaderState", () => DeviceState.ToString());
DATA.Subscribe(Name, "WIDReaderBusy", () => (DeviceState != OCRReaderStateEnum.Idle && DeviceState != OCRReaderStateEnum.Init));
DATA.Subscribe(Name, "WRIDReaderState", () => DeviceState.ToString());
DATA.Subscribe(Name, "WRIDReaderBusy", () => (DeviceState != OCRReaderStateEnum.Idle && DeviceState != OCRReaderStateEnum.Init));
DATA.Subscribe(Name, "LaserMaker1", () => LaserMark1);
DATA.Subscribe(Name, "LaserMaker2", () => LaserMark2);
DATA.Subscribe(Name, "LaserMark1Result", () => LaserMark1ReadResult);
DATA.Subscribe(Name, "LaserMark2Result", () => LaserMark2ReadResult);
DATA.Subscribe(Name, "JobFileList", () => JobFileList);
DATA.Subscribe(Name, "CurrentLaserMark", () => CurrentLaserMarkOnWafer);
DATA.Subscribe(Name, "CurrentImageFileName", () => CurrentImageFileName);
DATA.Subscribe(Name, "CurrentWaferID", () => WaferManager.Instance.GetWafer(InstalledModule, 0).WaferID);
EV.Subscribe(new EventItem("Alarm", AlarmWIDLoadJobFail, $"{Name} WID Reader load job failed.", EventLevel.Alarm, EventType.EventUI_Notify));
EV.Subscribe(new EventItem("Alarm", AlarmWIDLostCommunication, $"{Name} WID Reader lost communication.", EventLevel.Alarm, EventType.EventUI_Notify));
EV.Subscribe(new EventItem("Alarm", AlarmWIDReadTimeout, $"{Name} WID Reader read laser mark timeout.", EventLevel.Alarm, EventType.EventUI_Notify));
}
private void BuildTransitionTable()
{
fsm = new StateMachine<OCRReaderBaseDevice>(Module + Name + ".OCRReaderReaderStateMachine", (int)OCRReaderStateEnum.Init, 50);
AnyStateTransition(OCRReaderMsg.Error, fError, OCRReaderStateEnum.Error);
AnyStateTransition(OCRReaderMsg.Reset, fStartReset, OCRReaderStateEnum.Resetting);
Transition(OCRReaderStateEnum.Resetting, OCRReaderMsg.ActionDone, fResetComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.Resetting, OCRReaderMsg.ResetComplete, fResetComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.Resetting, FSM_MSG.TIMER, fMonitorReset, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.Init, OCRReaderMsg.StartInit, fStartInit, OCRReaderStateEnum.Initializing);
Transition(OCRReaderStateEnum.Initializing, OCRReaderMsg.InitComplete, fInitComplete, OCRReaderStateEnum.Initializing);
Transition(OCRReaderStateEnum.Initializing, OCRReaderMsg.ActionDone, fInitComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.Initializing, FSM_MSG.TIMER, fMonitorInit, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.Error, OCRReaderMsg.Clear, fStartClear, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.Idle, OCRReaderMsg.SetParameter, fStartSetParameter, OCRReaderStateEnum.SetParameter);
Transition(OCRReaderStateEnum.SetParameter, OCRReaderMsg.SetComplete, fSetParameterComplete, OCRReaderStateEnum.SetParameter);
Transition(OCRReaderStateEnum.SetParameter, OCRReaderMsg.ActionDone, fSetParameterComplete, OCRReaderStateEnum.SetParameter);
Transition(OCRReaderStateEnum.Idle, OCRReaderMsg.ReadParameter, fStartReadParameter, OCRReaderStateEnum.ReadParameter);
Transition(OCRReaderStateEnum.ReadParameter, OCRReaderMsg.ReadParaComplete, fReadParameterComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.ReadParameter, OCRReaderMsg.ActionDone, fReadParameterComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.ReadParameter, FSM_MSG.TIMER, fMonitorReadParameter, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.Idle, OCRReaderMsg.ReadWaferID, fStartReadWaferID, OCRReaderStateEnum.ReadWaferID);
Transition(OCRReaderStateEnum.ReadWaferID, OCRReaderMsg.ReadCarrierIDComplete, fReadWaferIDComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.ReadWaferID, OCRReaderMsg.ActionDone, fReadWaferIDComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.ReadWaferID, FSM_MSG.TIMER, fMonitorReading, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.Idle, OCRReaderMsg.SavePicture, fStartSavePicture, OCRReaderStateEnum.SavingPicture);
Transition(OCRReaderStateEnum.SavingPicture, OCRReaderMsg.SavePictureComplete, fSavePictureComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.SavingPicture, OCRReaderMsg.ActionDone, fSavePictureComplete, OCRReaderStateEnum.Idle);
Transition(OCRReaderStateEnum.SavingPicture, FSM_MSG.TIMER, fMonitorSavingPicture, OCRReaderStateEnum.Idle);
}
protected virtual void OnWaferIDRead(string wid, string score, string readtime)
{
EV.PostInfoLog(Name, $"{Name} read laser mark successfully,ID:{wid},score:{score},read time:{readtime}.");
CheckToPostMessage((int)OCRReaderMsg.ReadCarrierIDComplete, null);
}
protected virtual bool fMonitorSavingPicture(object[] param)
{
return false;
}
protected virtual bool fMonitorReading(object[] param)
{
if (DateTime.Now - StartReadTime > TimeSpan.FromSeconds((double)TimeLimitForRead))
{
OnError(AlarmWIDReadTimeout);
}
return false;
}
protected virtual bool fMonitorReadParameter(object[] param)
{
return false;
}
protected virtual bool fSavePictureComplete(object[] param)
{
return true; ;
}
protected abstract bool fStartSavePicture(object[] param);
protected virtual bool fError(object[] param)
{
return true;
}
protected abstract bool fStartReset(object[] param);
protected virtual bool fResetComplete(object[] param)
{
return true;
}
protected virtual bool fMonitorReset(object[] param)
{
return true;
}
protected abstract bool fStartInit(object[] param);
protected virtual bool fInitComplete(object[] param)
{
return true;
}
protected virtual bool fMonitorInit(object[] param)
{
return true;
}
protected virtual bool fStartClear(object[] param)
{
return true;
}
protected abstract bool fStartSetParameter(object[] param);
protected virtual bool fSetParameterComplete(object[] param)
{
return true;
}
protected abstract bool fStartReadParameter(object[] param);
protected virtual bool fReadParameterComplete(object[] param)
{
return true;
}
protected abstract bool fStartReadWaferID(object[] param);
protected virtual bool fReadWaferIDComplete(object[] param)
{
return true;
}
public virtual bool ReadWaferID(string jobname,int lasermarkindex=0)
{
StartReadTime = DateTime.Now;
CurrentJobName = jobname;
return CheckToPostMessage((int)OCRReaderMsg.ReadWaferID, new object[] { jobname, lasermarkindex });
}
public abstract string[] GetJobFileList();
public bool SavePicture(string path = "",string filename = "")
{
return CheckToPostMessage((int)OCRReaderMsg.SavePicture, new object[] { "SavePicture", path, filename });
}
protected override bool Init()
{
return base.Init();
}
public virtual void Monitor()
{
return;
}
public virtual void Reset()
{
}
public virtual bool OnActionDone(object[] param)
{
IsBusy = false;
CheckToPostMessage((int)OCRReaderMsg.ActionDone, new object[] { "ActionDone" });
if (ActionDone != null)
ActionDone(true);
return true;
}
public void OnActionDone(bool result)
{
if (ActionDone != null)
ActionDone(result);
}
public virtual bool OnError(string errorMsg)
{
EV.PostAlarmLog(Module, $"{Name} occured error:{errorMsg}");
return CheckToPostMessage((int)OCRReaderMsg.Error, null);
}
public bool CheckToPostMessage(int msg, params object[] args)
{
if (!fsm.FindTransition(fsm.State, msg))
{
EV.PostWarningLog(Name, $"{Name} is in { (OCRReaderStateEnum)fsm.State} state,can not do {(OCRReaderMsg)msg}");
return false;
}
if ((OCRReaderMsg)msg == OCRReaderMsg.Reset || (OCRReaderMsg)msg == OCRReaderMsg.ReadParameter ||
(OCRReaderMsg)msg == OCRReaderMsg.ReadWaferID || (OCRReaderMsg)msg == OCRReaderMsg.SavePicture ||
(OCRReaderMsg)msg == OCRReaderMsg.SetParameter || (OCRReaderMsg)msg == OCRReaderMsg.StartInit)
IsBusy = true;
else
IsBusy = false;
fsm.PostMsg(msg, args);
return true;
}
public bool Check(int msg, out string reason, params object[] args)
{
if (!fsm.FindTransition(fsm.State, msg))
{
reason = String.Format("{0} is in {1} state,can not do {2}", Name, (OCRReaderStateEnum)fsm.State, (OCRReaderMsg)msg);
return false;
}
reason = "";
return true;
}
public virtual bool Error
{
get;
}
public string Module { get ; set ; }
public string Name { get; set ; }
public bool HasAlarm { get; set; }
}
public enum OCRReaderStateEnum
{
Undefined = 0,
Init,
Initializing,
Idle,
SetParameter,
ReadParameter,
ReadWaferID,
SavingPicture,
Error,
Resetting,
}
public enum OCRReaderMsg
{
Reset,
ResetComplete,
Clear,
StartInit,
InitComplete,
SetParameter,
SetComplete,
ReadParameter,
ReadParaComplete,
ReadWaferID,
ReadCarrierIDComplete,
SavePicture,
SavePictureComplete,
ActionDone,
Error,
}
}
@@ -0,0 +1,397 @@
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.SCCore;
using Aitex.Sorter.Common;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders
{
public class OcrReader : BaseDevice, IDevice
{
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 _handlers.Count > 0 || _foregroundHandler != null; }
}
public bool Error
{
get
{
return _commErr || ExeError || !_socket.IsConnected;
}
}
public bool SocketIsConnected { set; get; }
public bool ExeError { get; set; } = false;
public bool ReadLaserMaker { get; set; }
public string JobName { get; set; }
public string LaserMaker { get; set; }
public string LaserMark1 { get; set; }
public string LaserMark1Score { get; set; }
public string LaserMark1ReadTime { get; set; }
public string T7Code { 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; }
private static Object _locker = new Object();
private AsyncSocket _socket;
private IHandler _foregroundHandler = null; //current handler
private Queue<IHandler> _handlers = new Queue<IHandler>();
public const string delimiter = "\r\n";
private bool _commErr = false;
private string _addr;
//private bool _onlineInited;
public OcrReader(string module, string name, string display, string deviceId, string address)
: base(module, name, display, deviceId)
{
_addr = address;
_socket = new AsyncSocket(address, delimiter);
_socket.OnDataChanged += new AsyncSocket.MessageHandler(OnDataChanged);
_socket.OnErrorHappened += new AsyncSocket.ErrorHandler(OnErrorHandler);
Initalized = false;
}
public bool Initialize()
{
_socket.Connect(this._addr);
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", () => LaserMaker);
DATA.Subscribe(Name, "LaserMaker2", () => T7Code);
_handlers.Clear();
Online(false, out _);
Initalized = true;
return true;
}
public void Terminate()
{
}
//private int timerCount = 0;
public void Monitor()
{
//if(timerCount ++>50)
//{
// timerCount = 0;
// lock (_locker)
// {
// if (!Busy)
// {
// if (!_socket.IsHstConnected) _commErr = true;
// }
// }
//}
//if (!Busy)
//{
// lock (_locker)
// {
// SocketIsConnected = _socket.IsConnected;
// }
//}
}
public void Reset()
{
lock (_locker)
{
_foregroundHandler = null;
_handlers.Clear();
}
if (_commErr || !_socket.IsConnected)
{
_commErr = false;
_socket.Connect(this._addr);
}
ExeError = false;
Initalized = true;
}
#region Command
public bool Read(bool bLaserMaker, string jobName, out string reason)
{
_handlers.Clear();
if (string.IsNullOrEmpty(jobName))
{
reason = "Job is undefine.";
return false;
}
_handlers.Enqueue(new handler(new OnlineHandler(this), false)); //offline
_handlers.Enqueue(new handler(new LoadJobHandler(this), ConvetJobName(jobName))); //LoadJob
_handlers.Enqueue(new handler(new OnlineHandler(this), true)); //online
ReadOK = false;
ReadLaserMaker = bLaserMaker;
_handlers.Enqueue(new handler(new ReadHandler(this))); //Read
return execute(out reason);
}
public bool Read(bool bLaserMaker, out string reason)
{
_handlers.Clear();
string[] jobs = GetJobName(bLaserMaker);
if (jobs.Length == 0 || string.IsNullOrEmpty(jobs[0]))
{
reason = "Job is undefine";
return false;
}
string jobName = ConvetJobName(jobs[0]);
if (JobName != jobName)
{
_handlers.Enqueue(new handler(new OnlineHandler(this), false)); //offline
_handlers.Enqueue(new handler(new LoadJobHandler(this), jobName)); //LoadJob
_handlers.Enqueue(new handler(new OnlineHandler(this), true)); //online
}
_handlers.Enqueue(new handler(new ReadHandler(this))); //Read
ReadOK = false;
ReadLaserMaker = bLaserMaker;
return execute(out reason);
}
public bool ReadOnHostMode(bool bLaserMaker, string[] jobnames, out string reason)
{
_handlers.Clear();
ReadOK = false;
string[] jobs = jobnames;
if (jobs.Length == 0 || string.IsNullOrEmpty(jobs[0]))
{
reason = "Job is undefine";
return false;
}
_handlers.Enqueue(new handler(new OnlineHandler(this), false)); //offline
_handlers.Enqueue(new handler(new LoadJobHandler(this), ConvetJobName(jobnames[0]))); //LoadJob
_handlers.Enqueue(new handler(new OnlineHandler(this), true)); //online
_handlers.Enqueue(new handler(new ReadHandler(this))); //Read
ReadLaserMaker = bLaserMaker;
return execute(out reason);
}
public bool Read(out string reason)
{
reason = string.Empty;
return execute(new handler(new ReadHandler(this)), out reason);
}
public bool ReadJobName(out string reason)
{
reason = string.Empty;
return execute(new handler(new GetJobHandler(this)), out reason);
}
public bool Online(bool online, out string reason)
{
reason = string.Empty;
return execute(new handler(new OnlineHandler(this), online), out reason);
}
public bool LoadJob(string jobName, out string reason)
{
reason = string.Empty;
return execute(new handler(new LoadJobHandler(this), jobName), out reason);
}
#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(';');
}
private bool execute(IHandler handler, out string reason)
{
reason = string.Empty;
lock (_locker)
{
_handlers.Enqueue(handler);
if (_foregroundHandler == null) execute(out _);
}
return true;
}
private bool execute(out string reason)
{
reason = string.Empty;
lock (_locker)
{
if (_handlers.Count > 0)
{
ExeError = false;
_foregroundHandler = _handlers.Dequeue();
if (!_foregroundHandler.Execute(ref _socket))
{
reason = " communication failed, please recovery it.";
//LOG.Error(reason);
EV.PostMessage(Name, EventEnum.DefaultWarning, "【Reader】" + reason);
_handlers.Clear();
_foregroundHandler = null;
return false;
}
}
}
return true;
}
private void OnDataChanged(string package)
{
try
{
package = package.ToUpper();
string[] msgs = Regex.Split(package, delimiter);
foreach (string msg in msgs)
{
if (msg.Length > 0)
{
bool completed = false;
string resp = msg;
lock (_locker)
{
if (_foregroundHandler != null && _foregroundHandler.OnMessage(ref _socket, resp, out completed))
{
if (completed && !Error)
{
_foregroundHandler = null;
string reason = string.Empty;
execute(out reason);
}
else if(Error)
{
_handlers.Clear();
_foregroundHandler = null;
}
}
}
}
}
}
catch (ExcuteFailedException ex)
{
EV.PostMessage(DeviceID, EventEnum.DefaultWarning, ex.Message);
}
catch (InvalidPackageException ex)
{
EV.PostMessage(DeviceID, EventEnum.DefaultWarning, ex.Message);
}
catch (System.Exception ex)
{
EV.PostMessage(Name, EventEnum.DefaultWarning, "【Reader】has exception:" + ex.ToString());
}
}
public void OnLaskerMarkerRead()
{
}
private void OnErrorHandler(ErrorEventArgs args)
{
_commErr = true;
Initalized = false;
EV.PostMessage(Module, EventEnum.CommunicationError, Display, args.Reason);
//EV.PostMessage(Name, EventEnum.DefaultWarning, string.Format("{0} Communication failed,please check it.{1}", Name, args.Reason));
}
private string ConvetJobName(string name)
{
name = name.Substring(name.LastIndexOf("\\") + 1); //remove dir
name = name.Substring(0, name.LastIndexOf(".")); //remove expand
return name;
}
}
}