首次上传

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,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();
}
}
}