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,403 @@
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using MECF.Framework.Common.Communications;
using MvCameraControl;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using VM.PlatformSDKCS;
using CameraDevice = MvCameraControl.IDevice;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.HikVision
{
public class HikGigeCamera : BaseDevice, IConnection, Aitex.Core.RT.Device.IDevice
{
IDeviceInfo deviceInfo = null;
private CameraDevice device;
// ch:枚举的相机类型 | en:TLayerType for enumerate devices
readonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice
| DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;
private List<IDeviceInfo> deviceInfoList = new List<IDeviceInfo>();
private string _grabName;
private bool _isSaveLocal = false;
Thread receiveThread = null; // ch:接收图像线程 | en: Receive image thread
public HikGigeCamera(string module, string scRoot, string name) : base(module, name, name, name)
{
IsConnected = false;
receiveThread = new Thread(ReceiveThreadProcess);
}
public string Address { get; private set; }
public string ImageFilePath { get; private set; }
public bool IsConnected { get; private set; } = false;
public bool IsGrabbing { get; private set; } = false;
public string Message { get; private set; }
public ImageBaseData ImageData { get; private set; }
public byte[] CamBitmap { get; private set; }
public bool Connect()
{
return true;
}
public bool Disconnect()
{
return true;
}
public void CamInitialize()
{
if (IsConnected)
{
return;
}
// ch: 初始化 SDK | en: Initialize SDK
SDKSystem.Initialize();
// ch: 枚举设备 | en: Enum Device List
RefreshDeviceList();
if (deviceInfoList.Count == 0)
{
Message = "No Camera be found";
return;
}
string sAddress = SC.GetStringValue($"{Name}.Address");
Address = sAddress;
var dinfo = deviceInfoList.Find(i=>i.SerialNumber == Address);
if (dinfo == null)
{
Message = $"Can no find Camera{Address}";
return;
}
// 打开摄像头(设备索引 0)
try
{
// ch:打开设备 | en:Open device
device = DeviceFactory.CreateDevice(dinfo);
}
catch (Exception ex)
{
Message = $"Create {Address} failed";
return;
}
int result = device.Open();
if (result != MvError.MV_OK)
{
ShowErrorMsg("Open Device fail!", result);
return;
}
//ch: 判断是否为gige设备 | en: Determine whether it is a GigE device
if (device is IGigEDevice)
{
//ch: 转换为gigE设备 | en: Convert to Gige device
IGigEDevice gigEDevice = device as IGigEDevice;
// ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
int optionPacketSize;
result = gigEDevice.GetOptimalPacketSize(out optionPacketSize);
if (result != MvError.MV_OK)
{
ShowErrorMsg("Warning: Get Packet Size failed!", result);
}
else
{
result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
if (result != MvError.MV_OK)
{
ShowErrorMsg("Warning: Set Packet Size failed!", result);
}
}
}
ImageFilePath = SC.SafeGetStringValue($"{Name}.ImageFilePath", "D:\\VMImage");
IsConnected = true;
}
public bool Initialize()
{
DATA.Subscribe($"{Module}.{Name}.IsConnected", () => this.IsConnected);
DATA.Subscribe($"{Module}.{Name}.Address", () => this.Address);
DATA.Subscribe($"{Module}.{Name}.Message", () => this.Message);
DATA.Subscribe($"{Module}.{Name}.CamBitmap", () => this.CamBitmap);
//转至运行模式
OP.Subscribe($"{Module}.{Name}.Grab", (cmd, param) =>
{
Grab((string)param[0]);
return true;
});
OP.Subscribe($"{Module}.{Name}.Grabbing", (cmd, param) =>
{
Grabbing();
return true;
});
OP.Subscribe($"{Module}.{Name}.Stop", (cmd, param) =>
{
Stop();
return true;
});
//CamInitialize();
return true;
}
public void Reset()
{
;
}
public void Terminate()
{
Stop();
SDKSystem.Finalize();
}
private void RefreshDeviceList()
{
// ch:创建设备列表 | en:Create Device List
int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList);
if (nRet != MvError.MV_OK)
{
ShowErrorMsg("Enumerate devices fail!", nRet);
return;
}
}
/// <summary>
/// ch:显示错误信息 | en:Show error message
/// </summary>
private void ShowErrorMsg(string message, int errorCode)
{
string errorMsg;
if (errorCode == 0)
{
errorMsg = message;
}
else
{
errorMsg = message + ": Error =" + String.Format("{0:X}", errorCode);
}
switch (errorCode)
{
case MvError.MV_E_HANDLE: errorMsg += " Error or invalid handle "; break;
case MvError.MV_E_SUPPORT: errorMsg += " Not supported function "; break;
case MvError.MV_E_BUFOVER: errorMsg += " Cache is full "; break;
case MvError.MV_E_CALLORDER: errorMsg += " Function calling order error "; break;
case MvError.MV_E_PARAMETER: errorMsg += " Incorrect parameter "; break;
case MvError.MV_E_RESOURCE: errorMsg += " Applying resource failed "; break;
case MvError.MV_E_NODATA: errorMsg += " No data "; break;
case MvError.MV_E_PRECONDITION: errorMsg += " Precondition error, or running environment changed "; break;
case MvError.MV_E_VERSION: errorMsg += " Version mismatches "; break;
case MvError.MV_E_NOENOUGH_BUF: errorMsg += " Insufficient memory "; break;
case MvError.MV_E_UNKNOW: errorMsg += " Unknown error "; break;
case MvError.MV_E_GC_GENERIC: errorMsg += " General error "; break;
case MvError.MV_E_GC_ACCESS: errorMsg += " Node accessing condition error "; break;
case MvError.MV_E_ACCESS_DENIED: errorMsg += " No permission "; break;
case MvError.MV_E_BUSY: errorMsg += " Device is busy, or network disconnected "; break;
case MvError.MV_E_NETER: errorMsg += " Network error "; break;
}
EV.PostWarningLog(Module,errorMsg);
}
public void Grab(string name)
{
CamInitialize();
if (IsConnected)
{
_grabName = name;
if (IsGrabbing)
{
_isSaveLocal = true;
return;
}
device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
device.Parameters.SetEnumValueByString("TriggerMode", "On");
device.Parameters.SetEnumValueByString("TriggerSource", "Software");
var result = device.StreamGrabber.StartGrabbing();
if (MvError.MV_OK != result)
{
ShowErrorMsg("Start grabbing Fail!", result);
return;
}
// ch:触发命令 | en:Trigger command
var result2 = device.Parameters.SetCommandValue("TriggerSoftware");
if (result2 != MvError.MV_OK)
{
ShowErrorMsg("Trigger Software Fail!", result2);
return;
}
GetImage(device,true);
Message = "Shot one picture";
Stop();
}
}
public void Grabbing()
{
CamInitialize();
if (IsConnected)
{
if (!IsGrabbing)
{
// ch:设置采集连续模式 | en:Set Continues Aquisition Mode
device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
device.Parameters.SetEnumValueByString("TriggerMode", "Off");
try
{
// ch:标志位置位true | en:Set position bit true
IsGrabbing = true;
receiveThread = new Thread(ReceiveThreadProcess);
receiveThread.Start();
}
catch (Exception ex)
{
ShowErrorMsg("Start grabbing thread Fail!", 0);
return;
}
// ch:开始采集 | en:Start Grabbing
var result = device.StreamGrabber.StartGrabbing();
if (result != MvError.MV_OK)
{
IsGrabbing = false;
receiveThread.Join();
ShowErrorMsg("Start Grabbing Fail!", result);
return;
}
Message = "Grabbing pictures";
}
else
{
Stop();
}
}
}
public void ReceiveThreadProcess()
{
while (IsGrabbing)
{
GetImage(device,_isSaveLocal);
}
}
/// <summary>
/// 抓取图像;单次抓取时需要存图
/// </summary>
/// <param name="cam"></param>
/// <param name="isSaveLocal"></param>
private void GetImage(CameraDevice cam,bool isSaveLocal)
{
IFrameOut frameOut = null;
int result = MvError.MV_OK;
result = device.StreamGrabber.GetImageBuffer(1000, out frameOut);
if (result == MvError.MV_OK)
{
if(isSaveLocal) //截图模式,原始图片进行保存
{
var folderPath = ImageFilePath + DateTime.Now.ToString("yyyy-MM-dd");
if (!Directory.Exists(folderPath))
{
// 创建文件夹
Directory.CreateDirectory(folderPath);
Console.WriteLine($"Folder '{folderPath}' created successfully.");
}
var info = new ImageFormatInfo() { FormatType = ImageFormatType.Jpeg, JpegQuality = 80 };
var f = folderPath + $"\\{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-FFF")}_{_grabName}.{info.FormatType}";
device.ImageSaver.SaveImageToFile(f, frameOut.Image, info, CFAMethod.Equilibrated);
EV.PostInfoLog(Module, $"Hik CCD check,Save image in {f}");
ImageData = ConvertImage(frameOut.Image); //注意克隆
_isSaveLocal = false;
}
CamBitmap = BitmapToBytes(frameOut.Image.ToBitmap());
device.StreamGrabber.FreeImageBuffer(frameOut);
}
}
public byte[] BitmapToBytes(Bitmap bitmap)
{
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Bmp); // 推荐Bmp格式保证数据完整性:ml-citation{ref="1,5" data="citationList"}
return ms.ToArray(); // 比GetBuffer()更精确获取有效数据:ml-citation{ref="12" data="citationList"}
}
}
public void Stop()
{
IsGrabbing = false;
if (receiveThread.IsAlive)
{
receiveThread.Join();
}
Message = "Standby";
if (device ==null)
{
return;
}
int result = device.StreamGrabber.StopGrabbing();
if (result != MvError.MV_OK)
{
ShowErrorMsg("Stop Grabbing Fail!", result);
}
result = device.Close();
if (MvError.MV_OK != result)
{
ShowErrorMsg("Close device failed", result);
}
// ch:销毁设备 | en:Destroy device
device.Dispose();
device = null;
IsConnected = false;
}
private ImageBaseData ConvertImage(IImage img)
{
return new ImageBaseData((byte[])img.PixelData.Clone(), (uint)img.ImageSize, (int)img.Width, (int)img.Height, 17301505);
}
}
}
@@ -0,0 +1,132 @@
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using Aitex.Core.RT.SCCore;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.HikVision
{
public class HikMV : BaseDevice, IDevice, IConnection
{
private readonly HikMVConnection _connection;
private readonly object _locker = new();
private int _retryCount = 0;
private PeriodicJob _thread;
private const int _maxRetryCount = 50;
private readonly R_TRIG _trigConnErr = new();
public bool IsConnected => _connection is { IsConnected: true };
public string Address => _connection.Address;
public bool IsResponded { get; set; }
public bool IsProcessing { get; set; } = false;
public string RawMessage { get; set; } = "";
public double[] Data { get; set; }
public HikMV(string module, string scRoot, string name) : base(module, name, name, name)
{
var ip = SC.SafeGetStringValue($"{name}.IP", "127.0.0.1");
var port = SC.GetValue($"{name}.Port", 9000);
_connection = new HikMVConnection($"{ip}:{port}","\r\n");
}
public bool Initialize()
{
DATA.Subscribe($"{UniqueName}.{nameof(RawMessage)}", () => RawMessage);
OP.Subscribe($"{UniqueName}.Execute", (string cmd, object[] args) => Execute((string)args[0]));
if (!_connection.Connect())
{
_trigConnErr.CLK = true;
if(_trigConnErr.Q)
EV.PostAlarmLog(Module, $"{Name}({Address}) Connect Failed");
}
_thread = new PeriodicJob(100, OnTimer, $"{UniqueName} MonitorHandler", true);
return true;
}
private bool OnTimer()
{
var result = _connection.MonitorTimeout();
if (result != null)
{
RawMessage = $"{result.SendText.Replace("\r", "").Replace("\n", "")} no Response";
IsProcessing = false;
Disconnect();
}
if (!_connection.IsConnected)
{
if (_retryCount < _maxRetryCount)
{
_retryCount++;
}
else
{
_retryCount = 0;
lock (_locker)
{
if (!_connection.Connect())
{
// 连接失败
_trigConnErr.CLK = true;
if(_trigConnErr.Q)
EV.PostAlarmLog(Module, $"{Name}({Address}) Connect Failed");
}
else
{
// 连接成功
_trigConnErr.CLK = false;
}
}
}
}
return true;
}
public bool Execute(string command)
{
IsResponded = false;
IsProcessing = true;
RawMessage = "";
var handler = new HikMVHandler(this, command+"\r\n");
handler.AckTimeout = TimeSpan.FromSeconds(5.0);
_connection.Execute(handler);
return true;
}
public void Reset()
{
_trigConnErr.RST = true;
IsProcessing = false;
IsResponded = false;
RawMessage = "";
}
public void Terminate()
{
Disconnect();
_trigConnErr.RST = true;
}
public bool Connect()
{
return _connection.Connect();
}
public bool Disconnect()
{
return _connection.Disconnect();
}
}
}
@@ -0,0 +1,74 @@
using Aitex.Core.RT.Log;
using MECF.Framework.Common.Communications;
using System;
using System.Linq;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.HikVision
{
public class HikMessage: MessageBase
{
public string RawMessage { get; set; } = "";
public double[] paras;
public bool Result { get; set; } = false;
}
public class HikMVConnection : TCPPortConnectionBase
{
public HikMVConnection(string address, string newline = "\r", bool isAsciiMode = true) : base(address, newline, isAsciiMode)
{
}
public override bool SendMessage(string message)
{
return base.SendMessage(message);
}
protected override MessageBase ParseResponse(string rawText)
{
HikMessage msg = new HikMessage();
msg.RawMessage = rawText;
if (msg.RawMessage.Length == 0)
{
LOG.Error($"empty response");
msg.IsFormatError = true;
return msg;
}
else if (msg.RawMessage.StartsWith("OK")&& msg.RawMessage.Contains(':'))
{
try
{
var m = msg.RawMessage.Split(':');
var values = m[1].Split(',');
msg.paras = new double[values.Length];
for (int i = 0; i < values.Length; i++)
{
msg.paras[i]= Convert.ToDouble(values[i]);
}
msg.Result = true;
}
catch (Exception)
{
LOG.Error($"Convert Response Failed From Camera{Address}({msg.RawMessage})");
msg.RawMessage = $"Convert Response Failed From Camera{Address}({msg.RawMessage})";
}
}
else if (msg.RawMessage.StartsWith("NG"))
{
LOG.Error($"NG Response From Camera{Address}");
}
else
{
LOG.Error($"Unknown Response From Camera{Address}({msg.RawMessage})");
msg.RawMessage = $"Unknown Response From Camera{Address}({msg.RawMessage})";
}
msg.IsResponse = true;
msg.IsAck = true;
return msg;
}
}
}
@@ -0,0 +1,81 @@
using MECF.Framework.Common.Communications;
using System;
using System.Text.RegularExpressions;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.HikVision
{
public class HikMVHandler : HandlerBase
{
public HikMV Device { get; }
public string _command;
public HikMVHandler(HikMV device, string command): base(command)
{
Device = device;
_command = command;
Name = command;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
HikMessage response = msg as HikMessage;
ResponseMessage = msg;
//ParseResult(response.RawMessage);
if (response.IsAck)
{
SetState(EnumHandlerState.Acked);
if (msg.IsError)
{
//Device.NoteError($"Command '{_command}' Error: {response.Data}:{ErrorString(response.ErrorText)}");
}
else
{
SetState(EnumHandlerState.Completed);
handled = true;
Device.Data = response.paras;
Device.RawMessage = response.RawMessage;
Device.IsResponded = response.Result;
Device.IsProcessing = false;
return true;
}
}
handled = false;
return false;
}
private void ParseResult(string rawMessage)
{
rawMessage = rawMessage.Replace("\r", "").Replace("\n", "");
// NG
// OK_1:xxxx,yyyy\r\n
var pattern = @"^OK_(\d+):(-?\d+\.\d+|\d+),(-?\d+\.\d+|\d+)$";
var pattern2 = @"^OK_(\d+):(-?\d+\.\d+|\d+)$";
if (rawMessage.StartsWith("OK"))
{
var m = Regex.Match(rawMessage, pattern);
if (m.Success)
{
var posX = Convert.ToDouble(m.Groups[2].Value);
var posY = Convert.ToDouble(m.Groups[3].Value);
Device.Data = [posX, posY];
Device.RawMessage = rawMessage;
}
else
{
var m2 = Regex.Match(rawMessage, pattern);
if (m2.Success)
{
var posR = Convert.ToDouble(m.Groups[2].Value);
Device.Data = [posR];
Device.RawMessage = rawMessage;
}
}
}
}
}
}
@@ -0,0 +1,518 @@
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using CalculatorModuleCs;
using GlobalVariableModuleCs;
using IfModuleCs;
using ImageSourceModuleCs;
using IMVSCircleFitModuCs;
using IMVSLineFindModuCs;
using SaveImageCs;
using VM.Core;
using VM.PlatformSDKCS;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.HikVision
{
public class HikVisionMasterSDK : BaseDevice, IDevice
{
string _sol = "";
private PeriodicJob _thread;
private bool _isInit = false;
public HikVisionMasterSDK(string module, string scRoot, string name,bool isInit) : base(module, name, name, name)
{
IsProcessing = false;
_sol = SC.SafeGetStringValue($"{Name}.VMSolutionAddress", "D:\\VMSolution\\123.sol");
_thread = new PeriodicJob(200, OnTimer, $"{Module}.{Name} MonitorHandler", true);
_isInit = isInit;
}
public string Command { get; set; } = "";
/// <summary>
/// 标记当前执行的程序流程
/// </summary>
public string ProjectName { get; set; } = "";
public bool ModuleStatus { get; set; } = false;
public bool Result { get; set; } = false;
public double[] SampleCircle { get; set; } = new double[3];
public double[] CurrentCircle { get; set; } = new double[3];
public double[] SampleData { get; set; }
public double[] SampleData2 { get; set; }
public double Distance { get; set; } = 0;
public double Tolerance { get; set; } = 1;
public double Tolerance2 { get; set; } = 1;
public bool IsProcessing { get; set; } = false;
public bool LoadFile { get; set; } = false;
public byte[] OutputImage { get; set; } = null;
public byte[] PreviewImage1 { get; set; } = null;
public byte[] PreviewImage2 { get; set; } = null;
public byte[] PreviewImage3 { get; set; } = null;
public byte[] PreviewImage4 { get; set; } = null;
public string LocalImageFilePath { get; set; }
public bool Initialize()
{
LocalImageFilePath = SC.SafeGetStringValue($"{Name}.{nameof(LocalImageFilePath)}", "D:\\VMImage\\Input");
if (!Directory.Exists(LocalImageFilePath))
{
// 创建文件夹
Directory.CreateDirectory(LocalImageFilePath);
Console.WriteLine($"Folder '{LocalImageFilePath}' created successfully.");
}
string s = SC.SafeGetStringValue($"{Name}.SampleData", "100,200,200,300,300,100"); //隐藏项
string s2 = SC.SafeGetStringValue($"{Name}.SampleData2", "100,200,200,300,300,100"); //隐藏项
SampleData = ConvertSample(s);
SampleData2 = ConvertSample(s2);
if (SampleData == null || SampleData2 == null)
{
EV.PostAlarmLog(Module, $"SampleData failed");
return true;
}
Tolerance = SC.GetValue<double>($"{Name}.{nameof(Tolerance)}", 1);
SC.RegisterValueChangedCallback($"{Name}.{nameof(Tolerance)}", (newvalue) => { Tolerance = (double)newvalue; LoadSolution(); }); //实时修改
Tolerance2 = SC.GetValue<double>($"{Name}.{nameof(Tolerance2)}", 1);
SC.RegisterValueChangedCallback($"{Name}.{nameof(Tolerance2)}", (newvalue) => { Tolerance2 = (double)newvalue; LoadSolution(); }); //实时修改
DATA.Subscribe($"{Module}.{Name}.{nameof(ProjectName)}", () => ProjectName);
DATA.Subscribe($"{Module}.{Name}.{nameof(ModuleStatus)}", () => ModuleStatus);
DATA.Subscribe($"{Module}.{Name}.{nameof(IsProcessing)}", () => IsProcessing);
DATA.Subscribe($"{Module}.{Name}.{nameof(SampleCircle)}", () => SampleCircle);
DATA.Subscribe($"{Module}.{Name}.{nameof(CurrentCircle)}", () => CurrentCircle);
DATA.Subscribe($"{Module}.{Name}.{nameof(Distance)}", () => Distance);
DATA.Subscribe($"{Module}.{Name}.{nameof(OutputImage)}", () => OutputImage);
DATA.Subscribe($"{Module}.{Name}.{nameof(Result)}", () => Result);
DATA.Subscribe($"{Module}.{Name}.{nameof(LoadFile)}", () => LoadFile);
DATA.Subscribe($"{Module}.{Name}.{nameof(PreviewImage1)}", () => PreviewImage1);
DATA.Subscribe($"{Module}.{Name}.{nameof(PreviewImage2)}", () => PreviewImage2);
DATA.Subscribe($"{Module}.{Name}.{nameof(PreviewImage3)}", () => PreviewImage3);
DATA.Subscribe($"{Module}.{Name}.{nameof(PreviewImage4)}", () => PreviewImage4);
if (!_isInit)
{
return true;
}
OP.Subscribe($"{Module}.{Name}.ExecuteLocalFile", (string cmd, object[] args) => ExecuteLocalFile((string)args[0]));
OP.Subscribe($"{Module}.{Name}.SetSample", (string cmd, object[] args) => SetSample((string)args[0]));
OP.Subscribe($"{Module}.{Name}.ReloadSolution", (string cmd, object[] args) => LoadSolution());
OP.Subscribe($"{Module}.{Name}.ExecuteGrab", (string cmd, object[] args) => ExecuteGrab((string)args[0]));
LoadSolution();
return true;
}
private double[] ConvertSample(string s)
{
var ss = s.Split(',');
if (ss.Length != 6) return null;
double[] ff = new double[6];
try
{
for (int i = 0; i < ff.Length; i++)
{
ff[i] = Convert.ToDouble(ss[i]);
}
}
catch (Exception)
{
return null;
}
return ff;
}
private bool SetSample(string command)
{
if (command == "GroupCheck")
{
ProjectName = "FindEdge";
}
else if (command.Contains("WaferPlaceCheck"))
{
ProjectName = "FindEdge2";
}
else
{
EV.PostInfoLog(Module, $"VM command error");
return false;
}
IMVSLineFindModuTool module1 = (IMVSLineFindModuTool)VmSolution.Instance[$"{ProjectName}.FindEdge1"];
IMVSLineFindModuTool module2 = (IMVSLineFindModuTool)VmSolution.Instance[$"{ProjectName}.FindEdge2"];
IMVSLineFindModuTool module3 = (IMVSLineFindModuTool)VmSolution.Instance[$"{ProjectName}.FindEdge3"];
GlobalVariableModuleTool globalVar = (GlobalVariableModuleTool)VmSolution.Instance["全局变量1"];
if (globalVar == null || module1 == null || module2 == null || module3 == null) return false;
if (ProjectName == "FindEdge")
{
globalVar.SetGlobalVar("point1x", module1.ModuResult.Midpoint.X.ToString());
globalVar.SetGlobalVar("point1y", module1.ModuResult.Midpoint.Y.ToString());
globalVar.SetGlobalVar("point2x", module2.ModuResult.Midpoint.X.ToString());
globalVar.SetGlobalVar("point2y", module2.ModuResult.Midpoint.Y.ToString());
globalVar.SetGlobalVar("point3x", module3.ModuResult.Midpoint.X.ToString());
globalVar.SetGlobalVar("point3y", module3.ModuResult.Midpoint.Y.ToString());
SampleData[0] = module1.ModuResult.Midpoint.X;
SampleData[1] = module1.ModuResult.Midpoint.Y;
SampleData[2] = module2.ModuResult.Midpoint.X;
SampleData[3] = module2.ModuResult.Midpoint.Y;
SampleData[4] = module3.ModuResult.Midpoint.X;
SampleData[5] = module3.ModuResult.Midpoint.Y;
}
else if (ProjectName == "FindEdge2")
{
globalVar.SetGlobalVar("point1x_2", module1.ModuResult.Midpoint.X.ToString());
globalVar.SetGlobalVar("point1y_2", module1.ModuResult.Midpoint.Y.ToString());
globalVar.SetGlobalVar("point2x_2", module2.ModuResult.Midpoint.X.ToString());
globalVar.SetGlobalVar("point2y_2", module2.ModuResult.Midpoint.Y.ToString());
globalVar.SetGlobalVar("point3x_2", module3.ModuResult.Midpoint.X.ToString());
globalVar.SetGlobalVar("point3y_2", module3.ModuResult.Midpoint.Y.ToString());
SampleData2[0] = module1.ModuResult.Midpoint.X;
SampleData2[1] = module1.ModuResult.Midpoint.Y;
SampleData2[2] = module2.ModuResult.Midpoint.X;
SampleData2[3] = module2.ModuResult.Midpoint.Y;
SampleData2[4] = module3.ModuResult.Midpoint.X;
SampleData2[5] = module3.ModuResult.Midpoint.Y;
}
var ss = $"{module1.ModuResult.Midpoint.X},{module1.ModuResult.Midpoint.Y},{module2.ModuResult.Midpoint.X},{module2.ModuResult.Midpoint.Y},{module3.ModuResult.Midpoint.X},{module3.ModuResult.Midpoint.Y}";
if (ProjectName == "FindEdge")
{
SC.SetItemValue($"{Name}.SampleData", ss);
}
else if (ProjectName == "FindEdge2")
{
SC.SetItemValue($"{Name}.SampleData2", ss);
}
return true;
}
private bool SetInitSample(double[] sampleArray1,double tolerance1, double[] sampleArray2, double tolerance2)
{
if (sampleArray1.Length !=6 || sampleArray2.Length != 6)
{
return false;
}
GlobalVariableModuleTool globalVar = (GlobalVariableModuleTool)VmSolution.Instance["全局变量1"];
if (globalVar == null) return false;
try
{
globalVar.SetGlobalVar("point1x", sampleArray1[0].ToString());
globalVar.SetGlobalVar("point1y", sampleArray1[1].ToString());
globalVar.SetGlobalVar("point2x", sampleArray1[2].ToString());
globalVar.SetGlobalVar("point2y", sampleArray1[3].ToString());
globalVar.SetGlobalVar("point3x", sampleArray1[4].ToString());
globalVar.SetGlobalVar("point3y", sampleArray1[5].ToString());
globalVar.SetGlobalVar("tolerance", tolerance1.ToString());
globalVar.SetGlobalVar("point1x_2", sampleArray2[0].ToString());
globalVar.SetGlobalVar("point1y_2", sampleArray2[1].ToString());
globalVar.SetGlobalVar("point2x_2", sampleArray2[2].ToString());
globalVar.SetGlobalVar("point2y_2", sampleArray2[3].ToString());
globalVar.SetGlobalVar("point3x_2", sampleArray2[4].ToString());
globalVar.SetGlobalVar("point3y_2", sampleArray2[5].ToString());
globalVar.SetGlobalVar("tolerance2", tolerance2.ToString());
}
catch (Exception ex)
{
return false;
}
return true;
}
private int _count = 0;
private bool OnTimer()
{
if (IsProcessing)
{
if (ProjectName!="FindEdge" && ProjectName != "FindEdge2")
{
return true;
}
VmProcedure process = (VmProcedure)VmSolution.Instance[ProjectName];
if (process.IsRunning)
{
_count++;
if (_count > 10)
{
_count = 0;
OutputImage = null;
CurrentCircle = new double[3] { 0,0,0 };
SampleCircle = new double[3] { 0,0,0 };
Distance = 0;
Result = false;
ModuleStatus = false;
IsProcessing = false;
EV.PostInfoLog(Module, $"VM TimeOver");
}
return true;
}
else
{
try
{
IMVSCircleFitModuTool module1 = (IMVSCircleFitModuTool)VmSolution.Instance[$"{ProjectName}.圆拟合1"];
IMVSCircleFitModuTool module2 = (IMVSCircleFitModuTool)VmSolution.Instance[$"{ProjectName}.圆拟合2"];
CalculatorModuleTool module3 = (CalculatorModuleTool)VmSolution.Instance[$"{ProjectName}.变量计算1"];
SaveImageTool module4 = (SaveImageTool)VmSolution.Instance[$"{ProjectName}.OutputImage"];
IfModuleTool module5 = (IfModuleTool)VmSolution.Instance[$"{ProjectName}.条件检测2"];
if (module4.ModuResult.ModuStatus == 1) OutputImage = BitmapToBytes(module4.ModuResult.OutputImage.ToBitmap());
else OutputImage = null;
if (Command == "WaferPlaceCheck")
{
PreviewImage1 = OutputImage;
}
else if (Command == "GroupCheck1")
{
PreviewImage2 = OutputImage;
}
else if (Command == "GroupCheck2")
{
PreviewImage3 = OutputImage;
}
else if (Command == "GroupCheck3")
{
PreviewImage4 = OutputImage;
}
var point1 = module1.ModuResult.OutputCircle.CenterPoint;
var radius1 = module1.ModuResult.OutputCircle.Radius;
var point2 = module2.ModuResult.OutputCircle.CenterPoint;
var radius2 = module2.ModuResult.OutputCircle.Radius;
var result = module3.ModuResult.GetOutputFloat("distance").pFloatVal;
if (point1 == null || point2 == null || result == null)
{
CurrentCircle = new double[3] { 0, 0, 0 };
SampleCircle = new double[3] { 0, 0, 0 };
Distance = 0;
Result = false;
ModuleStatus = false;
IsProcessing = false;
EV.PostInfoLog(Module, $"VM Failed");
return true;
}
CurrentCircle = new double[3] { point1.X, point1.Y, radius1 };
SampleCircle = new double[3] { point2.X, point2.Y, radius2 };
Distance = result.Length == 1 ? result[0] : -1;
Result = module5.ModuResult.NIfResult == 1;
ModuleStatus = module4.ModuResult.ModuStatus == 1;
}
catch (Exception ex)
{
OutputImage = null;
CurrentCircle = new double[3] { 0, 0, 0 };
SampleCircle = new double[3] { 0, 0, 0 };
Distance = 0;
Result = false;
ModuleStatus = false;
IsProcessing = false;
EV.PostInfoLog(Module, $"VM Test Failed");
}
IsProcessing = false;
}
}
else _count = 0;
return true;
}
public byte[] BitmapToBytes(Bitmap bitmap)
{
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Bmp); // 推荐Bmp格式保证数据完整性:ml-citation{ref="1,5" data="citationList"}
return ms.ToArray(); // 比GetBuffer()更精确获取有效数据:ml-citation{ref="12" data="citationList"}
}
}
public bool ExecuteGrab(string command)
{
if (IsProcessing)
{
EV.PostInfoLog(Module, $"VM processing");
return true;
}
var ccd = DEVICE.GetDevice<HikGigeCamera>($"LoadLock.HikGigeCamera");
if (ccd == null)
{
EV.PostInfoLog(Module, $"ccd no install");
return true;
}
if (ccd.ImageData == null)
{
EV.PostInfoLog(Module, $"ccd no picture");
return true;
}
if (command.Contains("WaferPlaceCheck"))
{
ProjectName = "FindEdge2";
}
else if (command.Contains("GroupCheck"))
{
ProjectName = "FindEdge";
}
else
{
EV.PostInfoLog(Module, $"VM command error");
return true;
}
try
{
ModuleStatus = false;
Result = false;
VmProcedure process = (VmProcedure)VmSolution.Instance[$"{ProjectName}"];
ImageSourceModuleTool module = (ImageSourceModuleTool)VmSolution.Instance[$"{ProjectName}.Picture"];
if (null == process || module == null) return true;
module.ModuParams.ImageSourceType = ImageSourceParam.ImageSourceTypeEnum.SDK;
module.SetImageData(ccd.ImageData);
process.Run(command);
IsProcessing = true;
Command = command;
}
catch (VmException ex)
{
EV.PostAlarmLog(Module, $"Excute VM Procedure Failed {ex}");
return true;
}
return true;
}
public bool ExecuteLocalFile(string command)
{
if (IsProcessing)
{
EV.PostInfoLog(Module, $"VM processing");
return true;
}
try
{
if (command.Contains("WaferPlaceCheck"))
{
ProjectName = "FindEdge2";
}
else if (command.Contains("GroupCheck"))
{
ProjectName = "FindEdge";
}
else
{
EV.PostInfoLog(Module, $"VM command error");
return true;
}
VmProcedure process = (VmProcedure)VmSolution.Instance[$"{ProjectName}"];
if (null == process) return true;
ImageSourceModuleTool module = (ImageSourceModuleTool)VmSolution.Instance[$"{ProjectName}.Picture"];
if (module.ModuParams.ImageSourceType == ImageSourceParam.ImageSourceTypeEnum.SDK)
{
module.ModuParams.ImageSourceType = ImageSourceParam.ImageSourceTypeEnum.LocalImage;
module.ClearAllInputImage();
string[] filePaths = Directory.GetFiles(LocalImageFilePath);
foreach (var item in filePaths)
{
module.AddInputImageByPath(item);
}
module.ModuParams.AutoPlay = true;
}
process.Run(command);
IsProcessing = true;
Command = command;
}
catch (VmException ex)
{
EV.PostAlarmLog(Module, $"Excute VM Procedure Failed {ex}");
return true;
}
return true;
}
public void Reset()
{
//if (!_isInit)
//{
// return;
//}
//LoadSolution();
}
private bool LoadSolution()
{
LoadFile = false;
try
{
VmSolution.Load(_sol);
ImageSourceModuleTool module = (ImageSourceModuleTool)VmSolution.Instance["FindEdge.Picture"];
module.ModuParams.ImageSourceType = ImageSourceParam.ImageSourceTypeEnum.LocalImage;
module.ClearAllInputImage();
string[] filePaths = Directory.GetFiles(LocalImageFilePath);
foreach (var item in filePaths)
{
module.AddInputImageByPath(item);
}
module.ModuParams.AutoPlay = true;
module = (ImageSourceModuleTool)VmSolution.Instance["FindEdge2.Picture"];
module.ModuParams.ImageSourceType = ImageSourceParam.ImageSourceTypeEnum.LocalImage;
module.ClearAllInputImage();
filePaths = Directory.GetFiles(LocalImageFilePath);
foreach (var item in filePaths)
{
module.AddInputImageByPath(item);
}
module.ModuParams.AutoPlay = true;
}
catch (Exception ex)
{
EV.PostAlarmLog(Module, $"Load VM file {_sol} Failed {ex}");
return false;
}
if (!SetInitSample(SampleData, Tolerance, SampleData2, Tolerance2))
{
EV.PostAlarmLog(Module, $"Set SampleData failed");
return false;
}
EV.PostInfoLog(Module, $"Load VisionMaster Success");
LoadFile = true;
return true;
}
public void Terminate()
{
VmSolution.Instance?.Dispose();
}
}
}
@@ -0,0 +1,564 @@
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.SCCore;
using Aitex.Core.Util;
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.Keyence
{
public class KeyenceCVX300F : BaseDevice, IConnection, IDevice
{
private KeyenceCVX300FConnection _connection;
private bool _isOn;
private bool _activeMonitorStatus;
private int _errorCode;
private string _lastError = string.Empty;
//private RD_TRIG _trigPumpOnOff = new RD_TRIG();
//private R_TRIG _trigError = new R_TRIG();
//private R_TRIG _trigOverTemp = new R_TRIG();
//private R_TRIG _trigWarningMessage = new R_TRIG();
private R_TRIG _trigCommunicationError = new R_TRIG();
private R_TRIG _trigRetryConnect = new R_TRIG();
uint iCurrentOper = 0xff;
List<byte> liReceivedData = new List<byte>();
byte bEnd = 0x0d;
//bool bStaGood = true;
//bool bCanBeat = false;
//int iBeatTimes = 0;
private int _iArea = 0;
public string _sResult;
//
private PeriodicJob _thread;
private LinkedList<HandlerBase> _lstHandler = new LinkedList<HandlerBase>();
private object _locker = new object();
private bool _enableLog = true;
private string _scRoot;
private string _strCmd;
#region 属性
public string Address
{
get; set;
}
public bool IsConnected
{
get
{
return _connection != null && _connection.IsConnected;
}
}
//属性
public bool AlarmStatus { get; set; }
public bool PositionComplete { get; set; }
public bool MotorBusy { get; set; }
//
public bool IsBusy { get; set; }
//public bool IsStbOff { get; set; } //StbOff消息是否发送
public int AreaData
{
get { return _iArea; }
}
#endregion
public bool Connect()
{
return true;
}
public bool Disconnect()
{
return true;
}
public KeyenceCVX300F(string module, string scRoot, string name) : base(module, name, name, name)
{
_scRoot = scRoot;
_activeMonitorStatus = true;
//
}
public bool Initialize()
{
// string portName = SC.GetStringValue($"{_scRoot}.{Module}.{Name}.Address");
string sAddress = SC.GetStringValue($"{Name}.Address");
Address = sAddress;
_enableLog = SC.GetValue<bool>($"{Name}.EnableLogMessage");
_connection = new KeyenceCVX300FConnection(sAddress);
_connection.EnableLog(_enableLog);
//
_sResult = "";
//
if (_connection.Connect())
{
EV.PostInfoLog(Module, $"{Module}.{Name} connected");
}
//设置属性
this.SetAttr();
//设置操作
this.SetOP();
//
_thread = new PeriodicJob(200, OnTimer, $"{Name} MonitorHandler", true);
//
//this.InitMachine();
//
ConnectionManager.Instance.Subscribe($"{Name}", this);
//SetServoOn();
return true;
}
/// <summary>
/// 设置属性
/// </summary>
private void SetAttr()
{
//DATA.Subscribe($"{Module}.{Name}.Area", () => _iArea);
DATA.Subscribe($"{Module}.{Name}.Result", () => this._sResult);
}
/// <summary>
/// 设置操作
/// </summary>
private void SetOP()
{
//读取面积
//OP.Subscribe($"{Module}.{Name}.CVXCheckArea", (cmd, param) =>
//{
// //Set("T1","T1");
// //EV.PostInfoLog(Module, $"{Name} Get area data.");
// return true;
//});
//读取结果
OP.Subscribe($"{Module}.{Name}.GetResult", (cmd, param) =>
{
GetResult(Convert.ToInt32(param[0]));
//
return true;
});
//转至运行模式
OP.Subscribe($"{Module}.{Name}.RunR0", (cmd, param) =>
{
RunR0();
return true;
});
//清除结果
OP.Subscribe($"{Module}.{Name}.ClearResult", (cmd, param) =>
{
this.ClearResult();
return true;
});
}
public void ClearResult()
{
this._sResult = "";
}
/// <summary>
/// 转到运行模式
/// </summary>
public void RunR0()
{
Set("R0", "R0");
EV.PostInfoLog(Module, $"{Name} Run R0 command.");
}
/// <summary>
/// 获取拍照比对结果
/// </summary>
/// <param name="iConId">执行条件编号</param>
public void GetResult(int iConId)
{
SetExecCond(iConId);
//this._strCmd = param[0] as string;
//if (this._strCmd.Length > 0)
//{
// Set(this._strCmd, this._strCmd);
// EV.PostInfoLog(Module, $"{Name} Get result.");
//}
//
//Set("T1", "T1");
EV.PostInfoLog(Module, $"{Name} Get result.");
}
/// <summary>
/// 设置输出文件名
/// </summary>
/// <param name="sFileName"></param>
public void SetFileName(string sFileName)
{
string sCmd = "STW,1," + sFileName.Trim();//1为相机内文件名编号,相机输出时调用编号
Set("STW", sCmd);
EV.PostInfoLog(Module, $"{Name} Set file name:" + sFileName);
}
/// <summary>
/// 写入执行条件:EXW,n
/// </summary>
/// <param name="iConId">条件编号</param>
public void SetExecCond(int iConId)
{
string sCmd = "EXW," + iConId.ToString();//执行条件编号,现在是点1处使用条件1,点2处使用条件2
Set("EXW", sCmd);
EV.PostInfoLog(Module, $"{Name} Set condition no.");
}
/// <summary>
/// 加入命令队列
/// </summary>
/// <param name="strCmd">命令 Ascii格式</param>
public void Set(string name, string strCmd)
{
lock (_locker)
{
_lstHandler.Clear();
if (_connection.IsBusy)
{
_connection.ForceClear();
}
List<byte> liCmd = Encoding.ASCII.GetBytes(strCmd).ToList<byte>();
liCmd.Add(0x0d); //CR
//liCmd.Add(0x0a); //LF 不可颠倒
byte[] bCmd = liCmd.ToArray();
//_lstHandler.AddLast(new HwAlignerGuideQueryHandler(this, strCmd, bCmd));
_lstHandler.AddLast(new KeyenceCVX300FSetHandler(this, name, bCmd));
}
}
public int _connecteTimes { get; set; }
private bool OnTimer()
{
try
{
//
_connection.MonitorTimeout();
//若断,重连
if ((!_connection.IsConnected) || _connection.IsCommunicationError)
{
lock (_locker)
{
//_trigSevroOn.RST = true;
//IsBusy = false;
_lstHandler.Clear();
}
//
_trigRetryConnect.CLK = _connection.IsConnected; //不可重复置值,否则Q会有变化
if (_connection.Connect())
{
//
//if (_trigRetryConnect.Q)
//{
EV.PostInfoLog(Module, $"{Module}.{Name} connected");
LOG.Write($"{Module}.{Name} connected");
//}
//转至运行模式,此命令可以重入
this.RunR0();
this.SetFileName("sic");
_trigRetryConnect.CLK = true;
}
else
{
if (_trigRetryConnect.Q)
{
EV.PostInfoLog(Module, $"Trying to connect {Module}.{Name} with address: {_connection.Address}");
LOG.Write($"Trying to connect {Module}.{Name} with address: {_connection.Address}");
}
}
Thread.Sleep(2000);//降低重连频率
}
//处理命令队列
HandlerBase handler = null;
if (!_connection.IsBusy)
{
lock (_locker)
{
if (_lstHandler.Count == 0 && _activeMonitorStatus && !IsBusy)
{
//Query();
}
if (_lstHandler.Count > 0)
{
handler = _lstHandler.First.Value;
_lstHandler.RemoveFirst();
}
}
if (handler != null)
{
_connection.Execute(handler);
}
}
//
return true;
}
catch (Exception ex)
{
LOG.Write(ex);
}
return true;
}
internal void NoteError()
{
}
public void Monitor()
{
try
{
_connection.EnableLog(_enableLog);
//if (_connecteTimes < 4) return;
_trigCommunicationError.CLK = _connection.IsCommunicationError;
if (_trigCommunicationError.Q)
{
EV.PostAlarmLog(Module, $"{Module}.{Name} communication error, {_connection.LastCommunicationError}");
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
}
public void Terminate()
{
try
{
if (_connection != null)
{
_connection.Disconnect();
_connection = null;
}
}
catch (Exception ex)
{
LOG.Write(ex);
}
}
public void Reset()
{
//
_connecteTimes = 0;
_connection.SetCommunicationError(false, "");//这里重置了CommunicationError ,就是去了OnTimer里面的重连的触发,所以需要另设变量以触发之(使用timeout来触发的情况)
_enableLog = SC.GetValue<bool>($"{Name}.EnableLogMessage");
_trigCommunicationError.RST = true;
_trigRetryConnect.RST = true;
//
}
public void SetActiveMonitor(bool active)
{
_activeMonitorStatus = active;
}
//internal void NoteOnOff(bool isOn)
//{
// _isOn = isOn;
//}
public bool _PraseData(string name, byte[] buffer)
{
bool bRes = false;
//
try
{
this.bEnd = 0x0d;
this.liReceivedData.AddRange(buffer);
List<byte> liData = new List<byte>();
int iIndex = this.liReceivedData.LastIndexOf(bEnd);
//int iIndex = this.liReceivedData.IndexOf(bEnd);
if (iIndex > 0)
{
liData.AddRange(this.liReceivedData.GetRange(0, iIndex + 1));
this.liReceivedData.RemoveRange(0, iIndex + 1);
}
else
{
return false;
}
string sAnswer = Encoding.ASCII.GetString(liData.ToArray());
//string sAnswer = Encoding.ASCII.GetString(buffer);
//返回一次 "T1\r" ,再次返回 "T1\r00004422,0\r"
string[] sCmds = sAnswer.Split('\n', '\r');
foreach (string sOneCmd in sCmds)
{
if (sOneCmd.Length > 0 && sOneCmd.Trim().CompareTo(name) != 0)
{
//bRes = this.DoOneCmd(name, sOneCmd);
}
}
}
catch (Exception ex)
{
string sEx = $"{Module}.{Name} Exception:" + ex.Message;
EV.PostAlarmLog(Module, sEx);
LOG.Write(sEx);
}
//
return bRes;
}
public bool PraseData(string name, byte[] buffer)
{
//
string sCmdBack = Encoding.ASCII.GetString(buffer);
bool bRes = false;
//
if (sCmdBack.Trim().Length > 0)
{
//
if (name.CompareTo("T1") == 0)
{
if (sCmdBack.CompareTo("T1\r") == 0)
{
bRes = false;
}
else
{
bool bResult = sCmdBack.Replace("T1\r", "").Contains("0");
//
if (bResult)
{
this._sResult = "OK";
}
else
{
this._sResult = "NG";
}
bRes = true;
}
}
else if (name.CompareTo("EXW") == 0)
{
Set("T1", "T1");
bRes = true;
}
else
{
if (sCmdBack.Contains("ER,"))
{
EV.PostWarningLog(Module, "Keyence CCD camera get an error answer.");
}
bRes = true;
}
}
//
return bRes;
}
//public void SetErrorCode(int errorCode)
//{
// _errorCode = errorCode;
//}
//public void SetError(string reason)
//{
// _trigWarningMessage.CLK = true;
// if (_trigWarningMessage.Q)
// {
// EV.PostWarningLog(Module, $"{Module}.{Name} error, {reason}");
// }
//}
private static byte[] ModRTU_CRC(byte[] buffer)
{
ushort crc = 0xFFFF;
// var buf = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, buffer));
var buf = buffer;
var len = buffer.Length;
for (var pos = 0; pos < len; pos++)
{
crc ^= buf[pos]; // XOR byte into least sig. byte of crc
for (var i = 8; i != 0; i--)
// Loop over each bit
if ((crc & 0x0001) != 0)
{
// If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
{
crc >>= 1; // Just shift right
}
}
// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
return BitConverter.GetBytes(crc);
}
}
}
@@ -0,0 +1,90 @@
using MECF.Framework.Common.Communications;
using System.Collections.Generic;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.Keyence
{
//public class KeyenceCVX300FConnection : SerialPortConnectionBase
public class KeyenceCVX300FConnection : TCPPortConnectionBase
{
private List<byte> _lstCacheBuffer = new List<byte>();
public KeyenceCVX300FConnection(string sAddress)
: base(sAddress, "\n", false)
{
}
public override bool SendMessage(byte[] message)
{
_lstCacheBuffer.Clear();
return base.SendMessage(message);
}
protected override MessageBase ParseResponse(byte[] rawMessage)
{
_lstCacheBuffer.AddRange(rawMessage);
byte[] temps = _lstCacheBuffer.ToArray();
KeyenceCVX300FMessage msg = new KeyenceCVX300FMessage();
msg.IsResponse = false;
msg.IsAck = false;
msg.IsComplete = false;
msg.RawMessage = _lstCacheBuffer.ToArray();
//if (temps.Length < 4) return msg;
/*
msg.DeviceAddress = temps[0];
msg.FunctionCode = temps[1];
*/
//if (msg.FunctionCode == 3)
//{
// msg.Length = temps[2];
// if (temps.Length < msg.Length + 5) return msg;
// msg.Data = _lstCacheBuffer.Skip(3).Take(msg.Length).ToArray();
//}else
msg.Data = _lstCacheBuffer.ToArray();
msg.IsResponse = true;
msg.IsAck = true;
msg.IsComplete = true;
//msg.IsEvent = false;
//msg.IsResponse = false;
return msg;
}
private static byte ModRTU_CRC(byte[] buffer)
{
//ushort crc = 0xFFFF;
// var buf = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, buffer));
var buf = buffer;
var len = buffer.Length;
byte temp = buffer[0];
for (int i = 1; i < buffer.Length; i++)
{
temp = (byte)(temp ^ buffer[i]);
}
return (byte)~temp;
}
//public new void Execute(HandlerBase handler)
//{
// if (_activeHandler != null || handler == null) //|| !_port.IsOpen())
// {
// return;
// }
// lock (_lockerActiveHandler)
// {
// retryTime = 0;
// _activeHandler = handler;
// _activeHandler.SetState(EnumHandlerState.Sent);
// SendMessage(handler.SendBinary);
// //
// }
//}
}
}
@@ -0,0 +1,109 @@
using MECF.Framework.Common.Communications;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.Keyence
{
public abstract class KeyenceCVX300FHandler : HandlerBase
{
public KeyenceCVX300F Device { get; }
protected KeyenceCVX300FHandler(KeyenceCVX300F device, byte[] commandvalue)
: base(commandvalue)
{
Device = device;
}
private static byte[] BuildMessage(byte[] commandvalue)
{
byte[] crc = ModRTU_CRC(commandvalue);
List<byte> result = commandvalue.ToList();
foreach (byte b in crc)
{
result.Add(b);
}
return result.ToArray();
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as KeyenceCVX300FMessage;
ResponseMessage = msg;
handled = true;
return true;
}
private static byte[] ModRTU_CRC(byte[] buffer)
{
ushort crc = 0xFFFF;
// var buf = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, buffer));
var buf = buffer;
var len = buffer.Length;
for (var pos = 0; pos < len; pos++)
{
crc ^= buf[pos]; // XOR byte into least sig. byte of crc
for (var i = 8; i != 0; i--)
// Loop over each bit
if ((crc & 0x0001) != 0)
{
// If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
{
crc >>= 1; // Just shift right
}
}
// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
return BitConverter.GetBytes(crc);
}
}
public class KeyenceCVX300FQueryHandler : KeyenceCVX300FHandler
{
public KeyenceCVX300FQueryHandler(KeyenceCVX300F device, string name, byte[] commandvalue)
: base(device, commandvalue)
{
Name = name;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as KeyenceCVX300FMessage;
handled = false;
if (!result.IsResponse)
return true;
Device.PraseData(Name, result.Data);
Device._connecteTimes = 0;
ResponseMessage = msg;
handled = true;
return true;
}
}
public class KeyenceCVX300FSetHandler : KeyenceCVX300FHandler
{
public KeyenceCVX300FSetHandler(KeyenceCVX300F device, string name, byte[] commandvalue)
: base(device, commandvalue)
{
Name = name;
}
public override bool HandleMessage(MessageBase msg, out bool handled)
{
var result = msg as KeyenceCVX300FMessage;
handled = Device.PraseData(Name, result.Data);
ResponseMessage = msg;
Device.IsBusy = false;
return true;
}
}
}
@@ -0,0 +1,14 @@
using MECF.Framework.Common.Communications;
namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.Keyence
{
public class KeyenceCVX300FMessage : BinaryMessage
{
public byte DeviceAddress { get; set; }
public byte FunctionCode { get; set; }
public byte Length { get; set; }
public byte[] Data { get; set; }
}
}