首次上传

This commit is contained in:
hanqiangqiang
2026-06-15 10:56:30 +08:00
commit b0213b94d6
4160 changed files with 736101 additions and 0 deletions
@@ -0,0 +1,174 @@
using System;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using MECF.Framework.Common.Equipment;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.CarrierIdReaders
{
public class CarrierIdReader : BaseDevice, IDevice
{
public event Action<ModuleName, string, string> OnCarrierIdRead;
public event Action<ModuleName, string> OnCarrierIdReadFailed;
public event Action<ModuleName, string/*Name*/, string/*Code*/> OnCarrierIdWrite;
public event Action<ModuleName, string/*Name*/> OnCarrierIdWriteFailed;
private string _loadPort;
public CarrierIdReader(string module, string name, string display="", string deviceId="", string address="", string page="", string loadport="") :base(module, name, name, name)
{
Module = module;
Name = name;
_loadPort = loadport;
}
public virtual bool Initialize()
{
DEVICE.Register(String.Format("{0}.{1}", Name, "ReadRFID"), (out string reason, int time, object[] param) =>
{
bool ret = Read(out reason);
if (ret)
{
reason = string.Format("{0}{1}", Name, "Reading ID");
return true;
}
return false;
});
DEVICE.Register(String.Format("{0}.{1}", Name, "WriteRFID"), (out string reason, int time, object[] param) =>
{
string id = (string)param[0];
bool ret = Write(id, out reason);
if (ret)
{
reason = string.Format("{0}{1}", Name, "Writing ID");
return true;
}
return false;
});
DEVICE.Register(String.Format("{0}.{1}", Name, "ReadCarrierID"), (out string reason, int time, object[] param) =>
{
bool ret = Read(out reason);
if (ret)
{
reason = string.Format("{0}{1}", Name, "Reading carrier ID");
return true;
}
return false;
});
DEVICE.Register(String.Format("{0}.{1}", Name, "WriteCarrierID"), (out string reason, int time, object[] param) =>
{
string id = (string)param[0];
bool ret = Write(id, out reason);
if (ret)
{
reason = string.Format("{0}{1}", Name, "Writing carrier ID");
return true;
}
return false;
});
return true;
}
public virtual bool Read(out string reason)
{
reason = string.Empty;
return true;
}
public virtual bool Read(int startpage,int length,out string reason)
{
reason = string.Empty;
return true;
}
public virtual bool Write(string id, out string reason)
{
reason = string.Empty;
return true;
}
public virtual bool Write(int startpage, int length, out string reason)
{
reason = string.Empty;
return true;
}
public virtual bool SetParameter(string paraname,string paravalue,out string reason)
{
reason = string.Empty;
return true;
}
public virtual string ReadParameter(string paraname,out string reason)
{
reason = string.Empty;
return "";
}
public virtual void Monitor()
{
}
public virtual void Terminate()
{
}
public virtual void Reset()
{
}
public virtual bool Connect()
{
return true;
}
public bool SetManualScanCode(string code)
{
ReadOk(code);
EV.PostInfoLog("System", "Manually scan code");
return true;
}
public void ReadOk(string code)
{
if (OnCarrierIdRead != null)
{
OnCarrierIdRead((ModuleName)Enum.Parse(typeof(ModuleName), string.IsNullOrEmpty(Module) ? _loadPort : Module), Name, code);
}
}
public void ReadFailed()
{
if (OnCarrierIdReadFailed != null)
{
OnCarrierIdReadFailed((ModuleName)Enum.Parse(typeof(ModuleName), string.IsNullOrEmpty(Module) ? _loadPort : Module), Name);
}
}
public void WriteOk(string code)
{
if (OnCarrierIdWrite != null)
{
OnCarrierIdWrite((ModuleName)Enum.Parse(typeof(ModuleName), string.IsNullOrEmpty(Module) ? _loadPort : Module), Name, code);
}
}
public void WriteFailed()
{
if (OnCarrierIdWriteFailed != null)
{
OnCarrierIdWriteFailed((ModuleName)Enum.Parse(typeof(ModuleName), string.IsNullOrEmpty(Module) ? _loadPort : Module), Name);
}
}
}
}
@@ -0,0 +1,244 @@
using System.Threading;
using System.Threading.Tasks;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.CarrierIdReaders.OmronBarcode
{
public class OmronBarcodeReader : CarrierIdReader
{
private AsyncSerialPort _port;
private string _scannerName;
//private int _scan;
private int _timeout;
private int _retryTime;
DeviceTimer _scanTimer = new DeviceTimer();
private bool _cmdScan;
private bool _cmdStopScan;
//private bool _msgError;
private bool _msgScanned;
public string _scanResult;
private object _locker = new object();
private bool _isScanning;
public OmronBarcodeReader(string module, string scannerName, string portName, int timeout, int retryTime):base(module, scannerName)
{
Module = module;
Name = scannerName;
_scannerName = scannerName;
_timeout = timeout*1000;
_retryTime = retryTime;
_port = new AsyncSerialPort(portName, 9600, 8 );
_port.EnableLog = true;
_port.OnDataChanged += _port_OnDataReceived;
_port.OnErrorHappened += _port_OnErrorHappened;
}
public override bool Initialize()
{
Task.Factory.StartNew(() =>
{
int count = SC.ContainsItem("System.ComPortRetryCount") ? SC.GetValue<int>("System.ComPortRetryCount") : 50;
int sleep = SC.ContainsItem("System.ComPortRetryDelayTime") ? SC.GetValue<int>("System.ComPortRetryDelayTime") : 1;
if (sleep <= 0 || sleep > 10)
sleep = 2;
int retry = 0;
do
{
if (_port.Open())
{
//LOG.Write($"Connected with {Module}.{Name} .");
EV.PostInfoLog(Module, $"Connected with {Module}.{Name} .");
break;
}
if (count>0 && retry++ > count)
{
LOG.Write($"Retry connect {Module}.{Name} stop retry.");
EV.PostAlarmLog(Module, $"Can't connect to {Module}.{Name} .");
break;
}
{
Thread.Sleep(sleep * 1000);
LOG.Write($"Retry connect {Module}.{Name} for the {retry + 1} time.");
}
} while (true);
});
// RetryInstance.Instance().Execute<bool>(
// ()=> _port.Open(),
// SC.GetValue<int>("System.ComPortRetryDelayTime"),
// SC.GetValue<int>("System.ComPortRetryCount"),
// true
// );
return true;
}
public override bool Read(out string reason)
{
Scan();
reason = "";
return true;
}
private bool InvokeScan(string arg1, object[] arg2)
{
Scan();
return true;
}
private bool InvokeStopScan(string arg1, object[] arg2)
{
StopScan();
return true;
}
public void Scan()
{
if (!_port.IsOpen())
{
EV.PostWarningLog(Module, _scannerName + " not open, can not scan");
return;
}
lock (_locker)
{
if (!_isScanning)
{
_scanTimer.Start(0);
_cmdScan = true;
_cmdStopScan = false;
}
}
}
public void StopScan()
{
if (!_port.IsOpen())
{
EV.PostWarningLog(Module, _scannerName + " not open, can not stop scan");
return;
}
lock (_locker)
{
if (_isScanning)
{
_cmdScan = false;
_cmdStopScan = true;
}
}
}
private void _port_OnErrorHappened(string obj)
{
EV.PostWarningLog(Module, _scannerName + " error, " + obj);
}
private void _port_OnDataReceived(string obj)
{
lock (_locker)
{
if (_isScanning)
{
_scanResult = obj.Replace("\r","");
_msgScanned = true;
}
}
}
public override void Monitor()
{
lock (_locker)
{
if (_isScanning)
{
if (_cmdStopScan)
{
_cmdStopScan = false;
_isScanning = false;
PerformStopTriggerScan();
}
else
{
if (_msgScanned)
{
_msgScanned = false;
_isScanning = false;
ReadOk(_scanResult);
}
else
{
if (_scanTimer.GetElapseTime() > _timeout)
{
_isScanning = false;
EV.PostWarningLog(Module, _scannerName + " error, timeout");
ReadFailed();
}
}
}
}
else
{
if (_cmdScan)
{
_cmdScan = false;
_isScanning = true;
PerformTriggerScan();
_scanTimer.Start(0);
}
}
}
}
public override void Terminate()
{
_port.Close();
}
public override void Reset()
{
if (!_port.IsOpen())
{
if (_port.Open())
{
EV.PostMessage("System", EventEnum.GeneralInfo, _scannerName + " opened, ");
}
}
}
private void PerformTriggerScan()
{
_port.Write(new byte[] { 0x1B, 0x5A, 0x0D });
}
private void PerformStopTriggerScan()
{
//_port.Write(new byte[] { 22, 85, 13 });
}
}
}
@@ -0,0 +1,270 @@
using System;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.SCCore;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.CarrierIdReaders.OmronRFID
{
public interface IRFIDMsg
{
string DeviceID { get; set; }
string package(params object[] args);
/// </summary>
/// return value, completed
/// <param name="type"></param>
/// <param name="cmd"></param>
/// <returns></returns>
bool unpackage(string msg);
}
public class handler<T> : IHandler where T : IRFIDMsg, new()
{
public int ID { get; set; }
public int Unit { get; set; }
public bool IsBackground { get; set; }
private static int retry_time = 3;
private int retry_count = retry_time;
private T _imp = new T();
private object[] _objs = null;
public handler(string deviceID, params object[] objs)
{
_imp.DeviceID = deviceID;
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)));
}
/// <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();
string type = msg.Substring(0, 2);
if (!type.Equals("00")) //0: command failed
{
/*
if (retry_count-- <= 0)
{
string warning = string.Format("retry over {0} times", retry_time);
LOG.Warning(warning);
throw (new ExcuteFailedException(warning));
}
*/
string warning = string.Format("excute failed. cause is {0}.", getErrMsg(type));
LOG.Warning(warning);
throw (new ExcuteFailedException(warning));
//port.Write(string.Format("{0}\r", _imp.package(this._objs)));
//return true;
}
msg = msg.Substring(2, msg.Length - 2);
completed = _imp.unpackage(msg);
return true;
}
catch (ExcuteFailedException e)
{
throw (e);
}
catch (Exception ex)
{
LOG.Write(ex);
throw (new InvalidPackageException(message));
}
}
private string getErrMsg(string error)
{
string msg = "";
switch (error)
{
case "14":
msg = "Format error There is a mistake in the command format";
break;
case "70":
msg = "Communications error Noise or another hindrance occurs during communications with an ID Tag, and communications cannot be completed normally.";
break;
case "71":
msg = "Verification error Correct data cannot be written to an ID Tag";
break;
case "72":
msg = "No Tag error Either there is no ID Tag in front of the CIDRW Head, or the CIDRW Head is unable to detect the ID Tag due to environmental factors";
break;
case "7B":
msg = "Outside write area error A write operation was not completed normally because the ID Tag was in an area in which the ID Tag could be read but not written";
break;
case "7E":
msg = "ID system error (1) The ID Tag is in a status where it cannot execute command processing";
break;
case "7F":
msg = "ID system error (2) An inapplicable ID Tag has been used";
break;
case "9A":
msg = "Hardware error in CPU An error occurred when writing to EEPROM.";
break;
}
return msg;
}
}
public class ReadHandler : IRFIDMsg //common move
{
public string DeviceID { get; set; }
public ReadHandler()
{
}
public string package(params object[] args)
{
string page = (string)args[0];
return string.Format("{0}{1}", "0100", page);
}
public bool unpackage(string msg)
{
OmronRfidReader device = DEVICE.GetDevice<OmronRfidReader>(DeviceID);
string asciiValue = HEX2ASCII(msg.Substring(0, Math.Min(256, msg.Length))).Trim('\0');
if (asciiValue.IndexOf('\0') != -1)
{
asciiValue = asciiValue.Substring(0, asciiValue.IndexOf('\0'));
}
if (SC.ContainsItem("LoadPort.CarrierIdNeedTrimSpace") &&
SC.GetValue<bool>("LoadPort.CarrierIdNeedTrimSpace"))
{
asciiValue = asciiValue.Trim();
}
device.SetCarrierIdReadResult(asciiValue);
return true;
}
public string HEX2ASCII(string hex)
{
string res = String.Empty;
try
{
for (int a = 0; a < hex.Length; a = a + 2)
{
string Char2Convert = hex.Substring(a, 2);
int n = Convert.ToInt32(Char2Convert, 16);
char c = (char)n;
res += c.ToString();
}
}
catch (Exception e)
{
LOG.Write(e);
}
return res;
}
}
public class WriteHandler : IRFIDMsg //common move
{
public string DeviceID { get; set; }
public string Rfid { get; set; }
public WriteHandler()
{
}
public string package(params object[] args)
{
string page = (string)args[0];
Rfid = (string)args[1];
//Rfid = ASCII2HEX((string)args[1]);
return string.Format("{0}{1}{2}", "0200", page, ASCII2HEX((string)args[1]).ToUpper());
}
public string ASCII2HEX(string src)
{
while (src.Length < 128)
{
src = '\0' + src;
}
if (src.Length > 128)
{
src = src.Substring(0, 128);
LOG.Write("RFID support max 128 characters");
}
string res = String.Empty;
try
{
char[] charValues = src.ToCharArray();
string hexOutput = "";
foreach (char _eachChar in charValues)
{
// Get the integral value of the character.
int value = Convert.ToInt32(_eachChar);
// Convert the decimal value to a hexadecimal value in string form.
hexOutput += String.Format("{0:X2}", value);
// to make output as your eg
// hexOutput +=" "+ String.Format("{0:X}", value);
}
return hexOutput;
}
catch (Exception e)
{
LOG.Write(e);
}
return res;
}
public bool unpackage(string msg)
{
OmronRfidReader device = DEVICE.GetDevice<OmronRfidReader>(DeviceID);
device.SetCarrierIdReadResult(Rfid);
return true;
}
}
}
@@ -0,0 +1,286 @@
using System;
using System.Text.RegularExpressions;
using Aitex.Core.Common.DeviceData;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.Util;
using Aitex.Sorter.Common;
using MECF.Framework.Common.Communications;
using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.CarrierIdReaders.OmronRFID
{
public class OmronRfidReader : CarrierIdReader, IConnection
{
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
{
get { return _foregroundHandler != null; }
}
public bool Error
{
get{return _commErr;}
}
public bool Communication
{
get
{
return _socket == null ? !_commErr : !_commErr && _socket.IsConnected;
}
}
private string _foupId;
public string FoupID
{
get
{
return _foupId;
}
set
{
//FAManager.Instance.ChangeFoupId(Name, value);
_foupId = value;
}
}
public string LoadPortName
{
get
{
return _loadPort;
}
}
private static Object _locker = new Object();
private AsyncSocket _socket;
private IHandler _foregroundHandler = null; //current handler
public const string delimiter = "\r";
private bool _commErr = false;
private string page;
private string _addr;
private string _loadPort ;
public OmronRfidReader(string module, string name, string display, string deviceId, string address, string page, string loadport )
: base(module, name, display, deviceId, address, page, loadport)
{
this.page = page;
_addr = address;
_loadPort = loadport ;
_socket = new AsyncSocket(address);
_socket.OnDataChanged += new AsyncSocket.MessageHandler(OnDataChanged);
_socket.OnErrorHappened += new AsyncSocket.ErrorHandler(OnErrorHandler);
Initalized = false;
}
public override bool Initialize()
{
ConnectionManager.Instance.Subscribe(Name, this);
_socket.Connect(this._addr);
DATA.Subscribe(Name, "RIDReaderBusy", () => Busy);
DATA.Subscribe(Name, "FoupID", () => FoupID);
DATA.Subscribe(Name, "RIDReaderState", () => State);
DATA.Subscribe(Name, "CommunicationStatus", () => IsConnected);
DATA.Subscribe(string.Format("Device.{0}.{1}", Module , Name),
() =>
{
AITRfidReaderData data = new AITRfidReaderData()
{
DeviceName = Name,
DeviceSchematicId = DeviceID,
DisplayName = Display,
IsBusy = Busy,
IsError = Error,
IsInitalized = Initalized,
State = State.ToString(),
};
return data;
}, SubscriptionAttribute.FLAG.IgnoreSaveDB);
OP.Subscribe($"{Name}.Reconnect", (string cmd, object[] args) => Connect());
Initalized = true;
return true;
}
public override void Reset()
{
base.Reset();
lock (_locker)
{
_foregroundHandler = null;
}
if (_commErr)
{
Connect();
}
}
public string Address
{
get { return _addr; }
}
public bool IsConnected
{
get { return _socket.IsConnected; }
}
public override bool Connect()
{
_commErr = false;
_socket.Connect(this._addr);
return true;
}
public bool Disconnect()
{
return true;
}
#region Command
public override bool Read(out string reason)
{
reason = string.Empty;
return execute(new handler<ReadHandler>(this.DeviceID, this.page), out reason);
}
public override bool Write(string id, out string reason)
{
reason = string.Empty;
return execute(new handler<WriteHandler>(this.DeviceID, this.page,id), out reason);
}
#endregion
private bool execute(IHandler handler, out string reason)
{
reason = string.Empty;
lock (_locker)
{
if (_foregroundHandler != null)
{
reason = string.Format("Busy,can not execute");
return false;
}
if(!handler.Execute(ref _socket))
{
reason = "Communication error, please re-connect";
return false;
}
_foregroundHandler = handler;
}
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))
{
_foregroundHandler = null;
}
}
}
}
}
catch (ExcuteFailedException ex)
{
EV.PostMessage(DeviceID, EventEnum.DefaultWarning, ex.Message);
_foregroundHandler = null;
}
catch (InvalidPackageException ex)
{
EV.PostMessage(DeviceID, EventEnum.DefaultWarning, ex.Message);
_foregroundHandler = null;
}
catch (System.Exception ex)
{
EV.PostMessage(Name, EventEnum.DefaultWarning, "【RFID】has exception:" + ex.ToString());
}
}
private void OnErrorHandler(ErrorEventArgs args)
{
ReadFailed();
_commErr = true;
Initalized = false;
EV.PostMessage(Module, EventEnum.CommunicationError, Display, args.Reason);
}
public void SetCarrierIdReadResult(string carrierId)
{
FoupID = carrierId;
ReadOk( carrierId);
}
}
}