首次上传
This commit is contained in:
+283
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+73
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+243
@@ -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;
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+339
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user