diff --git a/halftoneproject-master.rar b/halftoneproject-master.rar new file mode 100644 index 0000000..489ac17 Binary files /dev/null and b/halftoneproject-master.rar differ diff --git a/halftoneproject-master/Code/Config.cs b/halftoneproject-master/Code/Config.cs index 152508e..738ca42 100644 --- a/halftoneproject-master/Code/Config.cs +++ b/halftoneproject-master/Code/Config.cs @@ -1,101 +1,103 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using ProductionControl.Utils; - -namespace ProductionControl -{ - public class Config - { - public static Models.User loginUser; - public static bool HeightDevIOState; - public static Dictionary dicDevType = new Dictionary(); - // - public static string appBasePath = ""; - public static string CustomerVer = "A"; - - //跳过检测设备 - public static bool SkipAxis0, SkipAxis1, SkipAxis2, SkipAxis3; - public static bool SkipTension, SkipHeight, SkipLight, SkipScannerGL, SkipScannerCC, SkipSmallAxis; - //启用功能 2023-1023 - public static bool OpenMarkErrorStop; - - //DEV - public static int[] Axis_PulseOutMode=new int[4]; - public static int[] Axis_MM2PulseNum = new int[4] { 5000, 5000, 5000, 1000};//1mm对应脉冲数 - public static int[] Axis_HomeMode = new int[4]; - public static int[] Axis_HomeDir = new int[4];//回Home方向 - //回HOME速度 - public static JArray Axis_HomeVelLow = new JArray(); - public static JArray Axis_HomeVelHigh = new JArray(); - public static JArray Axis_HomeAcc = new JArray(); - public static JArray Axis_HomeDec = new JArray(); - - public static string IOCard_DeviceNum = "PCI-1730,BID#0"; - public static LightDevNameEnum Light_Name= LightDevNameEnum.康仕达; - public static int Light_PortNum = 1;//COM端口号 - public static int Tension_PortNum = 7;//COM端口号 - public static string SmallAxis_ComName = "COM2";//COM端口号 - public static string HeightDev_IP = "192.168.3.35"; - public static int HeightDev_Port = 64000; - public static decimal HeightDev_SafeValue = 0;//厚度传感器安全值(axis移动前的前提条件) - - public static string Scanner_GENTL_CTI = "ScannerRuntime\\Win64_x64\\MvFGProducerCXP.cti";//板卡相机 - //public static string Scanner_GENTL_CTI = "ScannerRuntime\\Win64_x64\\MvFGProducerCML.cti";//GE相机 - public static string SizeEnginePath; - public static string SizeBmp_SavePath, SizeBmp_Compare_SavePath, SizeBmp_Zoom_Image_SavePath; - public static double SizeBmp_SavePath_AutoClear = -1, SizeBmp_Compare_SavePath_AutoClear = -1, SizeBmp_Zoom_Image_SavePath_AutoClear = -1; - //缺陷配置 - public static Size Defect_CutSize, Defect_ReSize; - public static float Defect_Thresholds; - public static string Defect_SavePath, Defect_Compress_SavePath, Defect_Small_SavePath; - public static double Defect_SavePath_AutoClear =-1,Defect_Compress_SavePath_AutoClear=-1,Defect_Small_SavePath_AutoClear=-1; - public static bool SaveAllDefectImg, MakeTag; - //尺寸配置 - //public static string Size_LoadPath, Size_FileName; - - // - public static Dictionary CMDProcess; - - //DB - //有些服务器防火墙有问题需要加上 min pool size=1 避免认为是恶意请求 - //如果用到bulkCopy需要加: AllowLoadLocalInfile=true - //public static string dbMysqlCon = "server=localhost;Database=ProductionDB;Uid=root;Pwd=123456;"; - public static string DBConStr = "server=localhost;Database=ProductionDB;Uid=root;Pwd=123456; AllowLoadLocalInfile=true"; - - //LOG - public static string LogPath; - - //WEBService - public static string LocalIp=""; - public static int LocalHttpPort=18082, LocalSocketPort; - public static int timeout_http_wait = -1;//webapi超时限制,-1为无限制一直等待 - - //==========位置 初始位 上料位 下料位(下料位不存在时使用上料位) - public static JObject joPTSetting = new JObject() - { - { "initPT", null }, - { "upPT", null}, - { "downPT", null} - }; - //=========全局按钮 - //public static JObject joGButtonSetting = new JObject() { - // { "start", null }, - // { "pause", null}, - // { "reset", null}, - // { "warning", null}, - // { "iodefault", null} - //}; - public static void DelectPictureFile() - { - //删除文件 - Task.Factory.StartNew(() => +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using ProductionControl.Utils; + +namespace ProductionControl +{ + public class Config + { + public static Models.User loginUser; + public static bool HeightDevIOState; + public static Dictionary dicDevType = new Dictionary(); + // + public static string appBasePath = ""; + public static string CustomerVer = "A"; + + //跳过检测设备 + public static bool SkipAxis0, SkipAxis1, SkipAxis2, SkipAxis3; + public static bool SkipTension, SkipHeight, SkipLight, SkipScannerGL, SkipScannerCC, SkipSmallAxis; + //启用功能 2023-1023 + public static bool OpenMarkErrorStop; + //启用缺陷分布功能 + public static bool OpenFlawDistribution; + //DEV + public static int[] Axis_PulseOutMode=new int[4]; + public static int[] Axis_MM2PulseNum = new int[4] { 5000, 5000, 5000, 1000};//1mm对应脉冲数 + public static int[] Axis_HomeMode = new int[4]; + public static int[] Axis_HomeDir = new int[4];//回Home方向 + //回HOME速度 + public static JArray Axis_HomeVelLow = new JArray(); + public static JArray Axis_HomeVelHigh = new JArray(); + public static JArray Axis_HomeAcc = new JArray(); + public static JArray Axis_HomeDec = new JArray(); + + public static string IOCard_DeviceNum = "PCI-1730,BID#0"; + public static LightDevNameEnum Light_Name= LightDevNameEnum.康仕达; + public static int Light_PortNum = 1;//COM端口号 + public static int Tension_PortNum = 7;//COM端口号 + public static double Tension_Offset = 0;//张力偏移值 + public static string SmallAxis_ComName = "COM2";//COM端口号 + public static string HeightDev_IP = "192.168.3.35"; + public static int HeightDev_Port = 64000; + public static decimal HeightDev_SafeValue = 0;//厚度传感器安全值(axis移动前的前提条件) + + public static string Scanner_GENTL_CTI = "ScannerRuntime\\Win64_x64\\MvFGProducerCXP.cti";//板卡相机 + //public static string Scanner_GENTL_CTI = "ScannerRuntime\\Win64_x64\\MvFGProducerCML.cti";//GE相机 + public static string SizeEnginePath; + public static string SizeBmp_SavePath, SizeBmp_Compare_SavePath, SizeBmp_Zoom_Image_SavePath; + public static double SizeBmp_SavePath_AutoClear = -1, SizeBmp_Compare_SavePath_AutoClear = -1, SizeBmp_Zoom_Image_SavePath_AutoClear = -1; + //缺陷配置 + public static Size Defect_CutSize, Defect_ReSize; + public static float Defect_Thresholds; + public static string Defect_SavePath, Defect_Compress_SavePath, Defect_Small_SavePath; + public static double Defect_SavePath_AutoClear =-1,Defect_Compress_SavePath_AutoClear=-1,Defect_Small_SavePath_AutoClear=-1; + public static bool SaveAllDefectImg, MakeTag; + //尺寸配置 + //public static string Size_LoadPath, Size_FileName; + + // + public static Dictionary CMDProcess; + + //DB + //有些服务器防火墙有问题需要加上 min pool size=1 避免认为是恶意请求 + //如果用到bulkCopy需要加: AllowLoadLocalInfile=true + //public static string dbMysqlCon = "server=localhost;Database=ProductionDB;Uid=root;Pwd=123456;"; + public static string DBConStr = "server=localhost;Database=ProductionDB;Uid=root;Pwd=123456; AllowLoadLocalInfile=true"; + + //LOG + public static string LogPath; + + //WEBService + public static string LocalIp=""; + public static int LocalHttpPort=18082, LocalSocketPort; + public static int timeout_http_wait = -1;//webapi超时限制,-1为无限制一直等待 + + //==========位置 初始位 上料位 下料位(下料位不存在时使用上料位) + public static JObject joPTSetting = new JObject() + { + { "initPT", null }, + { "upPT", null}, + { "downPT", null} + }; + //=========全局按钮 + //public static JObject joGButtonSetting = new JObject() { + // { "start", null }, + // { "pause", null}, + // { "reset", null}, + // { "warning", null}, + // { "iodefault", null} + //}; + public static void DelectPictureFile() + { + //删除文件 + Task.Factory.StartNew(() => { // CreateSysFolder(); @@ -103,284 +105,291 @@ namespace ProductionControl //DeleteFiles(appBasePath + "\\temp\\"); // - if (Defect_SavePath_AutoClear >= 0) - DeleteFiles(Config.Defect_SavePath, Defect_SavePath_AutoClear, false); - if (Defect_Compress_SavePath_AutoClear >= 0) - DeleteFiles(Config.Defect_Compress_SavePath, Defect_Compress_SavePath_AutoClear, false); - if (Defect_Small_SavePath_AutoClear >= 0) - DeleteFiles(Config.Defect_Small_SavePath, Defect_Small_SavePath_AutoClear, false); - - // - if (SizeBmp_SavePath_AutoClear >= 0) - DeleteFiles(Config.SizeBmp_SavePath, SizeBmp_SavePath_AutoClear, false); - if (SizeBmp_Compare_SavePath_AutoClear >= 0) - DeleteFiles(Config.SizeBmp_Compare_SavePath, SizeBmp_Compare_SavePath_AutoClear, false); - if (SizeBmp_Zoom_Image_SavePath_AutoClear >= 0) - DeleteFiles(Config.SizeBmp_Zoom_Image_SavePath, SizeBmp_Zoom_Image_SavePath_AutoClear, false); - }); - } - - public static void LoadAllConfig() - { - if (string.IsNullOrWhiteSpace(appBasePath)) - appBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - - //删除文件 - Task.Factory.StartNew(() => - { - CreateSysFolder(); - - // - DeleteFiles(appBasePath+"\\temp\\"); - - // - if (Defect_SavePath_AutoClear>=0) - DeleteFiles(Config.Defect_SavePath, Defect_SavePath_AutoClear,true); - if (Defect_Compress_SavePath_AutoClear >= 0) - DeleteFiles(Config.Defect_Compress_SavePath, Defect_Compress_SavePath_AutoClear, true); - if (Defect_Small_SavePath_AutoClear>=0) - DeleteFiles(Config.Defect_Small_SavePath, Defect_Small_SavePath_AutoClear, true); - - // - if (SizeBmp_SavePath_AutoClear >= 0) - DeleteFiles(Config.SizeBmp_SavePath, SizeBmp_SavePath_AutoClear, true); - if (SizeBmp_Compare_SavePath_AutoClear >= 0) - DeleteFiles(Config.SizeBmp_Compare_SavePath, SizeBmp_Compare_SavePath_AutoClear, true); - if (SizeBmp_Zoom_Image_SavePath_AutoClear >= 0) - DeleteFiles(Config.SizeBmp_Zoom_Image_SavePath, SizeBmp_Zoom_Image_SavePath_AutoClear, true); - }); - - InitDevDic(); - LoadSysConfig(); - LoadPTConfig(); - - // - string lsCmdPath = appBasePath + "\\CMDProcess\\"; - if(!Directory.Exists(lsCmdPath)) - Directory.CreateDirectory(lsCmdPath); - - string fileName; - CMDProcess = new Dictionary(); - foreach (int item in Enum.GetValues(typeof(CMDName)))//item为key值 - { - //string name = Enum.GetName(typeof(CMDName), item);//获取名称 - fileName = lsCmdPath + item + ".json"; - if (File.Exists(fileName)) - CMDProcess.Add((CMDName)item, JObject.Parse(File.ReadAllText(fileName))); - //else - // CMDProcess.Add((CMDName)item, null); - } - } - public static void LoadSysConfig() - { - if (string.IsNullOrWhiteSpace(appBasePath)) - appBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - string configPath = appBasePath + "\\SysConfig.ini"; - string lsTmp = ""; - - CustomerVer = Util.ReadIniValue(configPath, "VER", "CustomerVer"); - if (string.IsNullOrWhiteSpace(CustomerVer)) - CustomerVer = "A"; - - //Skip - SkipAxis0 = Util.ReadIniValue(configPath, "SKIP", "SkipAxis0") =="1"; - SkipAxis1 = Util.ReadIniValue(configPath, "SKIP", "SkipAxis1") == "1"; - SkipAxis2 = Util.ReadIniValue(configPath, "SKIP", "SkipAxis2") == "1"; - SkipAxis3 = Util.ReadIniValue(configPath, "SKIP", "SkipAxis3") == "1"; - SkipTension = Util.ReadIniValue(configPath, "SKIP", "SkipTension") == "1"; - SkipHeight = Util.ReadIniValue(configPath, "SKIP", "SkipHeight") == "1"; - SkipLight = Util.ReadIniValue(configPath, "SKIP", "SkipLight") == "1"; - SkipScannerGL = Util.ReadIniValue(configPath, "SKIP", "SkipScannerGL") == "1"; - SkipScannerCC = Util.ReadIniValue(configPath, "SKIP", "SkipScannerCC") == "1"; - SkipSmallAxis = Util.ReadIniValue(configPath, "SKIP", "SkipSmallAxis") == "1"; - - OpenMarkErrorStop = Util.ReadIniValue(configPath, "SKIP", "MarkErrorStop") == "1"; - //DEV - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_PulseOutMode"); - if (Util.IsNumber(lsTmp)) Config.Axis_PulseOutMode[0] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_PulseOutMode"); - if (Util.IsNumber(lsTmp)) Config.Axis_PulseOutMode[1] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_PulseOutMode"); - if (Util.IsNumber(lsTmp)) Config.Axis_PulseOutMode[2] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_PulseOutMode"); - if (Util.IsNumber(lsTmp)) Config.Axis_PulseOutMode[3] = Convert.ToInt32(lsTmp); - - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_HomeMode"); - if (Util.IsNumber(lsTmp)) Config.Axis_HomeMode[0] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_HomeMode"); - if (Util.IsNumber(lsTmp)) Config.Axis_HomeMode[1] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_HomeMode"); - if (Util.IsNumber(lsTmp)) Config.Axis_HomeMode[2] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_HomeMode"); - if (Util.IsNumber(lsTmp)) Config.Axis_HomeMode[3] = Convert.ToInt32(lsTmp); - - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_HomeDir"); - if (Util.IsNumber(lsTmp)) Config.Axis_HomeDir[0] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_HomeDir"); - if (Util.IsNumber(lsTmp)) Config.Axis_HomeDir[1] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_HomeDir"); - if (Util.IsNumber(lsTmp)) Config.Axis_HomeDir[2] = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_HomeDir"); - if (Util.IsNumber(lsTmp)) Config.Axis_HomeDir[3] = Convert.ToInt32(lsTmp); - - // - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeVelLow"); - if (!string.IsNullOrWhiteSpace(lsTmp)) Axis_HomeVelLow = JArray.Parse(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeVelHigh"); - if (!string.IsNullOrWhiteSpace(lsTmp)) Axis_HomeVelHigh = JArray.Parse(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeAcc"); - if (!string.IsNullOrWhiteSpace(lsTmp)) Axis_HomeAcc = JArray.Parse(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeDec"); - if (!string.IsNullOrWhiteSpace(lsTmp)) Axis_HomeDec = JArray.Parse(lsTmp); - // - lsTmp = Util.ReadIniValue(configPath, "DEV", "Light_Name"); - if (Util.IsNumber(lsTmp)) Config.Light_Name = (LightDevNameEnum)Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Light_PortNum"); - if (Util.IsNumber(lsTmp)) Config.Light_PortNum = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Tension_PortNum"); - if (Util.IsNumber(lsTmp)) Config.Tension_PortNum = Convert.ToInt32(lsTmp); - Config.SmallAxis_ComName = Util.ReadIniValue(configPath, "DEV", "SmallAxis_ComName"); - - HeightDev_IP = Util.ReadIniValue(configPath, "DEV", "HeightDev_IP"); - lsTmp = Util.ReadIniValue(configPath, "DEV", "HeightDev_Port"); - if (Util.IsNumber(lsTmp)) Config.HeightDev_Port = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "DEV", "HeightDev_SafeValue"); - if (Util.IsNumber(lsTmp)) Config.HeightDev_SafeValue = Convert.ToDecimal(lsTmp); - - IOCard_DeviceNum = Util.ReadIniValue(configPath, "DEV", "IOCard_DeviceNum"); - - Defect_SavePath = Util.ReadIniValue(configPath, "DEV", "Defect_SavePath"); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_SavePath_AutoClear"); - if (Util.IsNumber(lsTmp)) Defect_SavePath_AutoClear = Convert.ToDouble(lsTmp); - Defect_Compress_SavePath = Util.ReadIniValue(configPath, "DEV", "Defect_Compress_SavePath"); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_Compress_SavePath_AutoClear"); - if (Util.IsNumber(lsTmp)) Defect_Compress_SavePath_AutoClear = Convert.ToDouble(lsTmp); - - Defect_Small_SavePath = Util.ReadIniValue(configPath, "DEV", "Defect_Small_SavePath"); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_Small_SavePath_AutoClear"); - if (Util.IsNumber(lsTmp)) Defect_Small_SavePath_AutoClear = Convert.ToDouble(lsTmp); - - lsTmp = Util.ReadIniValue(configPath, "DEV", "SaveAllDefectImg"); - SaveAllDefectImg = (lsTmp == "1"); - MakeTag = Util.ReadIniValue(configPath, "DEV", "MakeTag") == "1"; - SizeEnginePath = Util.ReadIniValue(configPath, "DEV", "SizeEnginePath"); - - SizeBmp_SavePath = Util.ReadIniValue(configPath, "DEV", "SizeBmp_SavePath"); - lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_SavePath_AutoClear"); - if (Util.IsNumber(lsTmp)) SizeBmp_SavePath_AutoClear = Convert.ToDouble(lsTmp); - - SizeBmp_Compare_SavePath = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath"); - lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath_AutoClear"); - if (Util.IsNumber(lsTmp)) SizeBmp_Compare_SavePath_AutoClear = Convert.ToDouble(lsTmp); - - SizeBmp_Zoom_Image_SavePath = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath"); - lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath_AutoClear"); - if (Util.IsNumber(lsTmp)) SizeBmp_Zoom_Image_SavePath_AutoClear = Convert.ToDouble(lsTmp); - //DB - DBConStr = Util.ReadIniValue(configPath, "DB", "DBConStr"); - //HTTP - LocalIp= Util.ReadIniValue(configPath, "HTTP", "LocalIp"); - lsTmp = Util.ReadIniValue(configPath, "HTTP", "LocalHttpPort"); - if (Util.IsNumber(lsTmp)) Config.LocalHttpPort = Convert.ToInt32(lsTmp); - lsTmp = Util.ReadIniValue(configPath, "HTTP", "LocalSocketPort"); - if (Util.IsNumber(lsTmp)) Config.LocalSocketPort = Convert.ToInt32(lsTmp); - //LOG - LogPath = Util.ReadIniValue(configPath, "LOG", "LogPath"); - - //缺陷配置 - Defect_CutSize = new Size(592, 532); - Defect_ReSize = new Size(224, 224); - Defect_Thresholds = 0.4f; - } - public static void LoadPTConfig() - { - if (string.IsNullOrWhiteSpace(appBasePath)) - appBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - string configPath = appBasePath + "\\PTConfig.json"; - string lsTmp = File.ReadAllText(configPath); - joPTSetting = JObject.Parse(lsTmp); - } - - private static void InitDevDic() - { - //dicDevType.Add("CodeScanner", "扫码枪");//固定为必有开始 - if(!dicDevType.ContainsKey("IOCard")) dicDevType.Add("IOCard", "I/O控制"); - if (!dicDevType.ContainsKey("Tension")) dicDevType.Add("Tension", "张力测量"); - if (!dicDevType.ContainsKey("Height")) dicDevType.Add("Height", "厚度测量"); - if (!dicDevType.ContainsKey("Axis")) dicDevType.Add("Axis", "滑台电机"); - if (!dicDevType.ContainsKey("AxisTag")) dicDevType.Add("AxisTag", "滑台&测量"); - if (!dicDevType.ContainsKey("Light")) dicDevType.Add("Light", "光源"); - if (!dicDevType.ContainsKey("Scanner_GENTL")) dicDevType.Add("Scanner_GENTL", "相机GENTL"); - if (!dicDevType.ContainsKey("Scanner_CC")) dicDevType.Add("Scanner_CC", "相机CC"); - if (!dicDevType.ContainsKey("SmallAxis")) dicDevType.Add("SmallAxis", "镜头电机"); - if (!dicDevType.ContainsKey("Defect")) dicDevType.Add("Defect", "缺陷检测"); - if (!dicDevType.ContainsKey("Size")) dicDevType.Add("Size", "尺寸测量"); - if (!dicDevType.ContainsKey("For")) dicDevType.Add("For", "For循环"); - if (!dicDevType.ContainsKey("If")) dicDevType.Add("If", "If条件"); - } - - private static void CreateSysFolder() - { - appBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - string dirPath = appBasePath + "\\Attachment\\"; - if(!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); - - dirPath = appBasePath + "\\Temp\\"; - if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); - } - /// - /// - /// - /// - /// - /// 把日期文件夹也按days进行删除,格式:yyyyMMdd - private static void DeleteFiles(string dirPath,double days=0,bool delDir=false) - { - if (!Directory.Exists(dirPath)) return; - DateTime delDate = DateTime.Now.AddDays(-days); - API.OutputDebugString($"清除{delDate.ToString("yyyyMMdd")}前记录:{dirPath}。"); - string[] file_list = Directory.GetFiles(dirPath); - if(days>0) - file_list = file_list.Select(file => new FileInfo(file)) - .Where(f=>f.CreationTime<= delDate) - .Select(x => x.FullName) - .ToArray(); - - foreach (string file in file_list) - { - try { - API.OutputDebugString($"清除文件:{file}..."); - File.Delete(file); - } catch(Exception ex) { - API.OutputDebugString($"Ex1:{ex.Message}"); - } - } - - // - if (delDir) - { - int dateNum = Convert.ToInt32(delDate.ToString("yyyyMMdd")); - string floderName; - string[] dirList = Directory.GetDirectories(dirPath,"20*"); - foreach (string dir in dirList) - { - floderName= dir.Trim('\\'); - floderName = floderName.Substring(floderName.LastIndexOf('\\') + 1); - if (floderName.Length == 8 && Util.IsNumber(floderName) && Convert.ToInt32(floderName) <= dateNum) - { - try - { - API.OutputDebugString($"清除目录:{dir}..."); - Directory.Delete(dir,true); - } - catch (Exception ex) - { - API.OutputDebugString($"Ex2:{ex.Message}"); - } - } - } - } - - } - } -} + if (Defect_SavePath_AutoClear >= 0) + DeleteFiles(Config.Defect_SavePath, Defect_SavePath_AutoClear, false); + if (Defect_Compress_SavePath_AutoClear >= 0) + DeleteFiles(Config.Defect_Compress_SavePath, Defect_Compress_SavePath_AutoClear, false); + if (Defect_Small_SavePath_AutoClear >= 0) + DeleteFiles(Config.Defect_Small_SavePath, Defect_Small_SavePath_AutoClear, false); + + // + if (SizeBmp_SavePath_AutoClear >= 0) + DeleteFiles(Config.SizeBmp_SavePath, SizeBmp_SavePath_AutoClear, false); + if (SizeBmp_Compare_SavePath_AutoClear >= 0) + DeleteFiles(Config.SizeBmp_Compare_SavePath, SizeBmp_Compare_SavePath_AutoClear, false); + if (SizeBmp_Zoom_Image_SavePath_AutoClear >= 0) + DeleteFiles(Config.SizeBmp_Zoom_Image_SavePath, SizeBmp_Zoom_Image_SavePath_AutoClear, false); + }); + } + + public static void LoadAllConfig() + { + if (string.IsNullOrWhiteSpace(appBasePath)) + appBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + + //删除文件 + Task.Factory.StartNew(() => + { + CreateSysFolder(); + + // + DeleteFiles(appBasePath+"\\temp\\"); + + // + if (Defect_SavePath_AutoClear>=0) + DeleteFiles(Config.Defect_SavePath, Defect_SavePath_AutoClear,true); + if (Defect_Compress_SavePath_AutoClear >= 0) + DeleteFiles(Config.Defect_Compress_SavePath, Defect_Compress_SavePath_AutoClear, true); + if (Defect_Small_SavePath_AutoClear>=0) + DeleteFiles(Config.Defect_Small_SavePath, Defect_Small_SavePath_AutoClear, true); + + // + if (SizeBmp_SavePath_AutoClear >= 0) + DeleteFiles(Config.SizeBmp_SavePath, SizeBmp_SavePath_AutoClear, true); + if (SizeBmp_Compare_SavePath_AutoClear >= 0) + DeleteFiles(Config.SizeBmp_Compare_SavePath, SizeBmp_Compare_SavePath_AutoClear, true); + if (SizeBmp_Zoom_Image_SavePath_AutoClear >= 0) + DeleteFiles(Config.SizeBmp_Zoom_Image_SavePath, SizeBmp_Zoom_Image_SavePath_AutoClear, true); + }); + + InitDevDic(); + LoadSysConfig(); + LoadPTConfig(); + + // + string lsCmdPath = appBasePath + "\\CMDProcess\\"; + if(!Directory.Exists(lsCmdPath)) + Directory.CreateDirectory(lsCmdPath); + + string fileName; + CMDProcess = new Dictionary(); + foreach (int item in Enum.GetValues(typeof(CMDName)))//item为key值 + { + //string name = Enum.GetName(typeof(CMDName), item);//获取名称 + fileName = lsCmdPath + item + ".json"; + if (File.Exists(fileName)) + CMDProcess.Add((CMDName)item, JObject.Parse(File.ReadAllText(fileName))); + //else + // CMDProcess.Add((CMDName)item, null); + } + } + public static void LoadSysConfig() + { + if (string.IsNullOrWhiteSpace(appBasePath)) + appBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + string configPath = appBasePath + "\\SysConfig.ini"; + string lsTmp = ""; + + CustomerVer = Util.ReadIniValue(configPath, "VER", "CustomerVer"); + if (string.IsNullOrWhiteSpace(CustomerVer)) + CustomerVer = "A"; + + //Skip + SkipAxis0 = Util.ReadIniValue(configPath, "SKIP", "SkipAxis0") =="1"; + SkipAxis1 = Util.ReadIniValue(configPath, "SKIP", "SkipAxis1") == "1"; + SkipAxis2 = Util.ReadIniValue(configPath, "SKIP", "SkipAxis2") == "1"; + SkipAxis3 = Util.ReadIniValue(configPath, "SKIP", "SkipAxis3") == "1"; + SkipTension = Util.ReadIniValue(configPath, "SKIP", "SkipTension") == "1"; + SkipHeight = Util.ReadIniValue(configPath, "SKIP", "SkipHeight") == "1"; + SkipLight = Util.ReadIniValue(configPath, "SKIP", "SkipLight") == "1"; + SkipScannerGL = Util.ReadIniValue(configPath, "SKIP", "SkipScannerGL") == "1"; + SkipScannerCC = Util.ReadIniValue(configPath, "SKIP", "SkipScannerCC") == "1"; + SkipSmallAxis = Util.ReadIniValue(configPath, "SKIP", "SkipSmallAxis") == "1"; + + OpenMarkErrorStop = Util.ReadIniValue(configPath, "SKIP", "MarkErrorStop") == "1"; + OpenFlawDistribution = Util.ReadIniValue(configPath, "SKIP", "OpenFlawDistribution") == "1"; + //DEV + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_PulseOutMode"); + if (Util.IsNumber(lsTmp)) Config.Axis_PulseOutMode[0] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_PulseOutMode"); + if (Util.IsNumber(lsTmp)) Config.Axis_PulseOutMode[1] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_PulseOutMode"); + if (Util.IsNumber(lsTmp)) Config.Axis_PulseOutMode[2] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_PulseOutMode"); + if (Util.IsNumber(lsTmp)) Config.Axis_PulseOutMode[3] = Convert.ToInt32(lsTmp); + + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_HomeMode"); + if (Util.IsNumber(lsTmp)) Config.Axis_HomeMode[0] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_HomeMode"); + if (Util.IsNumber(lsTmp)) Config.Axis_HomeMode[1] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_HomeMode"); + if (Util.IsNumber(lsTmp)) Config.Axis_HomeMode[2] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_HomeMode"); + if (Util.IsNumber(lsTmp)) Config.Axis_HomeMode[3] = Convert.ToInt32(lsTmp); + + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_HomeDir"); + if (Util.IsNumber(lsTmp)) Config.Axis_HomeDir[0] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_HomeDir"); + if (Util.IsNumber(lsTmp)) Config.Axis_HomeDir[1] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_HomeDir"); + if (Util.IsNumber(lsTmp)) Config.Axis_HomeDir[2] = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_HomeDir"); + if (Util.IsNumber(lsTmp)) Config.Axis_HomeDir[3] = Convert.ToInt32(lsTmp); + + // + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeVelLow"); + if (!string.IsNullOrWhiteSpace(lsTmp)) Axis_HomeVelLow = JArray.Parse(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeVelHigh"); + if (!string.IsNullOrWhiteSpace(lsTmp)) Axis_HomeVelHigh = JArray.Parse(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeAcc"); + if (!string.IsNullOrWhiteSpace(lsTmp)) Axis_HomeAcc = JArray.Parse(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeDec"); + if (!string.IsNullOrWhiteSpace(lsTmp)) Axis_HomeDec = JArray.Parse(lsTmp); + // + lsTmp = Util.ReadIniValue(configPath, "DEV", "Light_Name"); + if (Util.IsNumber(lsTmp)) Config.Light_Name = (LightDevNameEnum)Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Light_PortNum"); + if (Util.IsNumber(lsTmp)) Config.Light_PortNum = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Tension_PortNum"); + if (Util.IsNumber(lsTmp)) Config.Tension_PortNum = Convert.ToInt32(lsTmp); + Config.SmallAxis_ComName = Util.ReadIniValue(configPath, "DEV", "SmallAxis_ComName"); + + lsTmp = Util.ReadIniValue(configPath, "DEV", "Tension_Offset"); + if (string.IsNullOrEmpty(lsTmp)) + Config.Tension_Offset = 0; + else + Config.Tension_Offset = double.Parse(lsTmp); + + HeightDev_IP = Util.ReadIniValue(configPath, "DEV", "HeightDev_IP"); + lsTmp = Util.ReadIniValue(configPath, "DEV", "HeightDev_Port"); + if (Util.IsNumber(lsTmp)) Config.HeightDev_Port = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "DEV", "HeightDev_SafeValue"); + if (Util.IsNumber(lsTmp)) Config.HeightDev_SafeValue = Convert.ToDecimal(lsTmp); + + IOCard_DeviceNum = Util.ReadIniValue(configPath, "DEV", "IOCard_DeviceNum"); + + Defect_SavePath = Util.ReadIniValue(configPath, "DEV", "Defect_SavePath"); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_SavePath_AutoClear"); + if (Util.IsNumber(lsTmp)) Defect_SavePath_AutoClear = Convert.ToDouble(lsTmp); + Defect_Compress_SavePath = Util.ReadIniValue(configPath, "DEV", "Defect_Compress_SavePath"); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_Compress_SavePath_AutoClear"); + if (Util.IsNumber(lsTmp)) Defect_Compress_SavePath_AutoClear = Convert.ToDouble(lsTmp); + + Defect_Small_SavePath = Util.ReadIniValue(configPath, "DEV", "Defect_Small_SavePath"); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_Small_SavePath_AutoClear"); + if (Util.IsNumber(lsTmp)) Defect_Small_SavePath_AutoClear = Convert.ToDouble(lsTmp); + + lsTmp = Util.ReadIniValue(configPath, "DEV", "SaveAllDefectImg"); + SaveAllDefectImg = (lsTmp == "1"); + MakeTag = Util.ReadIniValue(configPath, "DEV", "MakeTag") == "1"; + SizeEnginePath = Util.ReadIniValue(configPath, "DEV", "SizeEnginePath"); + + SizeBmp_SavePath = Util.ReadIniValue(configPath, "DEV", "SizeBmp_SavePath"); + lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_SavePath_AutoClear"); + if (Util.IsNumber(lsTmp)) SizeBmp_SavePath_AutoClear = Convert.ToDouble(lsTmp); + + SizeBmp_Compare_SavePath = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath"); + lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath_AutoClear"); + if (Util.IsNumber(lsTmp)) SizeBmp_Compare_SavePath_AutoClear = Convert.ToDouble(lsTmp); + + SizeBmp_Zoom_Image_SavePath = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath"); + lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath_AutoClear"); + if (Util.IsNumber(lsTmp)) SizeBmp_Zoom_Image_SavePath_AutoClear = Convert.ToDouble(lsTmp); + //DB + DBConStr = Util.ReadIniValue(configPath, "DB", "DBConStr"); + //HTTP + LocalIp= Util.ReadIniValue(configPath, "HTTP", "LocalIp"); + lsTmp = Util.ReadIniValue(configPath, "HTTP", "LocalHttpPort"); + if (Util.IsNumber(lsTmp)) Config.LocalHttpPort = Convert.ToInt32(lsTmp); + lsTmp = Util.ReadIniValue(configPath, "HTTP", "LocalSocketPort"); + if (Util.IsNumber(lsTmp)) Config.LocalSocketPort = Convert.ToInt32(lsTmp); + //LOG + LogPath = Util.ReadIniValue(configPath, "LOG", "LogPath"); + + //缺陷配置 + Defect_CutSize = new Size(592, 532); + Defect_ReSize = new Size(224, 224); + Defect_Thresholds = 0.4f; + } + public static void LoadPTConfig() + { + if (string.IsNullOrWhiteSpace(appBasePath)) + appBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + string configPath = appBasePath + "\\PTConfig.json"; + string lsTmp = File.ReadAllText(configPath); + joPTSetting = JObject.Parse(lsTmp); + } + + private static void InitDevDic() + { + //dicDevType.Add("CodeScanner", "扫码枪");//固定为必有开始 + if(!dicDevType.ContainsKey("IOCard")) dicDevType.Add("IOCard", "I/O控制"); + if (!dicDevType.ContainsKey("Tension")) dicDevType.Add("Tension", "张力测量"); + if (!dicDevType.ContainsKey("Height")) dicDevType.Add("Height", "厚度测量"); + if (!dicDevType.ContainsKey("Axis")) dicDevType.Add("Axis", "滑台电机"); + if (!dicDevType.ContainsKey("AxisTag")) dicDevType.Add("AxisTag", "滑台&测量"); + if (!dicDevType.ContainsKey("Light")) dicDevType.Add("Light", "光源"); + if (!dicDevType.ContainsKey("Scanner_GENTL")) dicDevType.Add("Scanner_GENTL", "相机GENTL"); + if (!dicDevType.ContainsKey("Scanner_CC")) dicDevType.Add("Scanner_CC", "相机CC"); + if (!dicDevType.ContainsKey("SmallAxis")) dicDevType.Add("SmallAxis", "镜头电机"); + if (!dicDevType.ContainsKey("Defect")) dicDevType.Add("Defect", "缺陷检测"); + if (!dicDevType.ContainsKey("Size")) dicDevType.Add("Size", "尺寸测量"); + if (!dicDevType.ContainsKey("For")) dicDevType.Add("For", "For循环"); + if (!dicDevType.ContainsKey("If")) dicDevType.Add("If", "If条件"); + } + + private static void CreateSysFolder() + { + appBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + string dirPath = appBasePath + "\\Attachment\\"; + if(!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); + + dirPath = appBasePath + "\\Temp\\"; + if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); + } + /// + /// + /// + /// + /// + /// 把日期文件夹也按days进行删除,格式:yyyyMMdd + private static void DeleteFiles(string dirPath,double days=0,bool delDir=false) + { + if (!Directory.Exists(dirPath)) return; + DateTime delDate = DateTime.Now.AddDays(-days); + API.OutputDebugString($"清除{delDate.ToString("yyyyMMdd")}前记录:{dirPath}。"); + string[] file_list = Directory.GetFiles(dirPath); + if(days>0) + file_list = file_list.Select(file => new FileInfo(file)) + .Where(f=>f.CreationTime<= delDate) + .Select(x => x.FullName) + .ToArray(); + + foreach (string file in file_list) + { + try { + API.OutputDebugString($"清除文件:{file}..."); + File.Delete(file); + } catch(Exception ex) { + API.OutputDebugString($"Ex1:{ex.Message}"); + } + } + + // + if (delDir) + { + int dateNum = Convert.ToInt32(delDate.ToString("yyyyMMdd")); + string floderName; + string[] dirList = Directory.GetDirectories(dirPath,"20*"); + foreach (string dir in dirList) + { + floderName= dir.Trim('\\'); + floderName = floderName.Substring(floderName.LastIndexOf('\\') + 1); + if (floderName.Length == 8 && Util.IsNumber(floderName) && Convert.ToInt32(floderName) <= dateNum) + { + try + { + API.OutputDebugString($"清除目录:{dir}..."); + Directory.Delete(dir,true); + } + catch (Exception ex) + { + API.OutputDebugString($"Ex2:{ex.Message}"); + } + } + } + } + + } + } +} diff --git a/halftoneproject-master/Code/Device/DefectLib.cs b/halftoneproject-master/Code/Device/DefectLib.cs index d34a3f5..f4f95f4 100644 --- a/halftoneproject-master/Code/Device/DefectLib.cs +++ b/halftoneproject-master/Code/Device/DefectLib.cs @@ -279,9 +279,12 @@ namespace ProductionControl.Device task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk); liStep = 5; - //大图缺陷坐标转换到图纸坐标 - if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0) - task.defectInfor2RestorationDeskPage = yolo1.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk); + if (Config.OpenFlawDistribution) + { + //大图缺陷坐标转换到图纸坐标 + if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0) + task.defectInfor2RestorationDeskPage = yolo1.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk); + } stopwatch.Stop(); task.stopwatch[4] = stopwatch.ElapsedMilliseconds; diff --git a/halftoneproject-master/Code/Device/SizeLib.cs b/halftoneproject-master/Code/Device/SizeLib.cs index b20a105..09adf60 100644 --- a/halftoneproject-master/Code/Device/SizeLib.cs +++ b/halftoneproject-master/Code/Device/SizeLib.cs @@ -1,391 +1,395 @@ -using HalconDotNet; -using Microsoft.ML.OnnxRuntime; -using Microsoft.ML.OnnxRuntime.Tensors; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenCvSharp; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Yolo5; - -namespace ProductionControl.Device -{ - public class SizeLib : IDisposable - { - public Action WarningEvent; - /// - /// 检测结果JSON(原图,结果) - /// - public Action finishEvent; - /// - /// 是否打开设备成功 - /// - public bool IsInit { get; private set; } = false; - //private System.Timers.Timer timer = new System.Timers.Timer(); - - //配置 - HDevEngine MyEngine = new HDevEngine(); - - //777时用 - Yolo_Class yolo5 =new Yolo_Class(); - - private Thread t_task; - public SizeLib() - { - } - public bool start(string enginePath) - { - try - { - IsInit = true; - taskList.Clear(); - MyEngine.SetProcedurePath(enginePath); - - t_task = new System.Threading.Thread(run); - t_task.IsBackground = true; - t_task.Start(); - return true; - } - catch (Exception ex) - { - WarningEvent?.Invoke(WarningEnum.High,ex.Message); - return false; - } - } - public void stop() - { - if (!IsInit) return; - - try - { - IsInit = false; - //timer.Elapsed -= Timer_Elapsed; - - MyEngine.Dispose(); - } - catch { } - - } - - private bool _debug = false; - public bool setDebug { - get { return _debug; } - set { - if (!IsInit) return; - - _debug=value; - if (_debug) - MyEngine.StartDebugServer(); - else - MyEngine.StopDebugServer(); - } - } - //流程:111,222,444,333,777,777,777,。。。 - - private void run() - { - int taskCount; - while (IsInit) - { - lock (taskList) - { - taskCount = taskList.Count; - } - if (taskCount < 1) - { - Thread.Sleep(10); - continue; - } - - //// - int step = 0; - var task = pop(); - try - { - if (task != null) - { - var Program1 = new HDevProcedure(task.engineName); - HDevProcedureCall ProcCall1_PI_PT = new HDevProcedureCall(Program1); - step = 1; - // - HObject image; - if (task.bmp != null) - Bitmap2HObjectBpp24(out image, task.bmp); - else - HOperatorSet.ReadImage(out image, task.file_path); - step = 2; - //设置外部函数输入 - //if (task.index < 100) - { - ProcCall1_PI_PT.SetInputIconicParamObject("Image1", image.Clone()); - ProcCall1_PI_PT.SetInputCtrlParamTuple("index", task.index);//参数1-9 - ProcCall1_PI_PT.SetInputCtrlParamTuple("posX", task.posX); - ProcCall1_PI_PT.SetInputCtrlParamTuple("posY", task.posY); - ProcCall1_PI_PT.SetInputCtrlParamTuple("GerberPath",new HTuple( task.drawingPagePath));//美尚没有 - - //设置外部函数输入 - if ((task.PTandLinePos != null) && (task.PTandLinePos[0] != 0)) - { - double[] posarray = new double[23]; - posarray[0] = task.PTandLinePos[0]; - posarray[1] = task.PTandLinePos[2]; - posarray[2] = task.PTandLinePos[4]; - posarray[3] = task.PTandLinePos[6]; - posarray[4] = task.PTandLinePos[8]; - for (int i = 0; i < 18; i++) - { - posarray[5 + i] = task.PTandLinePos[10 + i]; +using HalconDotNet; +using Microsoft.ML.OnnxRuntime; +using Microsoft.ML.OnnxRuntime.Tensors; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OpenCvSharp; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Yolo5; + +namespace ProductionControl.Device +{ + public class SizeLib : IDisposable + { + public Action WarningEvent; + /// + /// 检测结果JSON(原图,结果) + /// + public Action finishEvent; + /// + /// 是否打开设备成功 + /// + public bool IsInit { get; private set; } = false; + //private System.Timers.Timer timer = new System.Timers.Timer(); + + //配置 + HDevEngine MyEngine = new HDevEngine(); + + //777时用 + Yolo_Class yolo5 =new Yolo_Class(); + + private Thread t_task; + public SizeLib() + { + } + public bool start(string enginePath) + { + try + { + IsInit = true; + taskList.Clear(); + MyEngine.SetProcedurePath(enginePath); + + t_task = new System.Threading.Thread(run); + t_task.IsBackground = true; + t_task.Start(); + return true; + } + catch (Exception ex) + { + WarningEvent?.Invoke(WarningEnum.High,ex.Message); + return false; + } + } + public void stop() + { + if (!IsInit) return; + + try + { + IsInit = false; + //timer.Elapsed -= Timer_Elapsed; + + MyEngine.Dispose(); + } + catch { } + + } + + private bool _debug = false; + public bool setDebug { + get { return _debug; } + set { + if (!IsInit) return; + + _debug=value; + if (_debug) + MyEngine.StartDebugServer(); + else + MyEngine.StopDebugServer(); + } + } + //流程:111,222,444,333,777,777,777,。。。 + + private void run() + { + int taskCount; + while (IsInit) + { + lock (taskList) + { + taskCount = taskList.Count; + } + if (taskCount < 1) + { + Thread.Sleep(10); + continue; + } + + //// + int step = 0; + var task = pop(); + try + { + if (task != null) + { + var Program1 = new HDevProcedure(task.engineName); + HDevProcedureCall ProcCall1_PI_PT = new HDevProcedureCall(Program1); + step = 1; + // + HObject image; + if (task.bmp != null) + Bitmap2HObjectBpp24(out image, task.bmp); + else + HOperatorSet.ReadImage(out image, task.file_path); + step = 2; + //设置外部函数输入 + //if (task.index < 100) + { + ProcCall1_PI_PT.SetInputIconicParamObject("Image1", image.Clone()); + ProcCall1_PI_PT.SetInputCtrlParamTuple("index", task.index);//参数1-9 + ProcCall1_PI_PT.SetInputCtrlParamTuple("posX", task.posX); + ProcCall1_PI_PT.SetInputCtrlParamTuple("posY", task.posY); + ProcCall1_PI_PT.SetInputCtrlParamTuple("GerberPath",new HTuple( task.drawingPagePath));//美尚没有 + + //设置外部函数输入 + if ((task.PTandLinePos != null) && (task.PTandLinePos[0] != 0)) + { + double[] posarray = new double[23]; + posarray[0] = task.PTandLinePos[0]; + posarray[1] = task.PTandLinePos[2]; + posarray[2] = task.PTandLinePos[4]; + posarray[3] = task.PTandLinePos[6]; + posarray[4] = task.PTandLinePos[8]; + for (int i = 0; i < 18; i++) + { + posarray[5 + i] = task.PTandLinePos[10 + i]; } - ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", posarray); - ///// - /// - //string directory = Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\"; - //if (!System.IO.Directory.Exists(directory)) - // System.IO.Directory.CreateDirectory(directory); - - //File.AppendAllText(directory + "sizeData.log", "data:" + string.Join(",", posarray) + "\r\n"); - } - else - { - double[] posarray = new double[23]; - ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", posarray); - } - } - if (task.index == 777) - { - ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", task.ContoursAffineTrans1_Out); - } - else - { - HObject ContoursAffineTrans1; - HOperatorSet.GenEmptyObj(out ContoursAffineTrans1); - ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", ContoursAffineTrans1); - } - - - step = 3; - ProcCall1_PI_PT.Execute();//执行外部函数 - step = 4; - //获取外部函数输出 - switch (task.index) - { - case 777://比对结果 - step = 10; - task.CompResult = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RES") == 1;//结果,1为true,0为false - step = 11; - if (!task.CompResult) - { - var Defects_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_X"); - var Defects_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Y"); - var Defects_LeftTop_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_LeftTop_X"); - var Defects_LeftTop_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_LeftTop_Y"); - var Defects_RightBottom_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_RightBottom_X"); - var Defects_RightBottom_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_RightBottom_Y"); - var Contour_Image = ProcCall1_PI_PT.GetOutputIconicParamObject("Contour_Image"); - //var Zoom_Image = ProcCall1_PI_PT.GetOutputIconicParamObject("Zoom_Image"); - - var Defects_Type = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Type"); - var Defects_Index = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Index"); - - step = 12; - //对比打标图:显示在UI上,以后修复台用 - //task.Zoom_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, Zoom_Image, Defects_LeftTop_X, Defects_LeftTop_Y, Defects_RightBottom_X, Defects_RightBottom_Y); - //新YOLO.DLL - task.defectInfor2RestorationDesk = new List>(); - task.Zoom_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, image, Defects_LeftTop_X, Defects_LeftTop_Y, - Defects_RightBottom_X, Defects_RightBottom_Y, Defects_Type, Defects_Index, Defects_X, Defects_Y, out task.defectInfor2RestorationDesk); - //WarningEvent?.Invoke(WarningEnum.Normal, $"SizeLib 777 call DrawContour_Opencv(),Defects_LeftTop_X={Defects_LeftTop_X}," + - // $"Defects_LeftTop_Y={Defects_LeftTop_Y},Defects_RightBottom_X={Defects_RightBottom_X},Defects_RightBottom_Y={Defects_RightBottom_Y}," + - // $"Defects_Type={Defects_Type},Defects_Index={Defects_Index},Defects_X={Defects_X},Defects_Y={Defects_Y}," + - // $"defectInfor2RestorationDesk={JsonConvert.SerializeObject(task.defectInfor2RestorationDesk)}"); - step = 13; - task.Zoom_Image_mat = yolo5.ResizesMat_4(task.Zoom_Image_mat); - - //大图缺陷坐标转换到图纸坐标 - step = 14; - if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0) - task.defectInfor2RestorationDeskPage = yolo5.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk); - } - break; - case 111: - task.MarkPointList[0] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_1"); - task.MarkPointList[1] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_1"); - break; - case 222: - task.MarkPointList[2] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_2"); - task.MarkPointList[3] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_2"); - break; - case 333: - task.MarkPointList[4] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_3"); - task.MarkPointList[5] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_3");//ContoursAffineTrans1 - task.ContoursAffineTrans1_Out = ProcCall1_PI_PT.GetOutputIconicParamObject("ContoursAffineTrans1_Out"); - break; - case 444: - task.MarkPointList[6] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_4"); - task.MarkPointList[7] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_4"); - break; - case 3333: //Tag使用,同时继续获取使用default时时校正和其它值 - step = 80; - if (!string.IsNullOrWhiteSpace( task.sizeTag)) - task.posePT= ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr; - goto default; - default: - step = 90; - task.PT1 = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT1");//index=8 PT1=PT2 - task.PT2 = ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT2"); - task.Shanxian = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Distance3Median"); - //task.RowP = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RowP"); - task.Circle_Ymm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Ymm"); - task.Circle_Xmm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Xmm"); - task.offsetX = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetX"); - task.offsetY = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetY"); - break; - } - step = 100; - ProcCall1_PI_PT.Dispose(); - Program1.Dispose(); - - step = 101; - task.isSucceed = true; - task.resultInfo = "成功"; - callback(task); - step = 102; - } - Thread.Sleep(5); - } - catch (Exception ex) - { - WarningEvent?.Invoke(WarningEnum.Low, $"SizeLib task err({step}) index({task.index}):"+ ex.Message); - task.isSucceed = false; - task.resultInfo = $"(errcode:{step}):{ex.Message}"; - callback(task); - } - } - } - private void callback(SizeTask task) - { - //返回成功/失败,异步调用 - if (task.finishEvent != null || (task.finishEvent = finishEvent) != null) - //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null); - System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task); - } - //异步回调 - WaitCallback waitCallback = new WaitCallback(o => { - var task = (SizeTask)o; - task.finishEvent(task); - }); - //=======task list - private List taskList = new List(); - public class SizeTask - { - public int stepIndex;//只为回调记录当前工序信息 - public string processName;//只为回调记录当前工序信息 - - public string engineName,sizeTag; - /// - /// 源文件 - /// - public string file_path; - public double posX,posY; - public Bitmap bmp; + ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", posarray); + ///// + /// + //string directory = Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\"; + //if (!System.IO.Directory.Exists(directory)) + // System.IO.Directory.CreateDirectory(directory); + + //File.AppendAllText(directory + "sizeData.log", "data:" + string.Join(",", posarray) + "\r\n"); + } + else + { + double[] posarray = new double[23]; + ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", posarray); + } + } + if (task.index == 777) + { + ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", task.ContoursAffineTrans1_Out); + } + else + { + HObject ContoursAffineTrans1; + HOperatorSet.GenEmptyObj(out ContoursAffineTrans1); + ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", ContoursAffineTrans1); + } + + + step = 3; + ProcCall1_PI_PT.Execute();//执行外部函数 + step = 4; + //获取外部函数输出 + switch (task.index) + { + case 777://比对结果 + step = 10; + task.CompResult = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RES") == 1;//结果,1为true,0为false + step = 11; + if (!task.CompResult) + { + var Defects_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_X"); + var Defects_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Y"); + var Defects_LeftTop_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_LeftTop_X"); + var Defects_LeftTop_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_LeftTop_Y"); + var Defects_RightBottom_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_RightBottom_X"); + var Defects_RightBottom_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_RightBottom_Y"); + var Contour_Image = ProcCall1_PI_PT.GetOutputIconicParamObject("Contour_Image"); + //var Zoom_Image = ProcCall1_PI_PT.GetOutputIconicParamObject("Zoom_Image"); + + var Defects_Type = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Type"); + var Defects_Index = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Index"); + + step = 12; + //对比打标图:显示在UI上,以后修复台用 + //task.Zoom_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, Zoom_Image, Defects_LeftTop_X, Defects_LeftTop_Y, Defects_RightBottom_X, Defects_RightBottom_Y); + //新YOLO.DLL + task.defectInfor2RestorationDesk = new List>(); + task.Zoom_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, image, Defects_LeftTop_X, Defects_LeftTop_Y, + Defects_RightBottom_X, Defects_RightBottom_Y, Defects_Type, Defects_Index, Defects_X, Defects_Y, out task.defectInfor2RestorationDesk); + //WarningEvent?.Invoke(WarningEnum.Normal, $"SizeLib 777 call DrawContour_Opencv(),Defects_LeftTop_X={Defects_LeftTop_X}," + + // $"Defects_LeftTop_Y={Defects_LeftTop_Y},Defects_RightBottom_X={Defects_RightBottom_X},Defects_RightBottom_Y={Defects_RightBottom_Y}," + + // $"Defects_Type={Defects_Type},Defects_Index={Defects_Index},Defects_X={Defects_X},Defects_Y={Defects_Y}," + + // $"defectInfor2RestorationDesk={JsonConvert.SerializeObject(task.defectInfor2RestorationDesk)}"); + step = 13; + task.Zoom_Image_mat = yolo5.ResizesMat_4(task.Zoom_Image_mat); + + //大图缺陷坐标转换到图纸坐标 + step = 14; + if (Config.OpenFlawDistribution) + { + if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0) + task.defectInfor2RestorationDeskPage = yolo5.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk); + + } + } + break; + case 111: + task.MarkPointList[0] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_1"); + task.MarkPointList[1] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_1"); + break; + case 222: + task.MarkPointList[2] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_2"); + task.MarkPointList[3] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_2"); + break; + case 333: + task.MarkPointList[4] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_3"); + task.MarkPointList[5] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_3");//ContoursAffineTrans1 + task.ContoursAffineTrans1_Out = ProcCall1_PI_PT.GetOutputIconicParamObject("ContoursAffineTrans1_Out"); + break; + case 444: + task.MarkPointList[6] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_4"); + task.MarkPointList[7] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_4"); + break; + case 3333: //Tag使用,同时继续获取使用default时时校正和其它值 + step = 80; + if (!string.IsNullOrWhiteSpace( task.sizeTag)) + task.posePT= ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr; + goto default; + default: + step = 90; + task.PT1 = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT1");//index=8 PT1=PT2 + task.PT2 = ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT2"); + task.Shanxian = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Distance3Median"); + //task.RowP = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RowP"); + task.Circle_Ymm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Ymm"); + task.Circle_Xmm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Xmm"); + task.offsetX = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetX"); + task.offsetY = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetY"); + break; + } + step = 100; + ProcCall1_PI_PT.Dispose(); + Program1.Dispose(); + + step = 101; + task.isSucceed = true; + task.resultInfo = "成功"; + callback(task); + step = 102; + } + Thread.Sleep(5); + } + catch (Exception ex) + { + WarningEvent?.Invoke(WarningEnum.Low, $"SizeLib task err({step}) index({task.index}):"+ ex.Message); + task.isSucceed = false; + task.resultInfo = $"(errcode:{step}):{ex.Message}"; + callback(task); + } + } + } + private void callback(SizeTask task) + { + //返回成功/失败,异步调用 + if (task.finishEvent != null || (task.finishEvent = finishEvent) != null) + //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null); + System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task); + } + //异步回调 + WaitCallback waitCallback = new WaitCallback(o => { + var task = (SizeTask)o; + task.finishEvent(task); + }); + //=======task list + private List taskList = new List(); + public class SizeTask + { + public int stepIndex;//只为回调记录当前工序信息 + public string processName;//只为回调记录当前工序信息 + + public string engineName,sizeTag; + /// + /// 源文件 + /// + public string file_path; + public double posX,posY; + public Bitmap bmp; public string drawingPagePath = "";//.gbx图纸路径 //2023-10-27 新增图纸选择pt点位与线宽点位 - public double[] PTandLinePos; - /// - /// 比对(index=777); 计算Mark(111/222/333/444); 尺寸(1-9); 轴偏移调整(10,20,30...) - /// - public int index; //index=8 PT1=PT2 - /// - /// 完成后回调 - /// - public Action finishEvent; - public long createTime = DateTime.Now.Ticks; - - //==结果返回 - /// - /// 比对结果(index=777) - /// - public bool CompResult; - public Mat Zoom_Image_mat;//对比打标图:777比对失败时计算得出,后面显示到UI 以后修复台用 - public List> defectInfor2RestorationDesk, defectInfor2RestorationDeskPage;//对比未通过坐标信息,合并到缺陷检测中的 //打标缺陷转为图纸的坐标; - //MARK点 - public double[] MarkPointList = { 0, 0, 0, 0, 0, 0, 0, 0 }; - public HObject ContoursAffineTrans1_Out;//index=333时输出,供后面多个777比对时输入使用 - public double[] posePT;//index=3333 && !isEmpty(sizeTag) 才取此数组值,len为0时急停 - // - public double PT1,PT2, Shanxian, Circle_Ymm, Circle_Xmm, offsetX, offsetY; - public bool isSucceed;//转换是否成功 - public string resultInfo = "";//成功或失败信息 - } - - public void add(SizeTask task) - { - lock (taskList) - taskList.Add(task); - } - private SizeTask pop() - { - lock (taskList) - { - if (taskList.Count < 1) - return null; - - var task = taskList[0]; - taskList.RemoveAt(0); - return task; - } - } - - public void Dispose() - { - stop(); - } - /// - /// Bitmap转HObject灰度图 - /// - /// Bitmap图像 - /// HObject图像 - private void Bitmap2HObjectBpp8( out HObject image,Bitmap bmp) - { - try - { - Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); - - BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); - - HOperatorSet.GenImage1(out image, "byte", bmp.Width, bmp.Height, srcBmpData.Scan0); - bmp.UnlockBits(srcBmpData); - } - catch (Exception) - { - image = null; - } - } - public void Bitmap2HObjectBpp24( out HObject image, Bitmap bmp) - { - try - { - Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); - - BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); - HOperatorSet.GenImageInterleaved(out image, srcBmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0); - bmp.UnlockBits(srcBmpData); - - } - catch (Exception ex) - { - image = null; - } - } - } -} + public double[] PTandLinePos; + /// + /// 比对(index=777); 计算Mark(111/222/333/444); 尺寸(1-9); 轴偏移调整(10,20,30...) + /// + public int index; //index=8 PT1=PT2 + /// + /// 完成后回调 + /// + public Action finishEvent; + public long createTime = DateTime.Now.Ticks; + + //==结果返回 + /// + /// 比对结果(index=777) + /// + public bool CompResult; + public Mat Zoom_Image_mat;//对比打标图:777比对失败时计算得出,后面显示到UI 以后修复台用 + public List> defectInfor2RestorationDesk, defectInfor2RestorationDeskPage;//对比未通过坐标信息,合并到缺陷检测中的 //打标缺陷转为图纸的坐标; + //MARK点 + public double[] MarkPointList = { 0, 0, 0, 0, 0, 0, 0, 0 }; + public HObject ContoursAffineTrans1_Out;//index=333时输出,供后面多个777比对时输入使用 + public double[] posePT;//index=3333 && !isEmpty(sizeTag) 才取此数组值,len为0时急停 + // + public double PT1,PT2, Shanxian, Circle_Ymm, Circle_Xmm, offsetX, offsetY; + public bool isSucceed;//转换是否成功 + public string resultInfo = "";//成功或失败信息 + } + + public void add(SizeTask task) + { + lock (taskList) + taskList.Add(task); + } + private SizeTask pop() + { + lock (taskList) + { + if (taskList.Count < 1) + return null; + + var task = taskList[0]; + taskList.RemoveAt(0); + return task; + } + } + + public void Dispose() + { + stop(); + } + /// + /// Bitmap转HObject灰度图 + /// + /// Bitmap图像 + /// HObject图像 + private void Bitmap2HObjectBpp8( out HObject image,Bitmap bmp) + { + try + { + Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); + + BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); + + HOperatorSet.GenImage1(out image, "byte", bmp.Width, bmp.Height, srcBmpData.Scan0); + bmp.UnlockBits(srcBmpData); + } + catch (Exception) + { + image = null; + } + } + public void Bitmap2HObjectBpp24( out HObject image, Bitmap bmp) + { + try + { + Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); + + BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); + HOperatorSet.GenImageInterleaved(out image, srcBmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0); + bmp.UnlockBits(srcBmpData); + + } + catch (Exception ex) + { + image = null; + } + } + } +} diff --git a/halftoneproject-master/Code/FrmInput.Designer.cs b/halftoneproject-master/Code/FrmInput.Designer.cs index c56032d..7402509 100644 --- a/halftoneproject-master/Code/FrmInput.Designer.cs +++ b/halftoneproject-master/Code/FrmInput.Designer.cs @@ -28,75 +28,80 @@ /// private void InitializeComponent() { - this.btnOK = new System.Windows.Forms.Button(); - this.btnCancel = new System.Windows.Forms.Button(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.cobList = new System.Windows.Forms.ComboBox(); - this.SuspendLayout(); - // - // btnOK - // - this.btnOK.Location = new System.Drawing.Point(358, 85); - this.btnOK.Name = "btnOK"; - this.btnOK.Size = new System.Drawing.Size(80, 30); - this.btnOK.TabIndex = 0; - this.btnOK.Text = "确认"; - this.btnOK.UseVisualStyleBackColor = true; - this.btnOK.Click += new System.EventHandler(this.btnOK_Click); - // - // btnCancel - // - this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.btnCancel.Location = new System.Drawing.Point(454, 85); - this.btnCancel.Name = "btnCancel"; - this.btnCancel.Size = new System.Drawing.Size(80, 30); - this.btnCancel.TabIndex = 0; - this.btnCancel.Text = "取消"; - this.btnCancel.UseVisualStyleBackColor = true; - // - // textBox1 - // - this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; - this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource; - this.textBox1.ImeMode = System.Windows.Forms.ImeMode.Disable; - this.textBox1.Location = new System.Drawing.Point(12, 22); - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(524, 28); - this.textBox1.TabIndex = 1; - // - // cobList - // - this.cobList.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - this.cobList.FormattingEnabled = true; - this.cobList.Location = new System.Drawing.Point(12, 22); - this.cobList.Name = "cobList"; - this.cobList.Size = new System.Drawing.Size(522, 26); - this.cobList.TabIndex = 2; - // - // FrmInput - // - this.AcceptButton = this.btnOK; - this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.CancelButton = this.btnCancel; - this.ClientSize = new System.Drawing.Size(548, 123); - this.Controls.Add(this.cobList); - this.Controls.Add(this.textBox1); - this.Controls.Add(this.btnCancel); - this.Controls.Add(this.btnOK); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "FrmInput"; - this.ShowIcon = false; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "请输入"; - this.TopMost = true; - this.Load += new System.EventHandler(this.FrmInput_Load); - this.Shown += new System.EventHandler(this.FrmInput_Shown); - this.ResumeLayout(false); - this.PerformLayout(); - + this.btnOK = new System.Windows.Forms.Button(); + this.btnCancel = new System.Windows.Forms.Button(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.cobList = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // btnOK + // + this.btnOK.Location = new System.Drawing.Point(239, 57); + this.btnOK.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.btnOK.Name = "btnOK"; + this.btnOK.Size = new System.Drawing.Size(53, 20); + this.btnOK.TabIndex = 0; + this.btnOK.Text = "确认"; + this.btnOK.UseVisualStyleBackColor = true; + this.btnOK.Click += new System.EventHandler(this.btnOK_Click); + // + // btnCancel + // + this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.btnCancel.Location = new System.Drawing.Point(303, 57); + this.btnCancel.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.btnCancel.Name = "btnCancel"; + this.btnCancel.Size = new System.Drawing.Size(53, 20); + this.btnCancel.TabIndex = 0; + this.btnCancel.Text = "取消"; + this.btnCancel.UseVisualStyleBackColor = true; + // + // textBox1 + // + this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; + this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource; + this.textBox1.ImeMode = System.Windows.Forms.ImeMode.Disable; + this.textBox1.Location = new System.Drawing.Point(8, 15); + this.textBox1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(351, 21); + this.textBox1.TabIndex = 1; + // + // cobList + // + this.cobList.FlatStyle = System.Windows.Forms.FlatStyle.Popup; + this.cobList.FormattingEnabled = true; + this.cobList.Location = new System.Drawing.Point(8, 15); + this.cobList.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.cobList.Name = "cobList"; + this.cobList.Size = new System.Drawing.Size(349, 20); + this.cobList.TabIndex = 2; + // + // FrmInput + // + this.AcceptButton = this.btnOK; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.btnCancel; + this.ClientSize = new System.Drawing.Size(365, 82); + this.Controls.Add(this.cobList); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.btnCancel); + this.Controls.Add(this.btnOK); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "FrmInput"; + this.ShowIcon = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "请输入"; + this.TopMost = true; + this.Load += new System.EventHandler(this.FrmInput_Load); + this.Shown += new System.EventHandler(this.FrmInput_Shown); + this.ResumeLayout(false); + this.PerformLayout(); + } #endregion diff --git a/halftoneproject-master/Code/FrmInput.resx b/halftoneproject-master/Code/FrmInput.resx index 1af7de1..29dcb1b 100644 --- a/halftoneproject-master/Code/FrmInput.resx +++ b/halftoneproject-master/Code/FrmInput.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + \ No newline at end of file diff --git a/halftoneproject-master/Code/FrmLogin.Designer.cs b/halftoneproject-master/Code/FrmLogin.Designer.cs index c1f5d2f..2e501f5 100644 --- a/halftoneproject-master/Code/FrmLogin.Designer.cs +++ b/halftoneproject-master/Code/FrmLogin.Designer.cs @@ -44,7 +44,7 @@ // btnLogin // this.btnLogin.Location = new System.Drawing.Point(131, 181); - this.btnLogin.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.btnLogin.Margin = new System.Windows.Forms.Padding(2); this.btnLogin.Name = "btnLogin"; this.btnLogin.Size = new System.Drawing.Size(75, 23); this.btnLogin.TabIndex = 5; @@ -56,7 +56,7 @@ // this.chkRememberPw.AutoSize = true; this.chkRememberPw.Location = new System.Drawing.Point(203, 155); - this.chkRememberPw.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.chkRememberPw.Margin = new System.Windows.Forms.Padding(2); this.chkRememberPw.Name = "chkRememberPw"; this.chkRememberPw.Size = new System.Drawing.Size(72, 16); this.chkRememberPw.TabIndex = 3; @@ -68,7 +68,7 @@ // this.chkRememberUserCode.AutoSize = true; this.chkRememberUserCode.Location = new System.Drawing.Point(90, 155); - this.chkRememberUserCode.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.chkRememberUserCode.Margin = new System.Windows.Forms.Padding(2); this.chkRememberUserCode.Name = "chkRememberUserCode"; this.chkRememberUserCode.Size = new System.Drawing.Size(84, 16); this.chkRememberUserCode.TabIndex = 4; @@ -80,7 +80,7 @@ // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(0, 1); - this.pictureBox1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.pictureBox1.Margin = new System.Windows.Forms.Padding(2); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(359, 95); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; @@ -90,7 +90,7 @@ // txtUserPw // this.txtUserPw.Location = new System.Drawing.Point(90, 133); - this.txtUserPw.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.txtUserPw.Margin = new System.Windows.Forms.Padding(2); this.txtUserPw.MaxLength = 16; this.txtUserPw.Name = "txtUserPw"; this.txtUserPw.PasswordChar = '*'; @@ -110,7 +110,7 @@ // txtUserCode // this.txtUserCode.Location = new System.Drawing.Point(90, 105); - this.txtUserCode.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.txtUserCode.Margin = new System.Windows.Forms.Padding(2); this.txtUserCode.Name = "txtUserCode"; this.txtUserCode.Size = new System.Drawing.Size(185, 21); this.txtUserCode.TabIndex = 1; @@ -128,7 +128,7 @@ // button2 // this.button2.Location = new System.Drawing.Point(281, 181); - this.button2.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.button2.Margin = new System.Windows.Forms.Padding(2); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(56, 23); this.button2.TabIndex = 9; @@ -153,13 +153,13 @@ this.Controls.Add(this.button2); this.Controls.Add(this.btnLogin); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.Margin = new System.Windows.Forms.Padding(2); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FrmLogin"; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "自动化视觉检测系统 - v1.2"; + this.Text = "自动化视觉检测系统 - v1.2.1"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FrmLogin_FormClosed); this.Load += new System.EventHandler(this.FrmLogin_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); diff --git a/halftoneproject-master/Code/FrmMain.Designer.cs b/halftoneproject-master/Code/FrmMain.Designer.cs index ad34aa3..8aa8941 100644 --- a/halftoneproject-master/Code/FrmMain.Designer.cs +++ b/halftoneproject-master/Code/FrmMain.Designer.cs @@ -30,11 +30,11 @@ { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain)); - System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle11 = new System.Windows.Forms.DataGridViewCellStyle(); - System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle14 = new System.Windows.Forms.DataGridViewCellStyle(); - System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle15 = new System.Windows.Forms.DataGridViewCellStyle(); - System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle12 = new System.Windows.Forms.DataGridViewCellStyle(); - System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle13 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.管理HToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.流程管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -700,7 +700,7 @@ this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer1.Location = new System.Drawing.Point(0, 80); - this.splitContainer1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.splitContainer1.Margin = new System.Windows.Forms.Padding(2); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 @@ -730,9 +730,9 @@ this.gpbProcessList.BackColor = System.Drawing.SystemColors.ActiveCaption; this.gpbProcessList.Controls.Add(this.dgvProcess); this.gpbProcessList.Location = new System.Drawing.Point(2, 202); - this.gpbProcessList.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.gpbProcessList.Margin = new System.Windows.Forms.Padding(2); this.gpbProcessList.Name = "gpbProcessList"; - this.gpbProcessList.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.gpbProcessList.Padding = new System.Windows.Forms.Padding(2); this.gpbProcessList.Size = new System.Drawing.Size(504, 159); this.gpbProcessList.TabIndex = 3; this.gpbProcessList.TabStop = false; @@ -742,37 +742,37 @@ // this.dgvProcess.AllowUserToAddRows = false; this.dgvProcess.AllowUserToDeleteRows = false; - dataGridViewCellStyle11.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; - dataGridViewCellStyle11.BackColor = System.Drawing.SystemColors.Control; - dataGridViewCellStyle11.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - dataGridViewCellStyle11.ForeColor = System.Drawing.SystemColors.WindowText; - dataGridViewCellStyle11.SelectionBackColor = System.Drawing.SystemColors.Highlight; - dataGridViewCellStyle11.SelectionForeColor = System.Drawing.SystemColors.HighlightText; - dataGridViewCellStyle11.WrapMode = System.Windows.Forms.DataGridViewTriState.True; - this.dgvProcess.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle11; + dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control; + dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText; + dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; + this.dgvProcess.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.dgvProcess.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvProcess.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colCode, this.colProcessName, this.colValue}); - dataGridViewCellStyle14.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; - dataGridViewCellStyle14.BackColor = System.Drawing.SystemColors.Window; - dataGridViewCellStyle14.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - dataGridViewCellStyle14.ForeColor = System.Drawing.SystemColors.ControlText; - dataGridViewCellStyle14.SelectionBackColor = System.Drawing.SystemColors.Highlight; - dataGridViewCellStyle14.SelectionForeColor = System.Drawing.SystemColors.HighlightText; - dataGridViewCellStyle14.WrapMode = System.Windows.Forms.DataGridViewTriState.False; - this.dgvProcess.DefaultCellStyle = dataGridViewCellStyle14; + dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Window; + dataGridViewCellStyle4.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + dataGridViewCellStyle4.ForeColor = System.Drawing.SystemColors.ControlText; + dataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.False; + this.dgvProcess.DefaultCellStyle = dataGridViewCellStyle4; this.dgvProcess.Dock = System.Windows.Forms.DockStyle.Fill; this.dgvProcess.Location = new System.Drawing.Point(2, 16); - this.dgvProcess.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.dgvProcess.Margin = new System.Windows.Forms.Padding(2); this.dgvProcess.MultiSelect = false; this.dgvProcess.Name = "dgvProcess"; this.dgvProcess.ReadOnly = true; this.dgvProcess.RowHeadersVisible = false; this.dgvProcess.RowHeadersWidth = 62; - dataGridViewCellStyle15.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.dgvProcess.RowsDefaultCellStyle = dataGridViewCellStyle15; + dataGridViewCellStyle5.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.dgvProcess.RowsDefaultCellStyle = dataGridViewCellStyle5; this.dgvProcess.RowTemplate.Height = 30; this.dgvProcess.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgvProcess.Size = new System.Drawing.Size(500, 141); @@ -792,9 +792,9 @@ // colProcessName // this.colProcessName.DataPropertyName = "ProcessName"; - dataGridViewCellStyle12.BackColor = System.Drawing.Color.White; - dataGridViewCellStyle12.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.colProcessName.DefaultCellStyle = dataGridViewCellStyle12; + dataGridViewCellStyle2.BackColor = System.Drawing.Color.White; + dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.colProcessName.DefaultCellStyle = dataGridViewCellStyle2; this.colProcessName.HeaderText = "工序名称"; this.colProcessName.MinimumWidth = 8; this.colProcessName.Name = "colProcessName"; @@ -805,8 +805,8 @@ // colValue // this.colValue.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; - dataGridViewCellStyle13.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold); - this.colValue.DefaultCellStyle = dataGridViewCellStyle13; + dataGridViewCellStyle3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold); + this.colValue.DefaultCellStyle = dataGridViewCellStyle3; this.colValue.HeaderText = "内容"; this.colValue.MinimumWidth = 8; this.colValue.Name = "colValue"; @@ -822,7 +822,7 @@ this.flpnlResultData.Controls.Add(this.kanban5); this.flpnlResultData.Controls.Add(this.kanban6); this.flpnlResultData.Location = new System.Drawing.Point(2, 102); - this.flpnlResultData.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.flpnlResultData.Margin = new System.Windows.Forms.Padding(2); this.flpnlResultData.Name = "flpnlResultData"; this.flpnlResultData.Size = new System.Drawing.Size(335, 108); this.flpnlResultData.TabIndex = 5; @@ -838,7 +838,7 @@ this.kanban1.Controls.Add(this.label4); this.kanban1.Controls.Add(this.label6); this.kanban1.Location = new System.Drawing.Point(2, 2); - this.kanban1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.kanban1.Margin = new System.Windows.Forms.Padding(2); this.kanban1.Name = "kanban1"; this.kanban1.Size = new System.Drawing.Size(53, 94); this.kanban1.TabIndex = 14; @@ -943,7 +943,7 @@ this.kanban2.Controls.Add(this.label7); this.kanban2.Controls.Add(this.label12); this.kanban2.Location = new System.Drawing.Point(59, 2); - this.kanban2.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.kanban2.Margin = new System.Windows.Forms.Padding(2); this.kanban2.Name = "kanban2"; this.kanban2.Size = new System.Drawing.Size(53, 94); this.kanban2.TabIndex = 17; @@ -1048,7 +1048,7 @@ this.kanban3.Controls.Add(this.label9); this.kanban3.Controls.Add(this.label15); this.kanban3.Location = new System.Drawing.Point(116, 2); - this.kanban3.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.kanban3.Margin = new System.Windows.Forms.Padding(2); this.kanban3.Name = "kanban3"; this.kanban3.Size = new System.Drawing.Size(53, 94); this.kanban3.TabIndex = 16; @@ -1153,7 +1153,7 @@ this.kanban4.Controls.Add(this.lblPT); this.kanban4.Controls.Add(this.label18); this.kanban4.Location = new System.Drawing.Point(173, 2); - this.kanban4.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.kanban4.Margin = new System.Windows.Forms.Padding(2); this.kanban4.Name = "kanban4"; this.kanban4.Size = new System.Drawing.Size(53, 94); this.kanban4.TabIndex = 15; @@ -1256,7 +1256,7 @@ this.kanban5.Controls.Add(this.lblCompareResult); this.kanban5.Controls.Add(this.label8); this.kanban5.Location = new System.Drawing.Point(230, 2); - this.kanban5.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.kanban5.Margin = new System.Windows.Forms.Padding(2); this.kanban5.Name = "kanban5"; this.kanban5.Size = new System.Drawing.Size(53, 94); this.kanban5.TabIndex = 18; @@ -1335,7 +1335,7 @@ this.kanban6.Controls.Add(this.lblDefectResult); this.kanban6.Controls.Add(this.label13); this.kanban6.Location = new System.Drawing.Point(287, 2); - this.kanban6.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.kanban6.Margin = new System.Windows.Forms.Padding(2); this.kanban6.Name = "kanban6"; this.kanban6.Size = new System.Drawing.Size(40, 94); this.kanban6.TabIndex = 19; @@ -1392,9 +1392,9 @@ this.gpbLog.BackColor = System.Drawing.SystemColors.ActiveCaption; this.gpbLog.Controls.Add(this.lstLog); this.gpbLog.Location = new System.Drawing.Point(2, 365); - this.gpbLog.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.gpbLog.Margin = new System.Windows.Forms.Padding(2); this.gpbLog.Name = "gpbLog"; - this.gpbLog.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.gpbLog.Padding = new System.Windows.Forms.Padding(2); this.gpbLog.Size = new System.Drawing.Size(502, 161); this.gpbLog.TabIndex = 4; this.gpbLog.TabStop = false; @@ -1421,9 +1421,9 @@ this.gpbProductInfo.Controls.Add(this.panel1); this.gpbProductInfo.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.gpbProductInfo.Location = new System.Drawing.Point(2, 2); - this.gpbProductInfo.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.gpbProductInfo.Margin = new System.Windows.Forms.Padding(2); this.gpbProductInfo.Name = "gpbProductInfo"; - this.gpbProductInfo.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.gpbProductInfo.Padding = new System.Windows.Forms.Padding(2); this.gpbProductInfo.Size = new System.Drawing.Size(504, 98); this.gpbProductInfo.TabIndex = 2; this.gpbProductInfo.TabStop = false; @@ -1442,7 +1442,7 @@ this.panel1.Controls.Add(this.label1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(2, 16); - this.panel1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.panel1.Margin = new System.Windows.Forms.Padding(2); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(500, 80); this.panel1.TabIndex = 0; @@ -1452,7 +1452,7 @@ this.txtBatchId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtBatchId.Location = new System.Drawing.Point(216, 58); - this.txtBatchId.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.txtBatchId.Margin = new System.Windows.Forms.Padding(2); this.txtBatchId.Name = "txtBatchId"; this.txtBatchId.ReadOnly = true; this.txtBatchId.Size = new System.Drawing.Size(282, 21); @@ -1473,7 +1473,7 @@ this.txtProductCode.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtProductCode.Location = new System.Drawing.Point(55, 33); - this.txtProductCode.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.txtProductCode.Margin = new System.Windows.Forms.Padding(2); this.txtProductCode.Name = "txtProductCode"; this.txtProductCode.ReadOnly = true; this.txtProductCode.Size = new System.Drawing.Size(444, 21); @@ -1495,7 +1495,7 @@ this.txtProductSN.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtProductSN.Location = new System.Drawing.Point(55, 58); - this.txtProductSN.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.txtProductSN.Margin = new System.Windows.Forms.Padding(2); this.txtProductSN.Name = "txtProductSN"; this.txtProductSN.ReadOnly = true; this.txtProductSN.Size = new System.Drawing.Size(282, 21); @@ -1516,7 +1516,7 @@ this.txtProductName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtProductName.Location = new System.Drawing.Point(55, 9); - this.txtProductName.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.txtProductName.Margin = new System.Windows.Forms.Padding(2); this.txtProductName.Name = "txtProductName"; this.txtProductName.ReadOnly = true; this.txtProductName.Size = new System.Drawing.Size(444, 21); @@ -1540,7 +1540,7 @@ this.splitContainer2.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainer2.IsSplitterFixed = true; this.splitContainer2.Location = new System.Drawing.Point(0, 0); - this.splitContainer2.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.splitContainer2.Margin = new System.Windows.Forms.Padding(2); this.splitContainer2.Name = "splitContainer2"; // // splitContainer2.Panel1 @@ -1552,7 +1552,7 @@ this.splitContainer2.Panel2.Controls.Add(this.gboxDefectList); this.splitContainer2.Panel2MinSize = 400; this.splitContainer2.Size = new System.Drawing.Size(463, 523); - this.splitContainer2.SplitterDistance = 25; + this.splitContainer2.SplitterDistance = 26; this.splitContainer2.SplitterWidth = 3; this.splitContainer2.TabIndex = 10; // @@ -1561,7 +1561,7 @@ this.splitContainer3.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer3.IsSplitterFixed = true; this.splitContainer3.Location = new System.Drawing.Point(0, 0); - this.splitContainer3.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.splitContainer3.Margin = new System.Windows.Forms.Padding(2); this.splitContainer3.Name = "splitContainer3"; this.splitContainer3.Orientation = System.Windows.Forms.Orientation.Horizontal; // @@ -1572,7 +1572,7 @@ // splitContainer3.Panel2 // this.splitContainer3.Panel2.Controls.Add(this.picScanner2); - this.splitContainer3.Size = new System.Drawing.Size(25, 523); + this.splitContainer3.Size = new System.Drawing.Size(26, 523); this.splitContainer3.SplitterDistance = 226; this.splitContainer3.SplitterWidth = 3; this.splitContainer3.TabIndex = 11; @@ -1584,9 +1584,9 @@ this.picScanner1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picScanner1.Dock = System.Windows.Forms.DockStyle.Fill; this.picScanner1.Location = new System.Drawing.Point(0, 0); - this.picScanner1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.picScanner1.Margin = new System.Windows.Forms.Padding(2); this.picScanner1.Name = "picScanner1"; - this.picScanner1.Size = new System.Drawing.Size(25, 226); + this.picScanner1.Size = new System.Drawing.Size(26, 226); this.picScanner1.TabIndex = 7; this.picScanner1.TabStop = false; // @@ -1596,9 +1596,9 @@ this.picScanner2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picScanner2.Dock = System.Windows.Forms.DockStyle.Fill; this.picScanner2.Location = new System.Drawing.Point(0, 0); - this.picScanner2.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.picScanner2.Margin = new System.Windows.Forms.Padding(2); this.picScanner2.Name = "picScanner2"; - this.picScanner2.Size = new System.Drawing.Size(25, 294); + this.picScanner2.Size = new System.Drawing.Size(26, 294); this.picScanner2.TabIndex = 9; this.picScanner2.TabStop = false; // @@ -1609,10 +1609,10 @@ this.gboxDefectList.Controls.Add(this.pnlBmpList); this.gboxDefectList.Dock = System.Windows.Forms.DockStyle.Fill; this.gboxDefectList.Location = new System.Drawing.Point(0, 0); - this.gboxDefectList.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.gboxDefectList.Margin = new System.Windows.Forms.Padding(2); this.gboxDefectList.Name = "gboxDefectList"; - this.gboxDefectList.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2); - this.gboxDefectList.Size = new System.Drawing.Size(435, 523); + this.gboxDefectList.Padding = new System.Windows.Forms.Padding(2); + this.gboxDefectList.Size = new System.Drawing.Size(434, 523); this.gboxDefectList.TabIndex = 3; this.gboxDefectList.TabStop = false; this.gboxDefectList.Tag = "0"; @@ -1624,7 +1624,7 @@ this.lblDefectAddTag.AutoSize = true; this.lblDefectAddTag.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.lblDefectAddTag.ForeColor = System.Drawing.Color.Blue; - this.lblDefectAddTag.Location = new System.Drawing.Point(284, 2); + this.lblDefectAddTag.Location = new System.Drawing.Point(283, 2); this.lblDefectAddTag.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblDefectAddTag.Name = "lblDefectAddTag"; this.lblDefectAddTag.Size = new System.Drawing.Size(0, 12); @@ -1637,16 +1637,16 @@ this.pnlBmpList.AutoSize = true; this.pnlBmpList.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlBmpList.Location = new System.Drawing.Point(2, 16); - this.pnlBmpList.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.pnlBmpList.Margin = new System.Windows.Forms.Padding(2); this.pnlBmpList.Name = "pnlBmpList"; - this.pnlBmpList.Size = new System.Drawing.Size(431, 505); + this.pnlBmpList.Size = new System.Drawing.Size(430, 505); this.pnlBmpList.TabIndex = 0; // // chkBuzzer // this.chkBuzzer.AutoSize = true; this.chkBuzzer.Location = new System.Drawing.Point(677, 27); - this.chkBuzzer.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.chkBuzzer.Margin = new System.Windows.Forms.Padding(2); this.chkBuzzer.Name = "chkBuzzer"; this.chkBuzzer.Size = new System.Drawing.Size(84, 16); this.chkBuzzer.TabIndex = 13; @@ -1658,7 +1658,7 @@ // this.chkDoorSensor.AutoSize = true; this.chkDoorSensor.Location = new System.Drawing.Point(677, 47); - this.chkDoorSensor.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.chkDoorSensor.Margin = new System.Windows.Forms.Padding(2); this.chkDoorSensor.Name = "chkDoorSensor"; this.chkDoorSensor.Size = new System.Drawing.Size(96, 16); this.chkDoorSensor.TabIndex = 14; @@ -1673,7 +1673,7 @@ this.btnMakeTags.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.btnMakeTags.ForeColor = System.Drawing.Color.Blue; this.btnMakeTags.Location = new System.Drawing.Point(881, 29); - this.btnMakeTags.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.btnMakeTags.Margin = new System.Windows.Forms.Padding(2); this.btnMakeTags.Name = "btnMakeTags"; this.btnMakeTags.Size = new System.Drawing.Size(65, 34); this.btnMakeTags.TabIndex = 15; @@ -1685,7 +1685,7 @@ // this.chkHttpLog.AutoSize = true; this.chkHttpLog.Location = new System.Drawing.Point(800, 27); - this.chkHttpLog.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.chkHttpLog.Margin = new System.Windows.Forms.Padding(2); this.chkHttpLog.Name = "chkHttpLog"; this.chkHttpLog.Size = new System.Drawing.Size(96, 16); this.chkHttpLog.TabIndex = 16; @@ -1724,10 +1724,10 @@ this.Controls.Add(this.menuStrip1); this.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.MainMenuStrip = this.menuStrip1; - this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.Margin = new System.Windows.Forms.Padding(2); this.Name = "FrmMain"; this.ShowIcon = false; - this.Text = "自动化视觉检测系统 - v1.2"; + this.Text = "自动化视觉检测系统 - v1.2.1"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmMian_FormClosing); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FrmMian_FormClosed); diff --git a/halftoneproject-master/Code/FrmMain.cs b/halftoneproject-master/Code/FrmMain.cs index 3944ac1..effb96b 100644 --- a/halftoneproject-master/Code/FrmMain.cs +++ b/halftoneproject-master/Code/FrmMain.cs @@ -1,911 +1,911 @@ -using Advantech.Motion; -using HalconDotNet; -using Microsoft.VisualBasic; -using Models; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenCvSharp; -using ProductionControl.Device; +using Advantech.Motion; +using HalconDotNet; +using Microsoft.VisualBasic; +using Models; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OpenCvSharp; +using ProductionControl.Device; using ProductionControl.UI; -using ProductionControl.Utils; -using SqlSugar; -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Forms; -using static ProductionControl.Device.AxisDev; -using static ProductionControl.Device.DefectLib; -using static ProductionControl.Device.SizeLib; - -namespace ProductionControl -{ - public partial class FrmMain : Form - { - WebService webService = new WebService(); - - private List productCodeList = new List(); - private DevContainer devContainer = new DevContainer(); - private Service.ProductService svcProduct = new Service.ProductService(); - private Service.OrderService svcOrder = new Service.OrderService(); - private bool bExitApp = false; - //禁用蜂鸣器,门磁 - private bool disableBuzzer, disableDoorSensor; - - //线宽,张力,厚度,PT - private List lstTension = new List(); - private List lstHeight = new List(); - private List lstLineWidth = new List(); - private List lstPT = new List(); - - private Queue scannerGBmpQueue = new Queue(); - private Queue scannerCBmpQueue = new Queue(); - //private int scannerCBmpIndex = 0;//scannerCBmpQueue中使用当前项的计数器 - private int compBmpIndex = 0;//比对777图的索引 - private int defectBmpNum = 0; - private int defectBmpNumResult = 0; - /// - /// 比对失败的图片 - /// - private List lstCompareFailZoomImage = new List(); - - private object myLock=new object(); - private WarningEnum warningLevel;//警告等级 - private CurrentPTEnum currentPT;//当前点位 - private CurrentStateEnum currentState;//当前状态 - /// - /// 当前流程ID,暂停/继续时使用 - /// - private int currProcessIndex = -1; - private Models.Product currProductModel = null;//当前产品 - - private bool autoMakeTagRuning = false; - private bool isProductRevise = false; - - //产品-厚度base校正点位索引 - private int ProductPT_HeightBaseNum = 0; - - private Stopwatch stopWatch = new Stopwatch(); - private Order order = new Order(); - //--333输出变量供后面多个777使用 - public HObject contoursAffineTrans1_Out; - - private System.Timers.Timer timer = new System.Timers.Timer(); - private class scannerGBmpLoc - { - public scannerGBmpLoc(Mat mat, double xmm, double ymm) - { - bmp = mat; - Xmm = xmm; - Ymm = ymm; - } - public Mat bmp { get; private set; } - public double Xmm { get; private set; } - public double Ymm { get; private set; } - } - private class scannerCBmpLoc - { - public scannerCBmpLoc(string path, double posX, double posY) - { - Path = path; - PosX=posX; - PosY=posY; - } - public scannerCBmpLoc(Bitmap bmp, double posX, double posY) - { - BMP = bmp; - PosX = posX; - PosY = posY; - } - public Bitmap BMP { get; private set; } - public string Path { get; private set; } - public double PosX { get; private set; } - public double PosY { get; private set; } - } - public FrmMain() - { - InitializeComponent(); - this.dgvProcess.AutoGenerateColumns = false; - this.tsbtnCloseDev.Visible = false; - this.tsslLoginInfo.Text = $"操作员:{Config.loginUser.Code}({Config.loginUser.Name})"; - this.tsslLoginTime.Text = $" 登录时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}"; - - //显示行号与列宽度自动调整 - dgvProcess.RowHeadersVisible = true; - dgvProcess.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders; - dgvProcess.RowPostPaint += (sender, e) => - { - Utils.Util.showRowNum_onDataGrid_RowPostPaint(this.dgvProcess, sender, e); - }; - checkCustomerVer(); - } - private void checkCustomerVer() - { - //if(Config.CustomerVer=="A") - // this.tsMenuOrderProduct.Visible = false; - } - private void FrmMian_Load(object sender, EventArgs e) - { - if (Config.loginUser.RoleInfo.Code!="admin") - checkRoleRight(); - loadProductCodeList(); - - this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow; - this.tsslLoginTime.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; - this.tsslLoginInfo.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; - this.tsAxisState.Text = ""; - - // - webService.LogEvent = (warning, msg) => - { - AddTextEvent("HTTP服务", msg, warning); - webService.LogEvent = null; - }; - webService.start(); - } - private void loadProductCodeList() - { - try - { - productCodeList = svcProduct.GetList().Select(m => m.Code).OrderBy(m=>m).ToList(); - } - catch(Exception ex) - { - AddTextEvent("启动", "加载产品料号失败:" + ex.Message,WarningEnum.High); - } - } - private void checkRoleRight() - { - this.流程管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Step") != null); - this.产品管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Product") != null); - this.设备调试ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Debug") != null); - - //this.tsMenuOrderQuery.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Order") != null); - //this.tsMenuStatistics.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Statistics") != null); - - this.角色管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Role") != null); - this.用户管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "User") != null); - - this.tsbtnProductRevise.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "HeightBase") != null); - this.tsMenuSysSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "SysSetting") != null); - this.tsMenuCmdSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "CmdSetting") != null); - this.tsMenuPTSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "PTSetting") != null); - } - private void txtProductName_KeyPress(object sender, KeyPressEventArgs e) - { - //if (e.KeyChar == '\r' && devContainer.state && currentState == CurrentStateEnum.ScanBarcode)// && currentPT== CurrentPTEnum.UpPT ) - //{ - // runStep(); - //} - } - //后台线程运行 - /// - /// 中断工序运行 - /// - /// - private bool isBreakProcessRun() - { - return warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.运行中; - } - private void runStep() - { - compBmpIndex = defectBmpNum = defectBmpNumResult = 0; - AddTextEvent("启动", "等待扫码枪扫码..."); - if (devContainer.devCodeScanner != null) - { - devContainer.devCodeScanner.stop(); - devContainer.devCodeScanner = null; - } - devContainer.devCodeScanner = new CodeScannerDev(); - if (!devContainer.devCodeScanner.start()) - { - AddTextEvent("扫码枪", "扫码枪初始化失败!"); - return; +using ProductionControl.Utils; +using SqlSugar; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using static ProductionControl.Device.AxisDev; +using static ProductionControl.Device.DefectLib; +using static ProductionControl.Device.SizeLib; + +namespace ProductionControl +{ + public partial class FrmMain : Form + { + WebService webService = new WebService(); + + private List productCodeList = new List(); + private DevContainer devContainer = new DevContainer(); + private Service.ProductService svcProduct = new Service.ProductService(); + private Service.OrderService svcOrder = new Service.OrderService(); + private bool bExitApp = false; + //禁用蜂鸣器,门磁 + private bool disableBuzzer, disableDoorSensor; + + //线宽,张力,厚度,PT + private List lstTension = new List(); + private List lstHeight = new List(); + private List lstLineWidth = new List(); + private List lstPT = new List(); + + private Queue scannerGBmpQueue = new Queue(); + private Queue scannerCBmpQueue = new Queue(); + //private int scannerCBmpIndex = 0;//scannerCBmpQueue中使用当前项的计数器 + private int compBmpIndex = 0;//比对777图的索引 + private int defectBmpNum = 0; + private int defectBmpNumResult = 0; + /// + /// 比对失败的图片 + /// + private List lstCompareFailZoomImage = new List(); + + private object myLock=new object(); + private WarningEnum warningLevel;//警告等级 + private CurrentPTEnum currentPT;//当前点位 + private CurrentStateEnum currentState;//当前状态 + /// + /// 当前流程ID,暂停/继续时使用 + /// + private int currProcessIndex = -1; + private Models.Product currProductModel = null;//当前产品 + + private bool autoMakeTagRuning = false; + private bool isProductRevise = false; + + //产品-厚度base校正点位索引 + private int ProductPT_HeightBaseNum = 0; + + private Stopwatch stopWatch = new Stopwatch(); + private Order order = new Order(); + //--333输出变量供后面多个777使用 + public HObject contoursAffineTrans1_Out; + + private System.Timers.Timer timer = new System.Timers.Timer(); + private class scannerGBmpLoc + { + public scannerGBmpLoc(Mat mat, double xmm, double ymm) + { + bmp = mat; + Xmm = xmm; + Ymm = ymm; + } + public Mat bmp { get; private set; } + public double Xmm { get; private set; } + public double Ymm { get; private set; } + } + private class scannerCBmpLoc + { + public scannerCBmpLoc(string path, double posX, double posY) + { + Path = path; + PosX=posX; + PosY=posY; + } + public scannerCBmpLoc(Bitmap bmp, double posX, double posY) + { + BMP = bmp; + PosX = posX; + PosY = posY; + } + public Bitmap BMP { get; private set; } + public string Path { get; private set; } + public double PosX { get; private set; } + public double PosY { get; private set; } + } + public FrmMain() + { + InitializeComponent(); + this.dgvProcess.AutoGenerateColumns = false; + this.tsbtnCloseDev.Visible = false; + this.tsslLoginInfo.Text = $"操作员:{Config.loginUser.Code}({Config.loginUser.Name})"; + this.tsslLoginTime.Text = $" 登录时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}"; + + //显示行号与列宽度自动调整 + dgvProcess.RowHeadersVisible = true; + dgvProcess.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders; + dgvProcess.RowPostPaint += (sender, e) => + { + Utils.Util.showRowNum_onDataGrid_RowPostPaint(this.dgvProcess, sender, e); + }; + checkCustomerVer(); + } + private void checkCustomerVer() + { + //if(Config.CustomerVer=="A") + // this.tsMenuOrderProduct.Visible = false; + } + private void FrmMian_Load(object sender, EventArgs e) + { + if (Config.loginUser.RoleInfo.Code!="admin") + checkRoleRight(); + loadProductCodeList(); + + this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow; + this.tsslLoginTime.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; + this.tsslLoginInfo.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; + this.tsAxisState.Text = ""; + + // + webService.LogEvent = (warning, msg) => + { + AddTextEvent("HTTP服务", msg, warning); + webService.LogEvent = null; + }; + webService.start(); + } + private void loadProductCodeList() + { + try + { + productCodeList = svcProduct.GetList().Select(m => m.Code).OrderBy(m=>m).ToList(); + } + catch(Exception ex) + { + AddTextEvent("启动", "加载产品料号失败:" + ex.Message,WarningEnum.High); + } + } + private void checkRoleRight() + { + this.流程管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Step") != null); + this.产品管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Product") != null); + this.设备调试ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Debug") != null); + + //this.tsMenuOrderQuery.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Order") != null); + //this.tsMenuStatistics.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Statistics") != null); + + this.角色管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Role") != null); + this.用户管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "User") != null); + + this.tsbtnProductRevise.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "HeightBase") != null); + this.tsMenuSysSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "SysSetting") != null); + this.tsMenuCmdSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "CmdSetting") != null); + this.tsMenuPTSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "PTSetting") != null); + } + private void txtProductName_KeyPress(object sender, KeyPressEventArgs e) + { + //if (e.KeyChar == '\r' && devContainer.state && currentState == CurrentStateEnum.ScanBarcode)// && currentPT== CurrentPTEnum.UpPT ) + //{ + // runStep(); + //} + } + //后台线程运行 + /// + /// 中断工序运行 + /// + /// + private bool isBreakProcessRun() + { + return warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.运行中; + } + private void runStep() + { + compBmpIndex = defectBmpNum = defectBmpNumResult = 0; + AddTextEvent("启动", "等待扫码枪扫码..."); + if (devContainer.devCodeScanner != null) + { + devContainer.devCodeScanner.stop(); + devContainer.devCodeScanner = null; + } + devContainer.devCodeScanner = new CodeScannerDev(); + if (!devContainer.devCodeScanner.start()) + { + AddTextEvent("扫码枪", "扫码枪初始化失败!"); + return; } //2023-10-20 不使用扫码枪事件处理 //devContainer.devCodeScanner.ScanerEvent = (code) => - string code = this.txtProductCode.Text; - { - if (!devContainer.state || currentState != CurrentStateEnum.等待扫码 || string.IsNullOrWhiteSpace(code)) - return; - - // - scannerGBmpQueue.Clear(); - scannerCBmpQueue.Clear(); - lstCompareFailZoomImage.Clear(); - contoursAffineTrans1_Out = null; - Thread threadtest = new System.Threading.Thread(() => - { - int errStep = 0; - try - { - var model = svcProduct.GetModelNav(code); - if (model != null && model.StepInfo.ProcessList.Count > 0) - { - errStep = 1; - //根据产品设置动态加载外观检测模型文件 - string onnxFile; - if (!string.IsNullOrWhiteSpace(model.DefectModelFile)) - onnxFile = $"{Application.StartupPath}\\onnxFiles\\{model.DefectModelFile}"; - else - onnxFile = $"{Application.StartupPath}\\onnxFiles\\default.onnx"; - devContainer.libDefect.loadModelFile(onnxFile); - - // - errStep = 2; - string sn = ""; - AutoResetEvent waitEvent = new AutoResetEvent(false); - this.Invoke(new System.Action(() => - { - FrmInput frm = new FrmInput(null, "请输入网版编码:"); - if (frm.ShowDialog() == DialogResult.OK && !string.IsNullOrWhiteSpace(frm.inputData)) - sn = frm.inputData; - waitEvent.Set(); - })); - errStep = 3; - waitEvent.WaitOne(); - if (string.IsNullOrWhiteSpace(sn)) - { - AddTextEvent("扫码枪", $"料号{code}未输入网版编码,流程中止!"); - return; - } - AddTextEvent("扫码枪", $"料号:{code},网版编码:{sn}"); - //是否闪退需观察 - errStep = 4; - devContainer.devCodeScanner.stop(); - devContainer.devCodeScanner = null; - errStep = 5; - //判断SN数量是否达到批次上限 - //创建表达式 - if (!string.IsNullOrWhiteSpace(model.BatchId) && model.TargetCount > 0) - { - var exp1 = Expressionable.Create() - .And(m => m.ProductId == model.Id) - .And(m => m.BatchId == model.BatchId) - .And(m => m.SN != sn) - .ToExpression();//注意 这一句 不能少 - errStep = 6; - if (svcOrder.Count(exp1) >= model.TargetCount) - { - AddTextEvent("扫码枪", $"当前产品本批次检测数已达目标数量,请更换检测批次号!"); - return; - } - - errStep = 7; - } - // - - this.Invoke(new System.Action(() => - { - this.txtProductSN.Text = sn; - })); - - // - model.HeightBaseDec = ""; - currentState = CurrentStateEnum.运行中; - currentPT = CurrentPTEnum.Moving; - currProductModel = model; - AddTextEvent("扫码枪", $"{model.Name} {model.Spec} [{model.Code}]"); - this.Invoke(new System.Action(() => - { - this.txtProductCode.Text = model.Code; - this.txtProductName.Text = model.Name; - this.dgvProcess.DataSource = new BindingSource(model.StepInfo.ProcessList, null); - devContainer.libFor.clear(); - devContainer.libIF.clear(); - tsbtnSizeTag.Enabled = tsbtnSizeImage.Enabled = tsbtnDefectImage.Enabled = true; - })); - errStep = 8; - // - ProductPT_HeightBaseNum = 0; - this.setButtonEnabled(this.tsbtnPause, true); - this.setButtonEnabled(this.tsbtnStopNow, true); - order = new Order(); - order.Qualified = true;//默认合格,中间有一项指标不合格则改为false - order.ProductId = currProductModel.Id; - order.StepId = (int)currProductModel.StepId; - order.SN = sn; - order.BatchId = currProductModel.BatchId; - errStep = 9; - int nextStepId = 0; - do - { - nextStepId = nextProcess(model, nextStepId); - } while (nextStepId >= 0 && !isBreakProcessRun()); - errStep = 10; - } - else - AddTextEvent("扫码枪", model != null ? $"料号{code}不存在!" : $"产品({model.Name})未配置检测流程!"); - } - catch (Exception ex) - { - //AddTextEvent("扫码后", $"errcode({errStep}):" + ex.Message);//会有空对象引用,但不知哪里报的 - //warning(WarningEnum.High); - } - }); - threadtest.IsBackground = true; - threadtest.Start(); - - }; - } - - //model.Type=1 系统校正 - /// - /// - /// - /// - /// 0-n - /// 大于等于0正常工序; -1:结束 -2:异常 - private int nextProcess(Models.Product model, int stepIndex) - { - try - { - //记录当前index - this.currProcessIndex = stepIndex; - this.Invoke(new System.Action(() => - { - try - { - this.dgvProcess.Rows[stepIndex].Selected = true; - dgvProcess.CurrentCell = dgvProcess.Rows[stepIndex].Cells[1]; - } - catch { } - })); - lock (myLock) - { - if (isBreakProcessRun()) - return stepIndex; - } - //开始计时 - if(!isProductRevise && model.StepInfo.StartTimeIndex>0 && model.StepInfo.StartTimeIndex==stepIndex+1) - stopWatch.Restart(); - - var processList = isProductRevise ? model.ReviseStepInfo.ProcessList : model.StepInfo.ProcessList; - var processInfo = processList[stepIndex]; - string processName = processInfo.ProcessName; - //AddTextEvent($"{stepIndex + 1}-{processName}", $"工序开始..."); - string jsonParams = null;//配方 - - if (model.ProductProcessList != null && model.ProductProcessList.Count > 0)//使用产品配方 - { - ProductProcess productProcessParams = model.ProductProcessList.First(m => m.ProcessCode == processInfo.ProcessCode); - if (productProcessParams != null) - { - jsonParams = productProcessParams.ProcessParams; - AddTextEvent($"{stepIndex + 1}-{processName}", $"使用产品专用配方:{jsonParams}"); - } - } - if (jsonParams == null)//使用流程默认配方 - { - jsonParams = processInfo.ProcessParams; - if (jsonParams == null) throw new Exception("配方为null!!"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"使用流程默认配方:{jsonParams}"); - } - - // - JObject processParam = JObject.Parse(jsonParams); - if (!processParam.ContainsKey("Disable") || !processParam.Value("Disable")) - { - AutoResetEvent endEvent; - uint sleepPre = processParam.Value("SleepPre"); - uint sleepLater = processParam.Value("SleepLater"); - if (sleepPre > 0) - Thread.Sleep((int)sleepPre); - double limitThresholdVal, lowerThresholdVal; //张力,厚度,Size,Defect - - //======Switch 工序类型 - bool asynRun; - string gbxBmpPath = ""; - - Models.Attachment attachmentFile; - int liStatocStepIndex = stepIndex; - switch (processInfo.ProcessCode) - { - case "IOCard": - #region - var direction = (IODirectionEnum)processParam.Value("Direction"); - if (direction == IODirectionEnum.输入 || direction == IODirectionEnum.输入输出) - { - uint IN_Waiting_Timeout = processParam.Value("IN_Waiting_Timeout"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"等待I/O输入信号{(IN_Waiting_Timeout > 0 ? $"(超时时长: {IN_Waiting_Timeout})" : "...")}"); - string[] inValue = processParam.Value("IN_OP_SHOW").ToObject>().ToArray(); - uint inWaitingTime = 0; - while (true) - { - if (isBreakProcessRun()) - return stepIndex; - - if (Util.compareIOInput(inValue, devContainer.devIOCard.DIData)) - break; - - Thread.Sleep(10); - inWaitingTime += 10; - if (IN_Waiting_Timeout>0 && inWaitingTime >= IN_Waiting_Timeout) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"输入等待超时告警!", WarningEnum.High); - warning(WarningEnum.Low);//暂停 - return stepIndex; - } - } - AddTextEvent($"{stepIndex + 1}-{processName}", $"I/O输入信号对比完成!"); - } - - if (direction == IODirectionEnum.输出 || direction == IODirectionEnum.输入输出) - devContainer.io_output($"{stepIndex + 1}-{processName}", processParam); - #endregion - break; - case "Tension": - #region - //limitThresholdVal = processParam.Value("LimitThresholdVal"); - //lowerThresholdVal = processParam.Value("LowerThresholdVal"); - //double tensionValue = 0; - //int timeoutTension = 0; - //do - //{ - // tensionValue = devContainer.devTension.getValue(); - // setDgvContentCol(liStatocStepIndex, $"张力值:{tensionValue}"); - // Thread.Sleep(10); - // timeoutTension += 10; - // if (tensionValue <= 0 && timeoutTension >= 600)//3秒超时 - // { - // AddTextEvent($"{stepIndex + 1}-{processName}", $"张力测量失败,确认设备是否正常!", WarningEnum.High); - // warning(WarningEnum.Low);//暂停 - // devContainer.io_output(CMDName.张力读取结束输出); - // currProcessIndex--; - // return stepIndex; - // } - //} while (tensionValue <= 0); - //devContainer.io_output(CMDName.张力读取结束输出); - - //lstTension.Add(tensionValue); - //updateTensionValue(model.TensionBaseValue+model.TensionUpFloatValue,model.TensionBaseValue-model.TensionDownFloatValue); - //if (limitThresholdVal > 0 && tensionValue >= limitThresholdVal) - //{ - // AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue},达到上限阀值:{limitThresholdVal},进行下料...", WarningEnum.Low); - // currProcessIndex = stepIndex + 1; - // warning(WarningEnum.Low);//暂停 - // return stepIndex; - //} - //else if (lowerThresholdVal > 0 && tensionValue < lowerThresholdVal) - //{ - // AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue},达到下限阀值:{lowerThresholdVal},进行下料...", WarningEnum.Low); - // currProcessIndex = stepIndex + 1; - // warning(WarningEnum.Low);//暂停 - // return stepIndex; - //} - //AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue}"); - #endregion - break; - case "Height": - #region - if (Config.SkipHeight) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); - setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); - break; - } - while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待 - { - Thread.Sleep(100); - if (isBreakProcessRun()) - { - //currProcessIndex = stepIndex;//本工序没执行,step不变 - return stepIndex; - } - } - - limitThresholdVal = processParam.Value("LimitThresholdVal"); - lowerThresholdVal = processParam.Value("LowerThresholdVal"); - bool IsRevise = processParam.Value("IsRevise"); - double relBaseValue = processParam.Value("RelBaseValue"); //配方中相对偏移值 - var heightValue = devContainer.devHeight.getHeight(); - heightValue = Math.Round(heightValue, 2);//保留2位小数 - File.AppendAllText(Application.StartupPath + "\\厚度测量记录.txt", heightValue+"\r\n");//TEMP - if (!IsRevise && heightValue < 0) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue},异常数据,终止任务!", WarningEnum.Low); - warning(WarningEnum.Low);//暂停 - return stepIndex; - } - //厚度Base校正 - if (isProductRevise) - { - setDgvContentCol(liStatocStepIndex, $"厚度值:{heightValue}"); - model.HeightBaseDec += heightValue + ";"; - AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue}"); - } - else if (IsRevise) - { - var reviseHeight = heightValue + relBaseValue; - model.HeightBaseDec += reviseHeight + ";"; - setDgvContentCol(liStatocStepIndex, $"base值:{reviseHeight} = 厚度值:{heightValue}+偏移值:{relBaseValue}"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"base值:{reviseHeight} = 厚度值:{heightValue}+偏移值:{relBaseValue},校正索引队列:{model.HeightBaseDec}"); - } - else - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue},base值:{model.HeightBaseDec},偏移值:{relBaseValue},当前base索引:{ProductPT_HeightBaseNum}"); - double heightDev = 0; - var heightDev_BaseList=model.HeightBaseDec.Split(new char[] {';',','}); - if (heightDev_BaseList.Count() > ProductPT_HeightBaseNum && heightDev_BaseList[ProductPT_HeightBaseNum].Trim() != "") - heightDev = Convert.ToDouble(heightDev_BaseList[ProductPT_HeightBaseNum].Trim()); - ProductPT_HeightBaseNum++; - - double heightValue2 =Math.Abs(heightDev - heightValue ) + relBaseValue; - heightValue2 = Math.Round(heightValue2, 2); - setDgvContentCol(liStatocStepIndex, $"厚度值:{heightValue2}"); - lstHeight.Add(heightValue2); - updateHeightValue(model.HeightBaseValue + model.HeightUpFloatValue, model.HeightBaseValue - model.HeightDownFloatValue); - if (limitThresholdVal > 0 && heightValue2 >= limitThresholdVal) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue2},达到上限阀值:{limitThresholdVal},进行下料...", WarningEnum.Low); - currProcessIndex = stepIndex + 1; - warning(WarningEnum.Low);//终止 - return stepIndex; - } - else if (lowerThresholdVal > 0 && heightValue2 < lowerThresholdVal) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue2},达到下限阀值:{lowerThresholdVal},进行下料...", WarningEnum.Low); - currProcessIndex = stepIndex + 1; - warning(WarningEnum.Low);//终止 - return stepIndex; - } - - AddTextEvent($"{stepIndex + 1}-{processName}", $"厚度值:{heightValue2} (Base值:{heightDev} - 读取数据:{heightValue} + 偏移值:{relBaseValue})"); - } - #endregion - break; - case "Axis": - #region 多轴后遗留问题:暂停后再启动不知哪几个轴已执行 - JObject processParamTmp = new JObject(); - //兼容旧版单轴 - if (!processParam.ContainsKey("0") && !processParam.ContainsKey("1") && !processParam.ContainsKey("2") && !processParam.ContainsKey("3")) - { - processParam.Add("Enable", true); - processParamTmp.Add(processParam.Value("AxisIndex").ToString(), processParam); - processParam = processParamTmp; - } - //- - foreach (var processParamSub in processParam.Properties()) - { - processParam = processParamSub.Value as JObject; - AddTextEvent($"{stepIndex + 1}-{processName}", processParam.ToString()); - if (!processParam.ContainsKey("Disable") || !processParam.Value("Disable")) - { - //asynRun = processParam.Value("AsynRun");//异步 - int AxisIndex = processParam.Value("AxisIndex"); - int DeviceType = processParam.Value("DeviceType"); - - double VelLow = processParam.Value("VelLow"); - double VelHigh = processParam.Value("VelHigh"); - double Acc = processParam.Value("Acc"); - double Dec = processParam.Value("Dec"); - - AxMoveMode MoveMode = (AxMoveMode)processParam.Value("MoveMode");//绝对位置 - double PPUValue = processParam.Value("Value"); - - AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}准备({(MoveMode == AxMoveMode.绝对位置 ? "绝对" : "相对")})运动至{PPUValue}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[AxisIndex]).ToString()})..."); - - //移动Axis前等待厚度传感器收回 - if (!Config.SkipHeight) - { - while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue)) - { - if (isBreakProcessRun()) - return stepIndex; - Thread.Sleep(10); - } - } - while (!devContainer.devAxis.isReady(AxisIndex)) - { - Thread.Sleep(100); - if (isBreakProcessRun()) - return stepIndex; - } - devContainer.devAxis.setAxisVelParam(VelLow, VelHigh, Acc, Dec, AxisIndex); - if (!devContainer.devAxis.move_ptp(AxisIndex, PPUValue, MoveMode)) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}运动失败!", WarningEnum.Low); - warning(WarningEnum.Low);//终止 - return stepIndex; - } - - //多轴运行自动使用异步,全部执行后强制等待各轴完成 asynRun属性已无用 - //AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴{AxisIndex}运行完成..."); - //while (!asynRun && !devContainer.devAxis.isReady(AxisIndex)) - //{ - // Thread.Sleep(100); - // if (isBreakProcessRun()) - // { - // currProcessIndex = stepIndex + 1; - // return stepIndex; - // } - //} - //if (devContainer.devAxis.isReady(AxisIndex)) - // AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}运行完成,当前命令位置:{devContainer.devAxis.getCmdPos_mm(AxisIndex)},反馈位置:{devContainer.devAxis.getActualPos_mm(AxisIndex)}"); - } - } - //多轴同时运行后强制等待各轴完成 - AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴组运行完成..."); - while (!devContainer.devAxis.isReady()) - { - Thread.Sleep(100); - if (isBreakProcessRun()) - { - currProcessIndex = stepIndex + 1; - return stepIndex; - } - } - AddTextEvent($"{stepIndex + 1}-{processName}", $"轴组运行完成。"); - #endregion - break; - case "AxisTag": - #region - //asynRun = processParam.Value("AsynRun");//异步 - string axisSizeTag= processParam.Value("SizeTag"); - int useIndex = processParam.Value("UseIndex");//消费posePT中的索引 - AxMoveMode TagMoveMode = (AxMoveMode)processParam.Value("MoveMode");//绝对位置 - var AxisIndexList = processParam.Value("AxisIndexList").ToObject>(); - - double TagVelLow = processParam.Value("VelLow"); - double TagVelHigh = processParam.Value("VelHigh"); - double TagAcc = processParam.Value("Acc"); - double TagDec = processParam.Value("Dec"); - var sizeTagObj = order.SizeTagDataList.LastOrDefault(m => m.SizeTag == axisSizeTag);//用最新的last - if (sizeTagObj == null) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"偏移校正轴工序找不到数据提供者Tag:{axisSizeTag}!", WarningEnum.High); - warning(WarningEnum.High); - return stepIndex; - } - string[] posePT= sizeTagObj.posePT.Split(','); - if(posePT.Length < useIndex+ AxisIndexList.Count) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"Tag:{axisSizeTag}对应消费索引:{useIndex},Axis数量:{AxisIndexList.Count} 超出postPT:{sizeTagObj.posePT} 范围!", WarningEnum.High); - warning(WarningEnum.High); - return stepIndex; - } - - double[] TagPPUValue = new double[AxisIndexList.Count]; - for (int i = 0; i < AxisIndexList.Count; i++) - TagPPUValue[i] = double.Parse(posePT[useIndex + i]); - string axisTagMsg = $"消费Tag:{axisSizeTag},索引:{useIndex}, 轴:{string.Join(",", AxisIndexList.ToList())},数据:{(TagMoveMode== AxMoveMode.绝对位置 ? "绝对" : "相对")}({string.Join(",", TagPPUValue.ToList())})"; - AddTextEvent($"{stepIndex + 1}-{processName}", axisTagMsg); - setDgvContentCol(liStatocStepIndex, axisTagMsg); - - //移动Axis前等待厚度传感器收回 - if (!Config.SkipHeight) - { - while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue)) - { - if (isBreakProcessRun()) - return stepIndex; //如果是相对位置,这里返回会有问题 - Thread.Sleep(10); - } - } - for (int i = 0; i < AxisIndexList.Count && i < TagPPUValue.Length; i++) - { - while (!devContainer.devAxis.isReady(AxisIndexList[i])) - { - Thread.Sleep(100); - if (isBreakProcessRun()) - return stepIndex; - } - devContainer.devAxis.setAxisVelParam(TagVelLow, TagVelHigh, TagAcc, TagDec, AxisIndexList[i]); - if (!devContainer.devAxis.move_ptp(AxisIndexList[i], TagPPUValue[i], TagMoveMode)) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndexList[i]}运动失败!", WarningEnum.Low); - warning(WarningEnum.Low);//终止 - return stepIndex;//如果是相对位置,这里返回会有问题 - } - - //AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴{AxisIndexList[i]}运行完成..."); - //while (!asynRun && !devContainer.devAxis.isReady(AxisIndexList[i])) - //{ - // Thread.Sleep(100); - // if (isBreakProcessRun()) - // { - // currProcessIndex = stepIndex + 1; - // return stepIndex;//如果是相对位置,这里返回会有问题 - // } - //} - //if (devContainer.devAxis.isReady(AxisIndexList[i])) - // AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndexList[i]}运行完成,当前命令位置:{devContainer.devAxis.getCmdPos_mm(AxisIndexList[i])},反馈位置:{devContainer.devAxis.getActualPos_mm(AxisIndexList[i])}"); - } - if (sizeTagObj.ConsumeStepIndex == null) sizeTagObj.ConsumeStepIndex = ""; - sizeTagObj.ConsumeStepIndex += $"{stepIndex + 1}-{useIndex}, ";//消费工序ID - - //多轴同时运行后强制等待各轴完成 - AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴组运行完成..."); - while (!devContainer.devAxis.isReady()) - { - Thread.Sleep(100); - if (isBreakProcessRun()) - { - currProcessIndex = stepIndex + 1; - return stepIndex; - } - } - AddTextEvent($"{stepIndex + 1}-{processName}", $"轴组运行完成。"); - #endregion - break; - case "Light": - #region - if (Config.SkipLight) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); - setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); - break; - } - int ChannelIndex = processParam.Value("ChannelIndex"); //通道 - int DigitalValue = processParam.Value("DigitalValue"); //亮度 - int nowDiaitalValue = devContainer.devLight.getDigitalValue(ChannelIndex); - AddTextEvent($"{stepIndex + 1}-{processName}", $"通道{ChannelIndex}当前值:{nowDiaitalValue},准备更新值:{DigitalValue}..."); - devContainer.devLight.setDigitalValue(ChannelIndex, DigitalValue); - nowDiaitalValue = devContainer.devLight.getDigitalValue(ChannelIndex); - AddTextEvent($"{stepIndex + 1}-{processName}", $"通道{ChannelIndex}更新后当前值:{nowDiaitalValue}。"); - #endregion - break; - case "Scanner_GENTL": - #region - if (Config.SkipScannerGL) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); - setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); - break; - } - while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待 - { - Thread.Sleep(100); - if (isBreakProcessRun()) - { - //currProcessIndex = stepIndex;//本工序没执行,step不变 - return stepIndex; - } - } - - AIEngineLibEnum AIEngineLib = AIEngineLibEnum.缺陷库; - if(processParam.ContainsKey("AIEngineLib")) - AIEngineLib=(AIEngineLibEnum)processParam.Value("AIEngineLib"); - float ExposureTime = processParam.Value("ExposureTime"); //曝光 - float Gain = processParam.Value("Gain"); //增益 - float ResultingFrameRate = processParam.Value("ResultingFrameRate"); //帧率 - - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机开始采集照片..."); - devContainer.devScannerGentl.setParam(ExposureTime, Gain, ResultingFrameRate); - - endEvent = new AutoResetEvent(false); - devContainer.devScannerGentl.ScanEvent = (num, bmpout) => - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成。"); - //----缺陷队列 - bool cloneUse = false; - if (AIEngineLib == AIEngineLibEnum.缺陷库 || AIEngineLib == AIEngineLibEnum.缺陷与测量库) - { - cloneUse = true; - var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmpout); - scannerGBmpQueue.Enqueue(new scannerGBmpLoc(mat, - devContainer.devAxis.getActualPos_mm(1), - devContainer.devAxis.getActualPos_mm(2)));//Dequeue - AddTextEvent($"{stepIndex + 1}-{processName}", $"缺陷图像队列数量: {scannerGBmpQueue.Count}"); - } - if (AIEngineLib == AIEngineLibEnum.测量库 || AIEngineLib == AIEngineLibEnum.缺陷与测量库) - { - scannerCBmpQueue.Enqueue(new scannerCBmpLoc( - cloneUse?(Bitmap)bmpout.Clone(): bmpout, - devContainer.devAxis.getActualPos_mm(1), - devContainer.devAxis.getActualPos_mm(2)));//Dequeue - AddTextEvent($"{stepIndex + 1}-{processName}", $"添加尺寸图像队列,X:{devContainer.devAxis.getActualPos_mm(1)},y:{devContainer.devAxis.getActualPos_mm(2)},数量: {scannerCBmpQueue.Count}"); - } - endEvent.Set();//线程返回 - }; - //AddTextEvent($"{stepIndex + 1}-{processName}", $"软触发拍照..."); - if (!devContainer.devScannerGentl.scan(1))//软触发拍照 - { - devContainer.devScannerGentl.ScanEvent = null; - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片失败!", WarningEnum.Low); - warning(WarningEnum.Low);//终止 - return stepIndex; - } - if (!endEvent.WaitOne(10000)) - { - devContainer.devScannerGentl.ScanEvent = null; - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片超时!", WarningEnum.Low); - warning(WarningEnum.Low);//终止 - return stepIndex; - } - devContainer.devScannerGentl.ScanEvent = null; - #endregion - break; - case "Scanner_CC": - #region - if (Config.SkipScannerCC) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); - setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); - break; - } - while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待 - { - Thread.Sleep(100); - if (isBreakProcessRun()) - { - //currProcessIndex = stepIndex;//本工序没执行,step不变 - return stepIndex; - } - } - - float ExposureTimeCC = processParam.Value("ExposureTime"); //曝光 - float GainCC = processParam.Value("Gain"); //增益 - float ResultingFrameRateCC = processParam.Value("ResultingFrameRate"); //帧率 - - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机开始采集照片..."); - devContainer.devScannerCC.setParam(ExposureTimeCC, GainCC, ResultingFrameRateCC); - - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机参数设置完成。"); - AutoResetEvent endEventCC = new AutoResetEvent(false); - //devContainer.devScannerCC.ScanEvent = (num, bmp2) => - //{ - // AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成."); - // scannerCBmpQueue.Enqueue(bmp2);//Dequeue - // endEventCC.Set();//线程返回 - //}; - devContainer.devScannerCC.ScanEventPath += new System.Action((num, path2) => - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成."); - scannerCBmpQueue.Enqueue(new scannerCBmpLoc(path2, - devContainer.devAxis.getActualPos_mm(0), - devContainer.devAxis.getActualPos_mm(2)));//Dequeue - AddTextEvent($"{stepIndex + 1}-{processName}", $"添加尺寸图像队列,X:{ devContainer.devAxis.getActualPos_mm(0)},y: { devContainer.devAxis.getActualPos_mm(2)},数量: { scannerCBmpQueue.Count}"); - endEventCC.Set();//线程返回 - }); - if (!devContainer.devScannerCC.scan(1))//软触发拍照 - { - devContainer.devScannerCC.ScanEventPath = null; - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片失败!", WarningEnum.Low); - warning(WarningEnum.Low);//终止 - return stepIndex; - } - - if (!endEventCC.WaitOne(10000)) - { - devContainer.devScannerCC.ScanEventPath = null; - AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片超时!", WarningEnum.Low); - warning(WarningEnum.Low);//终止 - return stepIndex; - } - devContainer.devScannerCC.ScanEventPath = null; - #endregion - break; - case "SmallAxis": - #region - if (Config.SkipSmallAxis) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); - setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); - break; - } - int CmdPos = processParam.Value("CmdPos"); //命令脉冲 - AddTextEvent($"{stepIndex + 1}-{processName}", $"开始由起始位置{devContainer.devSmallAxis.getCurrPPU()}运动到{CmdPos}..."); - devContainer.devSmallAxis.gotoPos(CmdPos, true); - AddTextEvent($"{stepIndex + 1}-{processName}", $"运动完成,当前位置:{devContainer.devSmallAxis.getCurrPPU()}"); - #endregion - break; - case "Size": - #region - asynRun = processParam.Value("AsynRun");//异步 - limitThresholdVal = processParam.Value("LimitThresholdVal"); - lowerThresholdVal = processParam.Value("LowerThresholdVal"); - int sizeIndex = processParam.Value("Index"); + string code = this.txtProductCode.Text; + { + if (!devContainer.state || currentState != CurrentStateEnum.等待扫码 || string.IsNullOrWhiteSpace(code)) + return; + + // + scannerGBmpQueue.Clear(); + scannerCBmpQueue.Clear(); + lstCompareFailZoomImage.Clear(); + contoursAffineTrans1_Out = null; + Thread threadtest = new System.Threading.Thread(() => + { + int errStep = 0; + try + { + var model = svcProduct.GetModelNav(code); + if (model != null && model.StepInfo.ProcessList.Count > 0) + { + errStep = 1; + //根据产品设置动态加载外观检测模型文件 + string onnxFile; + if (!string.IsNullOrWhiteSpace(model.DefectModelFile)) + onnxFile = $"{Application.StartupPath}\\onnxFiles\\{model.DefectModelFile}"; + else + onnxFile = $"{Application.StartupPath}\\onnxFiles\\default.onnx"; + devContainer.libDefect.loadModelFile(onnxFile); + + // + errStep = 2; + string sn = ""; + AutoResetEvent waitEvent = new AutoResetEvent(false); + this.Invoke(new System.Action(() => + { + FrmInput frm = new FrmInput(null, "请输入网版编码:"); + if (frm.ShowDialog() == DialogResult.OK && !string.IsNullOrWhiteSpace(frm.inputData)) + sn = frm.inputData; + waitEvent.Set(); + })); + errStep = 3; + waitEvent.WaitOne(); + if (string.IsNullOrWhiteSpace(sn)) + { + AddTextEvent("扫码枪", $"料号{code}未输入网版编码,流程中止!"); + return; + } + AddTextEvent("扫码枪", $"料号:{code},网版编码:{sn}"); + //是否闪退需观察 + errStep = 4; + devContainer.devCodeScanner.stop(); + devContainer.devCodeScanner = null; + errStep = 5; + //判断SN数量是否达到批次上限 + //创建表达式 + if (!string.IsNullOrWhiteSpace(model.BatchId) && model.TargetCount > 0) + { + var exp1 = Expressionable.Create() + .And(m => m.ProductId == model.Id) + .And(m => m.BatchId == model.BatchId) + .And(m => m.SN != sn) + .ToExpression();//注意 这一句 不能少 + errStep = 6; + if (svcOrder.Count(exp1) >= model.TargetCount) + { + AddTextEvent("扫码枪", $"当前产品本批次检测数已达目标数量,请更换检测批次号!"); + return; + } + + errStep = 7; + } + // + + this.Invoke(new System.Action(() => + { + this.txtProductSN.Text = sn; + })); + + // + model.HeightBaseDec = ""; + currentState = CurrentStateEnum.运行中; + currentPT = CurrentPTEnum.Moving; + currProductModel = model; + AddTextEvent("扫码枪", $"{model.Name} {model.Spec} [{model.Code}]"); + this.Invoke(new System.Action(() => + { + this.txtProductCode.Text = model.Code; + this.txtProductName.Text = model.Name; + this.dgvProcess.DataSource = new BindingSource(model.StepInfo.ProcessList, null); + devContainer.libFor.clear(); + devContainer.libIF.clear(); + tsbtnSizeTag.Enabled = tsbtnSizeImage.Enabled = tsbtnDefectImage.Enabled = true; + })); + errStep = 8; + // + ProductPT_HeightBaseNum = 0; + this.setButtonEnabled(this.tsbtnPause, true); + this.setButtonEnabled(this.tsbtnStopNow, true); + order = new Order(); + order.Qualified = true;//默认合格,中间有一项指标不合格则改为false + order.ProductId = currProductModel.Id; + order.StepId = (int)currProductModel.StepId; + order.SN = sn; + order.BatchId = currProductModel.BatchId; + errStep = 9; + int nextStepId = 0; + do + { + nextStepId = nextProcess(model, nextStepId); + } while (nextStepId >= 0 && !isBreakProcessRun()); + errStep = 10; + } + else + AddTextEvent("扫码枪", model != null ? $"料号{code}不存在!" : $"产品({model.Name})未配置检测流程!"); + } + catch (Exception ex) + { + //AddTextEvent("扫码后", $"errcode({errStep}):" + ex.Message);//会有空对象引用,但不知哪里报的 + //warning(WarningEnum.High); + } + }); + threadtest.IsBackground = true; + threadtest.Start(); + + }; + } + + //model.Type=1 系统校正 + /// + /// + /// + /// + /// 0-n + /// 大于等于0正常工序; -1:结束 -2:异常 + private int nextProcess(Models.Product model, int stepIndex) + { + try + { + //记录当前index + this.currProcessIndex = stepIndex; + this.Invoke(new System.Action(() => + { + try + { + this.dgvProcess.Rows[stepIndex].Selected = true; + dgvProcess.CurrentCell = dgvProcess.Rows[stepIndex].Cells[1]; + } + catch { } + })); + lock (myLock) + { + if (isBreakProcessRun()) + return stepIndex; + } + //开始计时 + if(!isProductRevise && model.StepInfo.StartTimeIndex>0 && model.StepInfo.StartTimeIndex==stepIndex+1) + stopWatch.Restart(); + + var processList = isProductRevise ? model.ReviseStepInfo.ProcessList : model.StepInfo.ProcessList; + var processInfo = processList[stepIndex]; + string processName = processInfo.ProcessName; + //AddTextEvent($"{stepIndex + 1}-{processName}", $"工序开始..."); + string jsonParams = null;//配方 + + if (model.ProductProcessList != null && model.ProductProcessList.Count > 0)//使用产品配方 + { + ProductProcess productProcessParams = model.ProductProcessList.First(m => m.ProcessCode == processInfo.ProcessCode); + if (productProcessParams != null) + { + jsonParams = productProcessParams.ProcessParams; + AddTextEvent($"{stepIndex + 1}-{processName}", $"使用产品专用配方:{jsonParams}"); + } + } + if (jsonParams == null)//使用流程默认配方 + { + jsonParams = processInfo.ProcessParams; + if (jsonParams == null) throw new Exception("配方为null!!"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"使用流程默认配方:{jsonParams}"); + } + + // + JObject processParam = JObject.Parse(jsonParams); + if (!processParam.ContainsKey("Disable") || !processParam.Value("Disable")) + { + AutoResetEvent endEvent; + uint sleepPre = processParam.Value("SleepPre"); + uint sleepLater = processParam.Value("SleepLater"); + if (sleepPre > 0) + Thread.Sleep((int)sleepPre); + double limitThresholdVal, lowerThresholdVal; //张力,厚度,Size,Defect + + //======Switch 工序类型 + bool asynRun; + string gbxBmpPath = ""; + + Models.Attachment attachmentFile; + int liStatocStepIndex = stepIndex; + switch (processInfo.ProcessCode) + { + case "IOCard": + #region + var direction = (IODirectionEnum)processParam.Value("Direction"); + if (direction == IODirectionEnum.输入 || direction == IODirectionEnum.输入输出) + { + uint IN_Waiting_Timeout = processParam.Value("IN_Waiting_Timeout"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"等待I/O输入信号{(IN_Waiting_Timeout > 0 ? $"(超时时长: {IN_Waiting_Timeout})" : "...")}"); + string[] inValue = processParam.Value("IN_OP_SHOW").ToObject>().ToArray(); + uint inWaitingTime = 0; + while (true) + { + if (isBreakProcessRun()) + return stepIndex; + + if (Util.compareIOInput(inValue, devContainer.devIOCard.DIData)) + break; + + Thread.Sleep(10); + inWaitingTime += 10; + if (IN_Waiting_Timeout>0 && inWaitingTime >= IN_Waiting_Timeout) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"输入等待超时告警!", WarningEnum.High); + warning(WarningEnum.Low);//暂停 + return stepIndex; + } + } + AddTextEvent($"{stepIndex + 1}-{processName}", $"I/O输入信号对比完成!"); + } + + if (direction == IODirectionEnum.输出 || direction == IODirectionEnum.输入输出) + devContainer.io_output($"{stepIndex + 1}-{processName}", processParam); + #endregion + break; + case "Tension": + #region + //limitThresholdVal = processParam.Value("LimitThresholdVal"); + //lowerThresholdVal = processParam.Value("LowerThresholdVal"); + //double tensionValue = 0; + //int timeoutTension = 0; + //do + //{ + // tensionValue = devContainer.devTension.getValue(); + // setDgvContentCol(liStatocStepIndex, $"张力值:{tensionValue}"); + // Thread.Sleep(10); + // timeoutTension += 10; + // if (tensionValue <= 0 && timeoutTension >= 600)//3秒超时 + // { + // AddTextEvent($"{stepIndex + 1}-{processName}", $"张力测量失败,确认设备是否正常!", WarningEnum.High); + // warning(WarningEnum.Low);//暂停 + // devContainer.io_output(CMDName.张力读取结束输出); + // currProcessIndex--; + // return stepIndex; + // } + //} while (tensionValue <= 0); + //devContainer.io_output(CMDName.张力读取结束输出); + + //lstTension.Add(tensionValue); + //updateTensionValue(model.TensionBaseValue+model.TensionUpFloatValue,model.TensionBaseValue-model.TensionDownFloatValue); + //if (limitThresholdVal > 0 && tensionValue >= limitThresholdVal) + //{ + // AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue},达到上限阀值:{limitThresholdVal},进行下料...", WarningEnum.Low); + // currProcessIndex = stepIndex + 1; + // warning(WarningEnum.Low);//暂停 + // return stepIndex; + //} + //else if (lowerThresholdVal > 0 && tensionValue < lowerThresholdVal) + //{ + // AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue},达到下限阀值:{lowerThresholdVal},进行下料...", WarningEnum.Low); + // currProcessIndex = stepIndex + 1; + // warning(WarningEnum.Low);//暂停 + // return stepIndex; + //} + //AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue}"); + #endregion + break; + case "Height": + #region + if (Config.SkipHeight) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); + setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); + break; + } + while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待 + { + Thread.Sleep(100); + if (isBreakProcessRun()) + { + //currProcessIndex = stepIndex;//本工序没执行,step不变 + return stepIndex; + } + } + + limitThresholdVal = processParam.Value("LimitThresholdVal"); + lowerThresholdVal = processParam.Value("LowerThresholdVal"); + bool IsRevise = processParam.Value("IsRevise"); + double relBaseValue = processParam.Value("RelBaseValue"); //配方中相对偏移值 + var heightValue = devContainer.devHeight.getHeight(); + heightValue = Math.Round(heightValue, 2);//保留2位小数 + File.AppendAllText(Application.StartupPath + "\\厚度测量记录.txt", heightValue+"\r\n");//TEMP + if (!IsRevise && heightValue < 0) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue},异常数据,终止任务!", WarningEnum.Low); + warning(WarningEnum.Low);//暂停 + return stepIndex; + } + //厚度Base校正 + if (isProductRevise) + { + setDgvContentCol(liStatocStepIndex, $"厚度值:{heightValue}"); + model.HeightBaseDec += heightValue + ";"; + AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue}"); + } + else if (IsRevise) + { + var reviseHeight = heightValue + relBaseValue; + model.HeightBaseDec += reviseHeight + ";"; + setDgvContentCol(liStatocStepIndex, $"base值:{reviseHeight} = 厚度值:{heightValue}+偏移值:{relBaseValue}"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"base值:{reviseHeight} = 厚度值:{heightValue}+偏移值:{relBaseValue},校正索引队列:{model.HeightBaseDec}"); + } + else + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue},base值:{model.HeightBaseDec},偏移值:{relBaseValue},当前base索引:{ProductPT_HeightBaseNum}"); + double heightDev = 0; + var heightDev_BaseList=model.HeightBaseDec.Split(new char[] {';',','}); + if (heightDev_BaseList.Count() > ProductPT_HeightBaseNum && heightDev_BaseList[ProductPT_HeightBaseNum].Trim() != "") + heightDev = Convert.ToDouble(heightDev_BaseList[ProductPT_HeightBaseNum].Trim()); + ProductPT_HeightBaseNum++; + + double heightValue2 =Math.Abs(heightDev - heightValue ) + relBaseValue; + heightValue2 = Math.Round(heightValue2, 2); + setDgvContentCol(liStatocStepIndex, $"厚度值:{heightValue2}"); + lstHeight.Add(heightValue2); + updateHeightValue(model.HeightBaseValue + model.HeightUpFloatValue, model.HeightBaseValue - model.HeightDownFloatValue); + if (limitThresholdVal > 0 && heightValue2 >= limitThresholdVal) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue2},达到上限阀值:{limitThresholdVal},进行下料...", WarningEnum.Low); + currProcessIndex = stepIndex + 1; + warning(WarningEnum.Low);//终止 + return stepIndex; + } + else if (lowerThresholdVal > 0 && heightValue2 < lowerThresholdVal) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue2},达到下限阀值:{lowerThresholdVal},进行下料...", WarningEnum.Low); + currProcessIndex = stepIndex + 1; + warning(WarningEnum.Low);//终止 + return stepIndex; + } + + AddTextEvent($"{stepIndex + 1}-{processName}", $"厚度值:{heightValue2} (Base值:{heightDev} - 读取数据:{heightValue} + 偏移值:{relBaseValue})"); + } + #endregion + break; + case "Axis": + #region 多轴后遗留问题:暂停后再启动不知哪几个轴已执行 + JObject processParamTmp = new JObject(); + //兼容旧版单轴 + if (!processParam.ContainsKey("0") && !processParam.ContainsKey("1") && !processParam.ContainsKey("2") && !processParam.ContainsKey("3")) + { + processParam.Add("Enable", true); + processParamTmp.Add(processParam.Value("AxisIndex").ToString(), processParam); + processParam = processParamTmp; + } + //- + foreach (var processParamSub in processParam.Properties()) + { + processParam = processParamSub.Value as JObject; + AddTextEvent($"{stepIndex + 1}-{processName}", processParam.ToString()); + if (!processParam.ContainsKey("Disable") || !processParam.Value("Disable")) + { + //asynRun = processParam.Value("AsynRun");//异步 + int AxisIndex = processParam.Value("AxisIndex"); + int DeviceType = processParam.Value("DeviceType"); + + double VelLow = processParam.Value("VelLow"); + double VelHigh = processParam.Value("VelHigh"); + double Acc = processParam.Value("Acc"); + double Dec = processParam.Value("Dec"); + + AxMoveMode MoveMode = (AxMoveMode)processParam.Value("MoveMode");//绝对位置 + double PPUValue = processParam.Value("Value"); + + AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}准备({(MoveMode == AxMoveMode.绝对位置 ? "绝对" : "相对")})运动至{PPUValue}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[AxisIndex]).ToString()})..."); + + //移动Axis前等待厚度传感器收回 + if (!Config.SkipHeight) + { + while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue)) + { + if (isBreakProcessRun()) + return stepIndex; + Thread.Sleep(10); + } + } + while (!devContainer.devAxis.isReady(AxisIndex)) + { + Thread.Sleep(100); + if (isBreakProcessRun()) + return stepIndex; + } + devContainer.devAxis.setAxisVelParam(VelLow, VelHigh, Acc, Dec, AxisIndex); + if (!devContainer.devAxis.move_ptp(AxisIndex, PPUValue, MoveMode)) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}运动失败!", WarningEnum.Low); + warning(WarningEnum.Low);//终止 + return stepIndex; + } + + //多轴运行自动使用异步,全部执行后强制等待各轴完成 asynRun属性已无用 + //AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴{AxisIndex}运行完成..."); + //while (!asynRun && !devContainer.devAxis.isReady(AxisIndex)) + //{ + // Thread.Sleep(100); + // if (isBreakProcessRun()) + // { + // currProcessIndex = stepIndex + 1; + // return stepIndex; + // } + //} + //if (devContainer.devAxis.isReady(AxisIndex)) + // AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}运行完成,当前命令位置:{devContainer.devAxis.getCmdPos_mm(AxisIndex)},反馈位置:{devContainer.devAxis.getActualPos_mm(AxisIndex)}"); + } + } + //多轴同时运行后强制等待各轴完成 + AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴组运行完成..."); + while (!devContainer.devAxis.isReady()) + { + Thread.Sleep(100); + if (isBreakProcessRun()) + { + currProcessIndex = stepIndex + 1; + return stepIndex; + } + } + AddTextEvent($"{stepIndex + 1}-{processName}", $"轴组运行完成。"); + #endregion + break; + case "AxisTag": + #region + //asynRun = processParam.Value("AsynRun");//异步 + string axisSizeTag= processParam.Value("SizeTag"); + int useIndex = processParam.Value("UseIndex");//消费posePT中的索引 + AxMoveMode TagMoveMode = (AxMoveMode)processParam.Value("MoveMode");//绝对位置 + var AxisIndexList = processParam.Value("AxisIndexList").ToObject>(); + + double TagVelLow = processParam.Value("VelLow"); + double TagVelHigh = processParam.Value("VelHigh"); + double TagAcc = processParam.Value("Acc"); + double TagDec = processParam.Value("Dec"); + var sizeTagObj = order.SizeTagDataList.LastOrDefault(m => m.SizeTag == axisSizeTag);//用最新的last + if (sizeTagObj == null) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"偏移校正轴工序找不到数据提供者Tag:{axisSizeTag}!", WarningEnum.High); + warning(WarningEnum.High); + return stepIndex; + } + string[] posePT= sizeTagObj.posePT.Split(','); + if(posePT.Length < useIndex+ AxisIndexList.Count) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"Tag:{axisSizeTag}对应消费索引:{useIndex},Axis数量:{AxisIndexList.Count} 超出postPT:{sizeTagObj.posePT} 范围!", WarningEnum.High); + warning(WarningEnum.High); + return stepIndex; + } + + double[] TagPPUValue = new double[AxisIndexList.Count]; + for (int i = 0; i < AxisIndexList.Count; i++) + TagPPUValue[i] = double.Parse(posePT[useIndex + i]); + string axisTagMsg = $"消费Tag:{axisSizeTag},索引:{useIndex}, 轴:{string.Join(",", AxisIndexList.ToList())},数据:{(TagMoveMode== AxMoveMode.绝对位置 ? "绝对" : "相对")}({string.Join(",", TagPPUValue.ToList())})"; + AddTextEvent($"{stepIndex + 1}-{processName}", axisTagMsg); + setDgvContentCol(liStatocStepIndex, axisTagMsg); + + //移动Axis前等待厚度传感器收回 + if (!Config.SkipHeight) + { + while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue)) + { + if (isBreakProcessRun()) + return stepIndex; //如果是相对位置,这里返回会有问题 + Thread.Sleep(10); + } + } + for (int i = 0; i < AxisIndexList.Count && i < TagPPUValue.Length; i++) + { + while (!devContainer.devAxis.isReady(AxisIndexList[i])) + { + Thread.Sleep(100); + if (isBreakProcessRun()) + return stepIndex; + } + devContainer.devAxis.setAxisVelParam(TagVelLow, TagVelHigh, TagAcc, TagDec, AxisIndexList[i]); + if (!devContainer.devAxis.move_ptp(AxisIndexList[i], TagPPUValue[i], TagMoveMode)) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndexList[i]}运动失败!", WarningEnum.Low); + warning(WarningEnum.Low);//终止 + return stepIndex;//如果是相对位置,这里返回会有问题 + } + + //AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴{AxisIndexList[i]}运行完成..."); + //while (!asynRun && !devContainer.devAxis.isReady(AxisIndexList[i])) + //{ + // Thread.Sleep(100); + // if (isBreakProcessRun()) + // { + // currProcessIndex = stepIndex + 1; + // return stepIndex;//如果是相对位置,这里返回会有问题 + // } + //} + //if (devContainer.devAxis.isReady(AxisIndexList[i])) + // AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndexList[i]}运行完成,当前命令位置:{devContainer.devAxis.getCmdPos_mm(AxisIndexList[i])},反馈位置:{devContainer.devAxis.getActualPos_mm(AxisIndexList[i])}"); + } + if (sizeTagObj.ConsumeStepIndex == null) sizeTagObj.ConsumeStepIndex = ""; + sizeTagObj.ConsumeStepIndex += $"{stepIndex + 1}-{useIndex}, ";//消费工序ID + + //多轴同时运行后强制等待各轴完成 + AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴组运行完成..."); + while (!devContainer.devAxis.isReady()) + { + Thread.Sleep(100); + if (isBreakProcessRun()) + { + currProcessIndex = stepIndex + 1; + return stepIndex; + } + } + AddTextEvent($"{stepIndex + 1}-{processName}", $"轴组运行完成。"); + #endregion + break; + case "Light": + #region + if (Config.SkipLight) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); + setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); + break; + } + int ChannelIndex = processParam.Value("ChannelIndex"); //通道 + int DigitalValue = processParam.Value("DigitalValue"); //亮度 + int nowDiaitalValue = devContainer.devLight.getDigitalValue(ChannelIndex); + AddTextEvent($"{stepIndex + 1}-{processName}", $"通道{ChannelIndex}当前值:{nowDiaitalValue},准备更新值:{DigitalValue}..."); + devContainer.devLight.setDigitalValue(ChannelIndex, DigitalValue); + nowDiaitalValue = devContainer.devLight.getDigitalValue(ChannelIndex); + AddTextEvent($"{stepIndex + 1}-{processName}", $"通道{ChannelIndex}更新后当前值:{nowDiaitalValue}。"); + #endregion + break; + case "Scanner_GENTL": + #region + if (Config.SkipScannerGL) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); + setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); + break; + } + while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待 + { + Thread.Sleep(100); + if (isBreakProcessRun()) + { + //currProcessIndex = stepIndex;//本工序没执行,step不变 + return stepIndex; + } + } + + AIEngineLibEnum AIEngineLib = AIEngineLibEnum.缺陷库; + if(processParam.ContainsKey("AIEngineLib")) + AIEngineLib=(AIEngineLibEnum)processParam.Value("AIEngineLib"); + float ExposureTime = processParam.Value("ExposureTime"); //曝光 + float Gain = processParam.Value("Gain"); //增益 + float ResultingFrameRate = processParam.Value("ResultingFrameRate"); //帧率 + + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机开始采集照片..."); + devContainer.devScannerGentl.setParam(ExposureTime, Gain, ResultingFrameRate); + + endEvent = new AutoResetEvent(false); + devContainer.devScannerGentl.ScanEvent = (num, bmpout) => + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成。"); + //----缺陷队列 + bool cloneUse = false; + if (AIEngineLib == AIEngineLibEnum.缺陷库 || AIEngineLib == AIEngineLibEnum.缺陷与测量库) + { + cloneUse = true; + var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmpout); + scannerGBmpQueue.Enqueue(new scannerGBmpLoc(mat, + devContainer.devAxis.getActualPos_mm(1), + devContainer.devAxis.getActualPos_mm(2)));//Dequeue + AddTextEvent($"{stepIndex + 1}-{processName}", $"缺陷图像队列数量: {scannerGBmpQueue.Count}"); + } + if (AIEngineLib == AIEngineLibEnum.测量库 || AIEngineLib == AIEngineLibEnum.缺陷与测量库) + { + scannerCBmpQueue.Enqueue(new scannerCBmpLoc( + cloneUse?(Bitmap)bmpout.Clone(): bmpout, + devContainer.devAxis.getActualPos_mm(1), + devContainer.devAxis.getActualPos_mm(2)));//Dequeue + AddTextEvent($"{stepIndex + 1}-{processName}", $"添加尺寸图像队列,X:{devContainer.devAxis.getActualPos_mm(1)},y:{devContainer.devAxis.getActualPos_mm(2)},数量: {scannerCBmpQueue.Count}"); + } + endEvent.Set();//线程返回 + }; + //AddTextEvent($"{stepIndex + 1}-{processName}", $"软触发拍照..."); + if (!devContainer.devScannerGentl.scan(1))//软触发拍照 + { + devContainer.devScannerGentl.ScanEvent = null; + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片失败!", WarningEnum.Low); + warning(WarningEnum.Low);//终止 + return stepIndex; + } + if (!endEvent.WaitOne(10000)) + { + devContainer.devScannerGentl.ScanEvent = null; + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片超时!", WarningEnum.Low); + warning(WarningEnum.Low);//终止 + return stepIndex; + } + devContainer.devScannerGentl.ScanEvent = null; + #endregion + break; + case "Scanner_CC": + #region + if (Config.SkipScannerCC) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); + setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); + break; + } + while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待 + { + Thread.Sleep(100); + if (isBreakProcessRun()) + { + //currProcessIndex = stepIndex;//本工序没执行,step不变 + return stepIndex; + } + } + + float ExposureTimeCC = processParam.Value("ExposureTime"); //曝光 + float GainCC = processParam.Value("Gain"); //增益 + float ResultingFrameRateCC = processParam.Value("ResultingFrameRate"); //帧率 + + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机开始采集照片..."); + devContainer.devScannerCC.setParam(ExposureTimeCC, GainCC, ResultingFrameRateCC); + + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机参数设置完成。"); + AutoResetEvent endEventCC = new AutoResetEvent(false); + //devContainer.devScannerCC.ScanEvent = (num, bmp2) => + //{ + // AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成."); + // scannerCBmpQueue.Enqueue(bmp2);//Dequeue + // endEventCC.Set();//线程返回 + //}; + devContainer.devScannerCC.ScanEventPath += new System.Action((num, path2) => + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成."); + scannerCBmpQueue.Enqueue(new scannerCBmpLoc(path2, + devContainer.devAxis.getActualPos_mm(0), + devContainer.devAxis.getActualPos_mm(2)));//Dequeue + AddTextEvent($"{stepIndex + 1}-{processName}", $"添加尺寸图像队列,X:{ devContainer.devAxis.getActualPos_mm(0)},y: { devContainer.devAxis.getActualPos_mm(2)},数量: { scannerCBmpQueue.Count}"); + endEventCC.Set();//线程返回 + }); + if (!devContainer.devScannerCC.scan(1))//软触发拍照 + { + devContainer.devScannerCC.ScanEventPath = null; + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片失败!", WarningEnum.Low); + warning(WarningEnum.Low);//终止 + return stepIndex; + } + + if (!endEventCC.WaitOne(10000)) + { + devContainer.devScannerCC.ScanEventPath = null; + AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片超时!", WarningEnum.Low); + warning(WarningEnum.Low);//终止 + return stepIndex; + } + devContainer.devScannerCC.ScanEventPath = null; + #endregion + break; + case "SmallAxis": + #region + if (Config.SkipSmallAxis) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!"); + setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!"); + break; + } + int CmdPos = processParam.Value("CmdPos"); //命令脉冲 + AddTextEvent($"{stepIndex + 1}-{processName}", $"开始由起始位置{devContainer.devSmallAxis.getCurrPPU()}运动到{CmdPos}..."); + devContainer.devSmallAxis.gotoPos(CmdPos, true); + AddTextEvent($"{stepIndex + 1}-{processName}", $"运动完成,当前位置:{devContainer.devSmallAxis.getCurrPPU()}"); + #endregion + break; + case "Size": + #region + asynRun = processParam.Value("AsynRun");//异步 + limitThresholdVal = processParam.Value("LimitThresholdVal"); + lowerThresholdVal = processParam.Value("LowerThresholdVal"); + int sizeIndex = processParam.Value("Index"); string sizeTag = processParam.ContainsKey("SizeTag") ? processParam.Value("SizeTag") : ""; @@ -948,25 +948,25 @@ namespace ProductionControl } - double[] getPosArray = getPosList.ToArray(); - if (scannerCBmpQueue.Count < 1) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测异常,无源图像!!", WarningEnum.Low); - warning(WarningEnum.Low);//暂停 - return stepIndex; - } - var bmpCBmpQueue = scannerCBmpQueue.Dequeue(); - AddTextEvent($"{stepIndex + 1}-{processName}", $"开始尺寸检测,index:{sizeIndex},posX:{bmpCBmpQueue.PosX},posY:{bmpCBmpQueue.PosY},图像队列数量: {scannerCBmpQueue.Count}..."); - - attachmentFile = model.AttachmentList.FirstOrDefault(x => x.Type == 0); - AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测,index:{sizeIndex},{model.AttachmentList.Count}|{(attachmentFile == null ? "null": attachmentFile.NameTimestamp+ attachmentFile.ExtendName)}"); - if (attachmentFile != null) - { - gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}"; - if (!File.Exists(gbxBmpPath+ attachmentFile.ExtendName)) gbxBmpPath = ""; - } - if ((sizeIndex == 333 || sizeIndex == 777) && gbxBmpPath == "") - AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测,index:{sizeIndex},图纸不存在!", WarningEnum.Low); + double[] getPosArray = getPosList.ToArray(); + if (scannerCBmpQueue.Count < 1) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测异常,无源图像!!", WarningEnum.Low); + warning(WarningEnum.Low);//暂停 + return stepIndex; + } + var bmpCBmpQueue = scannerCBmpQueue.Dequeue(); + AddTextEvent($"{stepIndex + 1}-{processName}", $"开始尺寸检测,index:{sizeIndex},posX:{bmpCBmpQueue.PosX},posY:{bmpCBmpQueue.PosY},图像队列数量: {scannerCBmpQueue.Count}..."); + + attachmentFile = model.AttachmentList.FirstOrDefault(x => x.Type == 0); + AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测,index:{sizeIndex},{model.AttachmentList.Count}|{(attachmentFile == null ? "null": attachmentFile.NameTimestamp+ attachmentFile.ExtendName)}"); + if (attachmentFile != null) + { + gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}"; + if (!File.Exists(gbxBmpPath+ attachmentFile.ExtendName)) gbxBmpPath = ""; + } + if ((sizeIndex == 333 || sizeIndex == 777) && gbxBmpPath == "") + AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测,index:{sizeIndex},图纸不存在!", WarningEnum.Low); //2023-10-27 //if ((sizeIndex == 3333)&&(getPosList != null) && (getPosList.Count() != 28)) // AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测,index:{sizeIndex},图纸读点不存在!", WarningEnum.Low); @@ -974,2426 +974,2426 @@ namespace ProductionControl AddTextEvent($"{stepIndex + 1}-{processName}", $"开始图纸读点,index:{sizeIndex},PT1:{getPosArray[0]},PT2:{getPosArray[2]},PT3:{getPosArray[4]},PT4:{getPosArray[6]},PT5:{getPosArray[8]}," + $"线宽1:[{getPosArray[10]},{getPosArray[11]}],线宽2:[{getPosArray[12]},{getPosArray[13]}],线宽3:[{getPosArray[14]},{getPosArray[15]}]," + $"线宽4:[{getPosArray[16]},{getPosArray[17]}],线宽5:[{getPosArray[18]},{getPosArray[19]}],线宽6:[{getPosArray[20]},{getPosArray[21]}]," + - $"线宽7:[{getPosArray[22]},{getPosArray[23]}],线宽8:[{getPosArray[24]},{getPosArray[25]}],线宽9:[{getPosArray[26]},{getPosArray[27]}]"); - //需要偏移校正,index=0时不能异步 //10,20,30...  - endEvent = new AutoResetEvent(false); - devContainer.libSize.add(new SizeTask() - { - stepIndex = stepIndex, - processName = processName, - sizeTag = sizeTag, - engineName = processParam.Value("EngineName"), - bmp = bmpCBmpQueue.BMP,//bmp/file_path二选一,优先bmp - file_path = bmpCBmpQueue.Path, - drawingPagePath = gbxBmpPath, - posX= bmpCBmpQueue.PosX, - posY= bmpCBmpQueue.PosY, + $"线宽7:[{getPosArray[22]},{getPosArray[23]}],线宽8:[{getPosArray[24]},{getPosArray[25]}],线宽9:[{getPosArray[26]},{getPosArray[27]}]"); + //需要偏移校正,index=0时不能异步 //10,20,30...  + endEvent = new AutoResetEvent(false); + devContainer.libSize.add(new SizeTask() + { + stepIndex = stepIndex, + processName = processName, + sizeTag = sizeTag, + engineName = processParam.Value("EngineName"), + bmp = bmpCBmpQueue.BMP,//bmp/file_path二选一,优先bmp + file_path = bmpCBmpQueue.Path, + drawingPagePath = gbxBmpPath, + posX= bmpCBmpQueue.PosX, + posY= bmpCBmpQueue.PosY, //2023-10-27 PTandLinePos = getPosArray, - index = sizeIndex,// scannerCBmpIndex++, - ContoursAffineTrans1_Out=this.contoursAffineTrans1_Out,//只有777时才使用最近333输出的结果 - finishEvent = (res) => - { - try - { - //比对 - if (res.index == 777)//比对 - { - if (res.isSucceed) - { - setDgvContentCol(liStatocStepIndex, $"index:{res.index}-{compBmpIndex},posX:{res.posX},posY:{res.posY},图像比对:{(res.CompResult ? "通过" : "未通过")} "); - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对,index:{res.index}-{compBmpIndex},posX:{res.posX},posY:{res.posY},结果:{(res.CompResult ? "通过" : "未通过")}"); - // - if (order.CompareResult < 2) - order.CompareResult = res.CompResult ? 1 : 2; - updateCompareResult(res.CompResult);//更新比对看板 - if (!res.CompResult) - { - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对,未通过结果:{JsonConvert.SerializeObject(res.defectInfor2RestorationDesk)}"); - //转为图纸上坐标位置 - if (res.defectInfor2RestorationDeskPage != null && res.defectInfor2RestorationDeskPage.Count > 0) - { - //AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"转换到图纸后坐标数据:{JsonConvert.SerializeObject(res.defectInfor2RestorationDeskPage)}"); - if (order.DefectInfoList == null) - order.DefectInfoList = new List(); - foreach (var item in res.defectInfor2RestorationDeskPage) - order.DefectInfoList.Add(new DefectInfo() - { - Type = 1, - Code = item[3], - X = double.Parse(item[1]), - Y = double.Parse(item[2]), - ZXD = double.Parse(item[4]), - ModifyUserCode = Config.loginUser.Code, - CreateUserCode = Config.loginUser.Code, - }); - } - - //比对失败的图片 -- 用于修复台调用 - Bitmap bmpCompareFailZoomImage = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.Zoom_Image_mat); - lstCompareFailZoomImage.Add(bmpCompareFailZoomImage); - if (Config.SizeBmp_Zoom_Image_SavePath != "" && Directory.Exists(Config.SizeBmp_Zoom_Image_SavePath)) - { - string path = Util.createSubDir(Config.SizeBmp_Zoom_Image_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); - //path += $"Size_SN{order.SN}_I{res.index}_X{res.Defects_X}_Y{res.Defects_Y}_C0_{ model.StepInfo.Name}"; - path += $"Size_SN{order.SN}_I{compBmpIndex}_X{res.posX}_Y{res.posY}_C0_{ model.StepInfo.Name}"; - bmpCompareFailZoomImage.Save(path + ".bmp", ImageFormat.Bmp); - if (res.defectInfor2RestorationDesk != null && res.defectInfor2RestorationDesk.Count > 0) - File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.defectInfor2RestorationDesk)); - } - //保存原图 - if (Config.SizeBmp_Compare_SavePath != "" && Directory.Exists(Config.SizeBmp_Compare_SavePath)) - { - string path = Util.createSubDir(Config.SizeBmp_Compare_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); - path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp"; - AddTextEvent($"{res.stepIndex + 1}-{processName}", $"未通过图片保存:{path}"); - if (res.bmp != null) - res.bmp.Save(path, ImageFormat.Bmp); - else - API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快 - } - } - } - else - { - //warning(WarningEnum.Low);//暂停 - setDgvContentCol(liStatocStepIndex, $"index:{res.index},图像比对失败!"); - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对失败,index:{res.index}-{compBmpIndex}.", WarningEnum.Low); - } - compBmpIndex++; - } - //MARK - else if (res.index == 111 || res.index == 222 || res.index == 333 || res.index == 444) - { - AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index},结果记录..."); - if (res.index == 333) this.contoursAffineTrans1_Out = res.ContoursAffineTrans1_Out;//不管成功失败都替换 - if (res.isSucceed) - { - Thread.Sleep(100); - AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index}; 当前值:{string.Join(",", res.MarkPointList)}"); - JArray markDatas; - if (string.IsNullOrWhiteSpace(order.MarkData)) - markDatas = new JArray() { 0, 0, 0, 0, 0, 0, 0, 0 }; - else - markDatas = JArray.Parse(order.MarkData); - for (int i = 0; i < res.MarkPointList.Count(); i++) - if (res.MarkPointList[i] != 0) - markDatas[i] = res.MarkPointList[i]; - order.MarkData = markDatas.ToString(); - setDgvContentCol(liStatocStepIndex, $"index:{res.index},Mark点:{order.MarkData} "); - AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index};合并后:{order.MarkData}"); - } - else - { - //warning(WarningEnum.Low);//暂停 - setDgvContentCol(liStatocStepIndex, $"index:{res.index},Mark点计算失败!"); + index = sizeIndex,// scannerCBmpIndex++, + ContoursAffineTrans1_Out=this.contoursAffineTrans1_Out,//只有777时才使用最近333输出的结果 + finishEvent = (res) => + { + try + { + //比对 + if (res.index == 777)//比对 + { + if (res.isSucceed) + { + setDgvContentCol(liStatocStepIndex, $"index:{res.index}-{compBmpIndex},posX:{res.posX},posY:{res.posY},图像比对:{(res.CompResult ? "通过" : "未通过")} "); + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对,index:{res.index}-{compBmpIndex},posX:{res.posX},posY:{res.posY},结果:{(res.CompResult ? "通过" : "未通过")}"); + // + if (order.CompareResult < 2) + order.CompareResult = res.CompResult ? 1 : 2; + updateCompareResult(res.CompResult);//更新比对看板 + if (!res.CompResult) + { + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对,未通过结果:{JsonConvert.SerializeObject(res.defectInfor2RestorationDesk)}"); + //转为图纸上坐标位置 + if (res.defectInfor2RestorationDeskPage != null && res.defectInfor2RestorationDeskPage.Count > 0) + { + //AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"转换到图纸后坐标数据:{JsonConvert.SerializeObject(res.defectInfor2RestorationDeskPage)}"); + if (order.DefectInfoList == null) + order.DefectInfoList = new List(); + foreach (var item in res.defectInfor2RestorationDeskPage) + order.DefectInfoList.Add(new DefectInfo() + { + Type = 1, + Code = item[3], + X = double.Parse(item[1]), + Y = double.Parse(item[2]), + ZXD = double.Parse(item[4]), + ModifyUserCode = Config.loginUser.Code, + CreateUserCode = Config.loginUser.Code, + }); + } + + //比对失败的图片 -- 用于修复台调用 + Bitmap bmpCompareFailZoomImage = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.Zoom_Image_mat); + lstCompareFailZoomImage.Add(bmpCompareFailZoomImage); + if (Config.SizeBmp_Zoom_Image_SavePath != "" && Directory.Exists(Config.SizeBmp_Zoom_Image_SavePath)) + { + string path = Util.createSubDir(Config.SizeBmp_Zoom_Image_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); + //path += $"Size_SN{order.SN}_I{res.index}_X{res.Defects_X}_Y{res.Defects_Y}_C0_{ model.StepInfo.Name}"; + path += $"Size_SN{order.SN}_I{compBmpIndex}_X{res.posX}_Y{res.posY}_C0_{ model.StepInfo.Name}"; + bmpCompareFailZoomImage.Save(path + ".bmp", ImageFormat.Bmp); + if (res.defectInfor2RestorationDesk != null && res.defectInfor2RestorationDesk.Count > 0) + File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.defectInfor2RestorationDesk)); + } + //保存原图 + if (Config.SizeBmp_Compare_SavePath != "" && Directory.Exists(Config.SizeBmp_Compare_SavePath)) + { + string path = Util.createSubDir(Config.SizeBmp_Compare_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); + path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp"; + AddTextEvent($"{res.stepIndex + 1}-{processName}", $"未通过图片保存:{path}"); + if (res.bmp != null) + res.bmp.Save(path, ImageFormat.Bmp); + else + API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快 + } + } + } + else + { + //warning(WarningEnum.Low);//暂停 + setDgvContentCol(liStatocStepIndex, $"index:{res.index},图像比对失败!"); + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对失败,index:{res.index}-{compBmpIndex}.", WarningEnum.Low); + } + compBmpIndex++; + } + //MARK + else if (res.index == 111 || res.index == 222 || res.index == 333 || res.index == 444) + { + AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index},结果记录..."); + if (res.index == 333) this.contoursAffineTrans1_Out = res.ContoursAffineTrans1_Out;//不管成功失败都替换 + if (res.isSucceed) + { + Thread.Sleep(100); + AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index}; 当前值:{string.Join(",", res.MarkPointList)}"); + JArray markDatas; + if (string.IsNullOrWhiteSpace(order.MarkData)) + markDatas = new JArray() { 0, 0, 0, 0, 0, 0, 0, 0 }; + else + markDatas = JArray.Parse(order.MarkData); + for (int i = 0; i < res.MarkPointList.Count(); i++) + if (res.MarkPointList[i] != 0) + markDatas[i] = res.MarkPointList[i]; + order.MarkData = markDatas.ToString(); + setDgvContentCol(liStatocStepIndex, $"index:{res.index},Mark点:{order.MarkData} "); + AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index};合并后:{order.MarkData}"); + } + else + { + //warning(WarningEnum.Low);//暂停 + setDgvContentCol(liStatocStepIndex, $"index:{res.index},Mark点计算失败!"); AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点计算失败,index:{res.index}.", WarningEnum.Low); //2023-10-20 make暂停 if (Config.OpenMarkErrorStop) - warning(WarningEnum.Low);//暂停 - } - - //保存 - if (Config.SizeBmp_SavePath != "" && Directory.Exists(Config.SizeBmp_SavePath)) - { - string path = Util.createSubDir(Config.SizeBmp_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); - path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp"; - if (res.bmp != null) - res.bmp.Save(path, ImageFormat.Bmp); - else - API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快 - } - } - else - { - int roundIndex = res.index % 10; - if (res.isSucceed) - { - string tagOutData = ""; - if (res.index == 3333 && !string.IsNullOrWhiteSpace(res.sizeTag)) - { - tagOutData = $"Tag:{res.sizeTag},posePT:[{string.Join(",", res.posePT)}]"; - if (res.posePT.Length < 2 || res.posePT.Length % 2 != 0) - { - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测输出Tag对应posePT非法: {tagOutData}", WarningEnum.High); - warning(WarningEnum.High);//急停 - return; - } + warning(WarningEnum.Low);//暂停 + } + + //保存 + if (Config.SizeBmp_SavePath != "" && Directory.Exists(Config.SizeBmp_SavePath)) + { + string path = Util.createSubDir(Config.SizeBmp_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); + path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp"; + if (res.bmp != null) + res.bmp.Save(path, ImageFormat.Bmp); + else + API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快 + } + } + else + { + int roundIndex = res.index % 10; + if (res.isSucceed) + { + string tagOutData = ""; + if (res.index == 3333 && !string.IsNullOrWhiteSpace(res.sizeTag)) + { + tagOutData = $"Tag:{res.sizeTag},posePT:[{string.Join(",", res.posePT)}]"; + if (res.posePT.Length < 2 || res.posePT.Length % 2 != 0) + { + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测输出Tag对应posePT非法: {tagOutData}", WarningEnum.High); + warning(WarningEnum.High);//急停 + return; + } //2023-10-27 - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"Tag对应posePT: {tagOutData}", WarningEnum.Normal); - - if (order.SizeTagDataList == null) - order.SizeTagDataList = new List(); - order.SizeTagDataList.Add(new SizeTagData() - { - SizeTag = res.sizeTag, - CreateStepIndex = res.stepIndex + 1, - posePT= string.Join(",", res.posePT)// 回转 Array.ConvertAll(sNums , double.Parse); - }); - - } - - setDgvContentCol(liStatocStepIndex, $"index:{res.index},PT1:{res.PT1},PT2:{res.PT2},Shanxian:{res.Shanxian},Circle_Xmm:{res.Circle_Xmm},Circle_Ymm:{res.Circle_Ymm},offsetX:{res.offsetX},offsetY:{res.offsetY}, {tagOutData}"); - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测完成 index:{res.index},PT1:{res.PT1},PT2:{res.PT2},Shanxian:{res.Shanxian},Circle_Xmm:{res.Circle_Xmm},Circle_Ymm:{res.Circle_Ymm},offsetX:{res.offsetX},offsetY:{res.offsetY}, {tagOutData} "); - //测量 - //------TEST - if (res.index>20 && res.index<30) - { - lock (lstPT) - { - lstPT.Add(Math.Round(res.PT1, 4)); - updatePTValueTest(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue); - } - } - //------ - if (roundIndex > 0)//1-9测量 - { - if (res.index < 10)//11-13 (PT: 7-9 => 21-29(PT1)) 不用管,李工处理 - { - //if (roundIndex >= 7) - //{ - // lock (lstPT) - // { - // lstPT.Add(Math.Round(res.PT1, 4)); - // lstPT.Add(res.index == 8 ? 0 : Math.Round(res.PT2, 4)); - // updatePTValue(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue); - // } - //} - - lock (lstLineWidth) - { - lstLineWidth.Add(res.Shanxian > 0 ? Math.Round(res.Shanxian, 2) : 0); - updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue); - } - } - } - //校正偏移 10,20,30...:偏移 - else - { - AxMoveMode axSizeMode = AxMoveMode.绝对位置; - double xPos = 0; - double yPos = 0; - //绝对偏移 - if (res.offsetX != 0 || res.offsetY != 0) - { - xPos += res.offsetX; - yPos += res.offsetY; - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"offsetX/Y绝对校正, 0轴:{xPos}mm, 2轴:{yPos}mm"); - } - else if (res.Circle_Xmm != 0 || res.Circle_Ymm != 0)//相对偏移校正 - { - axSizeMode = AxMoveMode.相对位置; - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"原点相对校正, 0轴:{res.Circle_Xmm}mm, 2轴:{res.Circle_Ymm}mm"); - if (res.Circle_Xmm != 0) xPos = res.Circle_Xmm; - if (res.Circle_Ymm != 0) yPos = res.Circle_Ymm; - } - //当前工序直接移动 - if (xPos != 0 || yPos != 0) - { - devContainer.devAxis.setAxisVelParam(0.1, 1, 1, 1, 0); - devContainer.devAxis.setAxisVelParam(0.1, 1, 1, 1, 2); - if (xPos != 0) devContainer.devAxis.move_ptp(0, xPos, axSizeMode); - if (yPos != 0) devContainer.devAxis.move_ptp(2, yPos, axSizeMode); - while (!devContainer.devAxis.isReady(0) || !devContainer.devAxis.isReady(2)) - { - Thread.Sleep(100); - if (isBreakProcessRun()) - break; - } - } - } - - //保存 - //string sizeFileName = Config.Size_SavePath + "\\" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"); - //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//更快 - //File.WriteAllText(defectFileName + ".json", JsonConvert.SerializeObject(res.informationList)); - } - //失败 - else - { - //------TEST - if (res.index > 20 && res.index < 30) - { - lock (lstPT) - { - lstPT.Add(0); - updatePTValueTest(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue); - } - } - //------ - - if (roundIndex > 0) - { - //if (roundIndex >= 7) - //{ - // lock (lstPT) - // { - // lstPT.Add(0); - // lstPT.Add(0); - // updatePTValue(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue); - // } - //} - - lock (lstLineWidth) - { - lstLineWidth.Add(0); - updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue); - } - } - setDgvContentCol(liStatocStepIndex, $"失败:{res.resultInfo}"); - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测失败index:{res.index}:{res.resultInfo}"); - //warning(WarningEnum.Low);//暂停 这里不能暂停,stepIndex和scannerBmpQueue队列也不对了 - } - - //保存 - if (Config.SizeBmp_SavePath != "" && Directory.Exists(Config.SizeBmp_SavePath)) - { - string path = Util.createSubDir(Config.SizeBmp_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); - path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp"; - if (res.bmp != null) - res.bmp.Save(path, ImageFormat.Bmp); - else - API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快 - } - } - } - catch(Exception ex) - { - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测回调处理异常 index:{res.index},ex={ex.Message}"); - } - - // - //if (!asynRun)//是否异步执行endEvent.Set()都没问题 - endEvent.Set();//roundIndex=0成功或失败线程返回 - //--- - if (res.bmp != null) - { - res.bmp.Dispose(); - res.bmp = null; - } - else - { - API.DeleteFile(res.file_path); - } - } - }); - - //需等上面异步回调中的相对偏移校正完成再继续 - if (!asynRun || sizeIndex % 10==0) - { - if (!endEvent.WaitOne(60000)) - AddTextEvent($"{stepIndex + 1}-{processName}", $"{sizeIndex}等待超时,忽略继续!", WarningEnum.Low); - } - #endregion - break; - case "Defect": - #region - limitThresholdVal = processParam.Value("LimitThresholdVal"); - lowerThresholdVal = processParam.Value("LowerThresholdVal"); - if (scannerGBmpQueue.Count < 1) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"缺陷检测异常,无源图像!!", WarningEnum.Low); - warning(WarningEnum.Low);//终止 - return stepIndex; - } - var bmpLoc = scannerGBmpQueue.Dequeue(); - AddTextEvent($"{stepIndex + 1}-{processName}", $"开始缺陷检测,源图索引:{defectBmpNum},图像队列数量: {scannerGBmpQueue.Count}..."); - string[] aarCut_size = processParam.Value("CutSize").Split(','); - string[] aarResize = processParam.Value("Resize").Split(','); - //图纸 - attachmentFile = model.AttachmentList.FirstOrDefault(x => x.Type == 0); - if (attachmentFile != null) - { - gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}"; - if (!File.Exists(gbxBmpPath + attachmentFile.ExtendName)) gbxBmpPath = ""; - } - AddTextEvent($"{stepIndex + 1}-{processName}", $"图纸路径:{gbxBmpPath}"); - devContainer.libDefect.add(new DefectTask() - { - stepIndex= stepIndex, - processName= processName, - drawingPagePath= gbxBmpPath, - index = defectBmpNum++, - bmp = bmpLoc.bmp, - Xmm = bmpLoc.Xmm, - Ymm = bmpLoc.Ymm, - cut_size = new System.Drawing.Size(Convert.ToInt32(aarCut_size[0]), Convert.ToInt32(aarCut_size[1])), - resize = new System.Drawing.Size(Convert.ToInt32(aarResize[0]), Convert.ToInt32(aarResize[1])), - thresholds = processParam.Value("Thresholds"), - thresholdsClass = processParam.Value("ThresholdsClass"), - recAreaThreshold= getProductAreaThreshol(model), //qxName,面积; qxName,面积; qxName,面积; - finishEvent = (res) => - { - if (res.isSucceed) - { - setDgvContentCol(liStatocStepIndex, $"源图索引:{res.index},缺陷数:{res.defectCount},处理时间(ms):{string.Join("->", res.stopwatch.Select(i => i.ToString()).ToArray())}"); - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"缺陷检测完成(源图索引:{res.index}),缺陷数:{res.defectCount},处理时间(ms):{string.Join("->", res.stopwatch.Select(i => i.ToString()).ToArray())}"); - string path; - if (res.defectCount > 0) - { - //UI显示小图 (含统计缺陷类型数量) - showDefectSmallBmps(res.bmps_tag, res.bmps_cut, res.Xmm, res.Ymm, res.informationList); - if (res.defectInfor2RestorationDeskPage != null && res.defectInfor2RestorationDeskPage.Count > 0) - { - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"转换后坐标数据:{JsonConvert.SerializeObject(res.defectInfor2RestorationDeskPage)}"); - if (order.DefectInfoList == null) - order.DefectInfoList = new List(); - foreach (var item in res.defectInfor2RestorationDeskPage) - order.DefectInfoList.Add(new DefectInfo() - { - Type = 0, - Code = item[3], - X = double.Parse(item[1]), - Y = double.Parse(item[2]), - ZXD = double.Parse(item[4]), - ModifyUserCode = Config.loginUser.Code, - CreateUserCode = Config.loginUser.Code, - }); - } - //保存原始大图 - if (Config.Defect_SavePath != "" && Directory.Exists(Config.Defect_SavePath)) - { - path = Util.createSubDir(Config.Defect_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); - path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}"; - //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//比.NET(File.Copy)更快 - //res.bmp.SaveImage(path + ".bmp");//opencv保存格式与BMP不同 - OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save(path + ".bmp", ImageFormat.Bmp); - File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.informationList)); - } - - //保存小图 - if (Config.Defect_Small_SavePath != "" && Directory.Exists(Config.Defect_Small_SavePath)) - { - path = Util.createSubDir(Config.Defect_Small_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); - path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_{ model.StepInfo.Name}"; - for (int i = 0; i < res.bmps_tag.Count(); i++) - res.bmps_tag[i].Save(path + $"_i{i}.bmp", ImageFormat.Bmp); - } - - //保存压缩大图 -- 用于修复台调用 - if (Config.Defect_Compress_SavePath != "" && Directory.Exists(Config.Defect_Compress_SavePath)) - { - path = Util.createSubDir(Config.Defect_Compress_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); - path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}"; - //res.bmpCompress.SaveImage(path + ".bmp");//opencv保存格式与BMP不同 - OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmpCompress).Save(path + ".bmp", ImageFormat.Bmp); - File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.defectInfor2RestorationDesk)); - } - } - else//没有缺陷 - { - if (Config.SaveAllDefectImg && Config.Defect_SavePath != "" && Directory.Exists(Config.Defect_SavePath)) - { - path = Util.createSubDir(Config.Defect_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); - path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}"; - //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//比.NET(File.Copy)更快 - //res.bmp.SaveImage(path + ".bmp");//opencv保存格式与BMP不同 - OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save(path + ".bmp", ImageFormat.Bmp); - - } - } - } - else - { - setDgvContentCol(liStatocStepIndex, $"失败:{res.resultInfo}"); - AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"缺陷检测失败:{res.resultInfo}"); - //warning(WarningEnum.Low);//暂停 这里不能暂停,stepIndex和scannerBmpQueue队列也不对了 - } - defectBmpNumResult++; - foreach (var item in res.bmps_cut) - item.Dispose(); - res.bmp.Dispose(); - res.bmp = null; - res.bmps_tag = null; - if (res.bmpCompress != null) - { - res.bmpCompress.Dispose(); - res.bmpCompress = null; - } - System.GC.Collect(); - } - }); - #endregion - break; - case "For": - #region - long UniqueId = processParam.Value("UniqueId"); - int GotoStepIndex = processParam.Value("GotoStepIndex");//1-n - int LimitNum = processParam.Value("LimitNum");//1-n - bool Reset = processParam.Value("Reset"); - if (GotoStepIndex - 1 == stepIndex) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"For死循环!!!"); - warning(WarningEnum.High); - return stepIndex; - } - if (!devContainer.libFor.dicData.ContainsKey(UniqueId)) - devContainer.libFor.dicData.Add(UniqueId, 0); - // - int Num = devContainer.libFor.dicData[UniqueId]; - Num++; - if (Num <= LimitNum) - { - if (Num == LimitNum) - { - setDgvContentCol(liStatocStepIndex, $"第[{Num}/{LimitNum}]次,循环完成"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"第[{Num}/{LimitNum}]次,循环完成。"); - } - else - { - setDgvContentCol(liStatocStepIndex, $"第[{Num}/{LimitNum}]次"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"第[{Num}/{LimitNum}]次跳转到步骤[{GotoStepIndex}]..."); - stepIndex = GotoStepIndex - 2; - } - devContainer.libFor.dicData[UniqueId] = Num; - } - else - { - setDgvContentCol(liStatocStepIndex, $"已失效不执行"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"本循环已失效不执行!"); - } - - //达到limit重置0 - if (devContainer.libFor.dicData[UniqueId] >= LimitNum && Reset) - { - devContainer.libFor.dicData[UniqueId] = 0; - setDgvContentCol(liStatocStepIndex, $"第[0/{LimitNum}]次"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器已重置。"); - } - #endregion - break; - case "If": - #region - long UniqueId_if = processParam.Value("UniqueId"); - int GotoStepIndex_if = processParam.Value("GotoStepIndex");//1-n - int LimitNum_if = processParam.Value("LimitNum");//1-n - bool Reset_if = processParam.Value("Reset"); - if (GotoStepIndex_if - 1 == stepIndex) - { - AddTextEvent($"{stepIndex + 1}-{processName}", $"If死循环,不可自我跳转!!!"); - warning(WarningEnum.High); - return stepIndex; - } - // - if (!devContainer.libIF.dicData.ContainsKey(UniqueId_if)) - devContainer.libIF.dicData.Add(UniqueId_if, 0); - // - int Num_if = devContainer.libIF.dicData[UniqueId_if]; - Num_if++; - if (Num_if <= LimitNum_if) - { - if (Num_if == LimitNum_if) - { - setDgvContentCol(liStatocStepIndex, $"第[{Num_if}/{LimitNum_if}]次,跳转至[{GotoStepIndex_if}]"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器[{Num_if}/{LimitNum_if}],跳转至步骤[{GotoStepIndex_if}]..."); - stepIndex = GotoStepIndex_if - 2; - } - else - { - setDgvContentCol(liStatocStepIndex, $"第[{Num_if}/{LimitNum_if}]次,不跳转"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器[{Num_if}/{LimitNum_if}],不跳转。"); - } - // - devContainer.libIF.dicData[UniqueId_if] = Num_if; - } - else - { - setDgvContentCol(liStatocStepIndex, $"已失效不执行"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"本IF已失效不执行。"); - } - - //达到limit重置0 - if (devContainer.libIF.dicData[UniqueId_if] >= LimitNum_if && Reset_if) - { - devContainer.libIF.dicData[UniqueId_if] = 0; - setDgvContentCol(liStatocStepIndex, $"第[0/{LimitNum_if}]次"); - AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器已重置。"); - } - #endregion - break; - default: - AddTextEvent($"{stepIndex + 1}-{processName}", $"未知工序:{processInfo.ProcessCode}"); - warning(WarningEnum.High); - return stepIndex; - } - if (sleepLater > 0) Thread.Sleep((int)sleepLater); - } - - //============结束,判断是否自动下料 - if (stepIndex == processList.Count - 1) - { - //厚度校正 直接更新并保存 - if (isProductRevise) - { - isProductRevise = false; - if (MessageBox.Show($"厚度校正完成,是否保存?\r\nBase值:{model.HeightBaseDec}", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - //保存 //更新指定列 - if (svcProduct.Update(it => new Product() { HeightBaseDec = model.HeightBaseDec }, it => it.Id == model.Id)) - AddTextEvent($"产品校正", $"保存成功。"); - else - AddTextEvent($"产品校正", $"保存失败!!"); - } - //下料 - currentState = CurrentStateEnum.自动流程结束; - gotoDownPT(); - } - else//生产 - { - //等待缺陷图显示完成 - while (defectBmpNum != defectBmpNumResult) - Thread.Sleep(100); - - //判断是否合格 - DefectCodeEnum defectCode; - string defectNames = ""; - if (model.QualifiedCriterionList!= null && model.QualifiedCriterionList.Count >0) - { - int itemDefectCount; - foreach (var item in model.QualifiedCriterionList) - { - defectCode = EnumUtil.Convert2Enum(item.DefectCode); - itemDefectCount = getDefectCountFromCode(order, defectCode); - if (item.MaxDefectCount>-1 && itemDefectCount > item.MaxDefectCount) - { - order.Qualified = false; - defectNames += $"{((DefectNameEnum)(int)defectCode).ToString()}({itemDefectCount}),"; - } - } - } - - stopWatch.Stop(); - long timeLen = stopWatch.ElapsedMilliseconds / 1000; - this.BeginInvoke(new System.Action(() => - { - lblTimeLen.Visible = true; - lblTimeLen.Text = $"检测时长: {timeLen} 秒"; - if (defectNames != "") - { - lblDefectResult.Text = "未通过"; - lblDefectResultCount.Text = defectNames.Substring(0, defectNames.Length - 1); - this.toolTip1.SetToolTip(lblDefectResultCount, lblDefectResultCount.Text); - lblDefectResult.ForeColor = lblDefectResultCount.ForeColor = Color.Red; - } - })); - order.TimeLen = timeLen; - order.DefectCount = (int)this.gboxDefectList.Tag; - order.Succeed = true; - order.ModifyUserCode = order.CreateUserCode = Config.loginUser.Code; - - order.Abnormalities = "";//无异常 - order.RepairCode = "";//无修复人员 - //如SN检测已存在,先删除 - var oldSNOrder= svcOrder.GetFirst(m=> m.SN==order.SN); - if(oldSNOrder!=null) - { - AddTextEvent("删除记录", $"删除上一重复SN检测记录:SN={oldSNOrder.SN}, Date={oldSNOrder.CreateTime}"); - svcOrder.DelNav(oldSNOrder); - } - if (!svcOrder.InsertNav(order))//导航插入 - AddTextEvent("保存失败", $"保存生产记录失败!"); - //更新本批次检测数量 - if (!string.IsNullOrWhiteSpace(model.BatchId)) - { - var expOrder = Expressionable.Create() - .And(m => m.ProductId == model.Id) - .And(m => m.BatchId == model.BatchId) - .ToExpression();//注意 这一句 不能少 - currProductModel.CompleteCount = svcOrder.Count(expOrder); - } - //以主键为条件更新CompleteCount单列值 - svcProduct.Update(it => new Product() { CompleteCount = currProductModel.CompleteCount }, it => it.Id == currProductModel.Id); - - if (Config.MakeTag && order.DefectCount > 0)//要打标 and 有缺陷图 - { - AddTextEvent("完成", $"工序结束,用时 {order.TimeLen} 秒;缺陷 {order.DefectCount} 张."); - //+(Config.MakeTag ? "开始自动打标...":"手动打标...")); - currentPT = CurrentPTEnum.MakeTag; - currentState = CurrentStateEnum.打标中; - setButtonEnabled(tsbtnGoDownPT, true); - setButtonEnabled(tsbtnReset, true); - setButtonEnabled(btnMakeTags, true); - //if (!Config.MakeTag)//自动打标 - { - this.Invoke(new System.Action(() => - { - btnMakeTag_Click(null, null); - })); - } - } - else//下料 - { - AddTextEvent("完成", $"用时 {order.TimeLen} 秒,进行下料..."); - currentState = CurrentStateEnum.自动流程结束; - gotoDownPT(); - } - } - - currProcessIndex = -1; - return -1; - } - else //继续 - { - return ++stepIndex; - //return nextProcess(model, ++stepIndex); - } - } - catch (Exception ex) - { - AddTextEvent("工序", $"[{stepIndex+1}] Err:" + ex.Message+"\n"+ex.StackTrace); - warning(WarningEnum.Low); - return -2; - } - } - private Dictionary getProductAreaThreshol(Product m) - { - Dictionary dic = new Dictionary(); - foreach(var item in m.QualifiedCriterionList) - dic.Add(item.DefectCode, (float)(item.Size * 25.4 * 25.4 / m.HoleCount / m.HoleCount) );//网目 => mm^2 - - //全缺陷项 - var lstDefect = Utils.EnumUtil.GetArrayList(); - foreach (DictionaryEntry item in lstDefect) - { - string code = item.Value.ToString(); - if (!dic.ContainsKey(code)) - dic.Add(code, 0); - } - - return dic; - } - private void setDgvContentCol(int rowIndex, string info) - { - int row = rowIndex;//why -1 ??? - this.Invoke(new System.Action(() => - { - this.dgvProcess.Rows[row].Cells["colValue"].Value = info; - })); - } - /// - /// 报警,只响应low,high - /// - private void warning(WarningEnum level, bool buzzer = true) - { - if (level == WarningEnum.Normal) - return; - - lock(myLock) - warningLevel = level; - if (level == WarningEnum.Low)//暂停 - { - currentState = CurrentStateEnum.暂停; - pauseCommand(buzzer); - } - else if (level == WarningEnum.High)//急停 - { - currentState = CurrentStateEnum.急停; - devContainer.devAxis.stopNow(); - - stopNowCommand(); - } - - //启用报警消除按钮 - this.Invoke(new System.Action(() => - { - tsbtnWarning.Enabled = true; - })); - } - private void updateTensionValue(double upperLimit,double lowerLimit) - { - int count = lstTension.Count(); - if (count < 1) return; - switch (count) - { - case 1: - order.Tension1 = lstTension[count - 1]; - AddTextEvent("张力值", $"张力1:{order.Tension1}"); - break; - case 2: - order.Tension2 = lstTension[count - 1]; - AddTextEvent("张力值", $"张力2:{order.Tension2}"); - break; - case 3: - order.Tension3 = lstTension[count - 1]; - AddTextEvent("张力值", $"张力3:{order.Tension3}"); - break; - case 4: - order.Tension4 = lstTension[count - 1]; - AddTextEvent("张力值", $"张力4:{order.Tension4}"); - break; - case 5: - order.Tension5 = lstTension[count - 1]; - AddTextEvent("张力值", $"张力5:{order.Tension5}"); - break; - } - - double value = Math.Round(lstTension.Average(), 2); - double valueMax = lstTension.Max(); - double valueMin = lstTension.Min(); - if (order != null) order.TensionValue = value; - Color color = (upperLimit+ lowerLimit>0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; - Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; - Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; - this.BeginInvoke(new System.Action(() => - { - this.lblTension.Text = Math.Round(value, 2).ToString(); - this.lblTension.ForeColor = color; - - this.lblTensionMax.Text = Math.Round(valueMax, 2).ToString(); - this.lblTensionMax.ForeColor = colorMax; - - this.lblTensionMin.Text = Math.Round(valueMin, 2).ToString(); - this.lblTensionMin.ForeColor = colorMin; - })); - //不合格 - if (color == Color.Red) order.Qualified = false; - } - private void updateHeightValue(double upperLimit, double lowerLimit) - { - int count = lstHeight.Count(); - if (count < 1) return; - AddTextEvent("厚度", string.Join(",", lstHeight)); - switch (count) - { - case 1: - order.Height1 = lstHeight[count - 1]; - AddTextEvent("厚度值", $"厚度1:{order.Height1}"); - break; - case 2: - order.Height2 = lstHeight[count - 1]; - AddTextEvent("厚度值", $"厚度2:{order.Height2}"); - break; - case 3: - order.Height3 = lstHeight[count - 1]; - AddTextEvent("厚度值", $"厚度3:{order.Height3}"); - break; - case 4: - order.Height4 = lstHeight[count - 1]; - AddTextEvent("厚度值", $"厚度4:{order.Height4}"); - break; - case 5: - order.Height5 = lstHeight[count - 1]; - AddTextEvent("厚度值", $"厚度5:{order.Height5}"); - break; - } - - double value = Math.Round(lstHeight.Average(), 2); - double valueMax = lstHeight.Max(); - double valueMin = lstHeight.Min(); - if (order != null) order.HeightValue = value; - Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; - Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; - Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; - this.Invoke(new System.Action(() => - { - this.lblHeight.Text = Math.Round(value, 2).ToString(); - this.lblHeight.ForeColor = color; - - this.lblHeightMax.Text = Math.Round(valueMax, 2).ToString(); - this.lblHeightMax.ForeColor = colorMax; - - this.lblHeightMin.Text = Math.Round(valueMin, 2).ToString(); - this.lblHeightMin.ForeColor = colorMin; - })); - //不合格 - if (color == Color.Red) order.Qualified = false; - } - private void updateLineWidthValue(double upperLimit, double lowerLimit) - { - int count = lstLineWidth.Count(); - if (count < 1) return; - switch (count) - { - case 1: - order.LineWidth1 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽1:{order.LineWidth1}"); - break; - case 2: - order.LineWidth2 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽2:{order.LineWidth2}"); - break; - case 3: - order.LineWidth3 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽3:{order.LineWidth3}"); - break; - case 4: - order.LineWidth4 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽4:{order.LineWidth4}"); - break; - case 5: - order.LineWidth5 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽5:{order.LineWidth5}"); - break; - case 6: - order.LineWidth6 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽6:{order.LineWidth6}"); - break; - case 7: - order.LineWidth7 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽7:{order.LineWidth7}"); - break; - case 8: - order.LineWidth8 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽8:{order.LineWidth8}"); - break; - case 9: - order.LineWidth9 = lstLineWidth[count - 1]; - AddTextEvent("线宽值", $"线宽9:{order.LineWidth9}"); - break; - } - List lstValidValue = new List(); - for (int i = 0; i < count; i++) - { - if (lstLineWidth[i] > 0) - lstValidValue.Add(lstLineWidth[i]); - } - if (lstValidValue.Count < 1) return;//WLQ 前面失败时会向lstLineWidth.add(0) - - double value = Math.Round(lstValidValue.Average(), 2); - double valueMax = lstValidValue.Max(); - double valueMin = lstValidValue.Min(); - if (order != null) order.LineWidthValue = value; - Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; - Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; - Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; - this.Invoke(new System.Action(() => - { - this.lblLineWidth.Text = Math.Round(value, 2).ToString(); - this.lblLineWidth.ForeColor = color; - - this.lblLineWidthMax.Text = Math.Round(valueMax, 2).ToString(); - this.lblLineWidthMax.ForeColor = colorMax; - - this.lblLineWidthMin.Text = Math.Round(valueMin, 2).ToString(); - this.lblLineWidthMin.ForeColor = colorMin; - })); - //不合格 - if (color == Color.Red) order.Qualified = false; - } - private void updatePTValue(double upperLimit, double lowerLimit) - { - //每次加2个:PT1,PT2 - int count = lstPT.Count(); - if (count < 1) return; - switch (count) - { - case 2: - order.PT1 = lstPT[count - 2]; - order.PT2 = lstPT[count - 1]; - AddTextEvent("PT值",$"PT1:{order.PT1},PT2:{order.PT2}"); - break; - case 4: - order.PT3 = lstPT[count - 2]; - order.PT4 = lstPT[count - 1]; - AddTextEvent("PT值", $"PT3:{order.PT3},PT4:{order.PT4}"); - break; - case 6: - order.PT5 = lstPT[count - 2]; - order.PT6 = lstPT[count - 1]; - AddTextEvent("PT值", $"PT5:{order.PT5},PT6:{order.PT6}"); - break; - } - - List lstValidValue = new List(); - for (int i = 0; i < count; i++) - { - if (lstPT[i] > 0) - lstValidValue.Add(lstPT[i]); - } - double value = Math.Round(lstValidValue.Average(), 4); - double valueMax = lstValidValue.Max(); - double valueMin = lstValidValue.Min(); - if (order != null) order.PTValue = value; - Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; - Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; - Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; - this.Invoke(new System.Action(() => - { - this.lblPT.Text = value.ToString(); - this.lblPT.ForeColor = color; - - this.lblPTMax.Text = Math.Round(valueMax, 4).ToString(); - this.lblPTMax.ForeColor = colorMax; - - this.lblPTMin.Text = Math.Round(valueMin, 4).ToString(); - this.lblPTMin.ForeColor = colorMin; - })); - //不合格 - if (color == Color.Red) order.Qualified = false; - } - private void updatePTValueTest(double upperLimit, double lowerLimit) - { - //每次加2个:PT1,PT2 - int count = lstPT.Count(); - if (count < 1) return; - switch (count) - { - case 1: - order.PT1 = lstPT[count - 1]; - AddTextEvent("PT1", $"PT1:{order.PT1}"); - break; - case 2: - order.PT2 = lstPT[count - 1]; - AddTextEvent("PT2", $"PT2:{order.PT2}"); - break; - case 3: - order.PT3 = lstPT[count - 1]; - order.PT4 = 0; - AddTextEvent("PT3", $"PT3:{order.PT3}"); - break; - case 4: - order.PT5 = lstPT[count - 1]; - AddTextEvent("PT4", $"PT4:{order.PT5}"); - break; - case 5: - order.PT6 = lstPT[count - 1]; - AddTextEvent("PT5", $"PT5:{order.PT6}"); - break; - } - - List lstValidValue = new List(); - for (int i = 0; i < count; i++) - { - if (lstPT[i] > 0) - lstValidValue.Add(lstPT[i]); - } - double value = Math.Round(lstValidValue.Average(), 4); - double valueMax = lstValidValue.Max(); - double valueMin = lstValidValue.Min(); - if (order != null) order.PTValue = value; - Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; - Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; - Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; - this.Invoke(new System.Action(() => - { - this.lblPT.Text = value.ToString(); - this.lblPT.ForeColor = color; - - this.lblPTMax.Text = Math.Round(valueMax, 4).ToString(); - this.lblPTMax.ForeColor = colorMax; - - this.lblPTMin.Text = Math.Round(valueMin, 4).ToString(); - this.lblPTMin.ForeColor = colorMin; - })); - //不合格 - if (color == Color.Red) order.Qualified = false; - } - private void updateCompareResult(bool compareResult) - { - this.Invoke(new System.Action(() => - { - this.lblCompareResult.Text = (order.CompareResult==1 ? "通过" : "未通过"); - if (!compareResult) - { - this.lblCompareResultCount.Text = (Convert.ToInt16(lblCompareResultCount.Text) + 1).ToString(); - this.lblCompareResult.ForeColor = lblCompareResultCount.ForeColor=Color.Red; - //不合格 - order.Qualified = false; - } - })); - } - private void resetUIValue() - { - this.Invoke(new System.Action(() => + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"Tag对应posePT: {tagOutData}", WarningEnum.Normal); + + if (order.SizeTagDataList == null) + order.SizeTagDataList = new List(); + order.SizeTagDataList.Add(new SizeTagData() + { + SizeTag = res.sizeTag, + CreateStepIndex = res.stepIndex + 1, + posePT= string.Join(",", res.posePT)// 回转 Array.ConvertAll(sNums , double.Parse); + }); + + } + + setDgvContentCol(liStatocStepIndex, $"index:{res.index},PT1:{res.PT1},PT2:{res.PT2},Shanxian:{res.Shanxian},Circle_Xmm:{res.Circle_Xmm},Circle_Ymm:{res.Circle_Ymm},offsetX:{res.offsetX},offsetY:{res.offsetY}, {tagOutData}"); + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测完成 index:{res.index},PT1:{res.PT1},PT2:{res.PT2},Shanxian:{res.Shanxian},Circle_Xmm:{res.Circle_Xmm},Circle_Ymm:{res.Circle_Ymm},offsetX:{res.offsetX},offsetY:{res.offsetY}, {tagOutData} "); + //测量 + //------TEST + if (res.index>20 && res.index<30) + { + lock (lstPT) + { + lstPT.Add(Math.Round(res.PT1, 4)); + updatePTValueTest(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue); + } + } + //------ + if (roundIndex > 0)//1-9测量 + { + if (res.index < 10)//11-13 (PT: 7-9 => 21-29(PT1)) 不用管,李工处理 + { + //if (roundIndex >= 7) + //{ + // lock (lstPT) + // { + // lstPT.Add(Math.Round(res.PT1, 4)); + // lstPT.Add(res.index == 8 ? 0 : Math.Round(res.PT2, 4)); + // updatePTValue(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue); + // } + //} + + lock (lstLineWidth) + { + lstLineWidth.Add(res.Shanxian > 0 ? Math.Round(res.Shanxian, 2) : 0); + updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue); + } + } + } + //校正偏移 10,20,30...:偏移 + else + { + AxMoveMode axSizeMode = AxMoveMode.绝对位置; + double xPos = 0; + double yPos = 0; + //绝对偏移 + if (res.offsetX != 0 || res.offsetY != 0) + { + xPos += res.offsetX; + yPos += res.offsetY; + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"offsetX/Y绝对校正, 0轴:{xPos}mm, 2轴:{yPos}mm"); + } + else if (res.Circle_Xmm != 0 || res.Circle_Ymm != 0)//相对偏移校正 + { + axSizeMode = AxMoveMode.相对位置; + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"原点相对校正, 0轴:{res.Circle_Xmm}mm, 2轴:{res.Circle_Ymm}mm"); + if (res.Circle_Xmm != 0) xPos = res.Circle_Xmm; + if (res.Circle_Ymm != 0) yPos = res.Circle_Ymm; + } + //当前工序直接移动 + if (xPos != 0 || yPos != 0) + { + devContainer.devAxis.setAxisVelParam(0.1, 1, 1, 1, 0); + devContainer.devAxis.setAxisVelParam(0.1, 1, 1, 1, 2); + if (xPos != 0) devContainer.devAxis.move_ptp(0, xPos, axSizeMode); + if (yPos != 0) devContainer.devAxis.move_ptp(2, yPos, axSizeMode); + while (!devContainer.devAxis.isReady(0) || !devContainer.devAxis.isReady(2)) + { + Thread.Sleep(100); + if (isBreakProcessRun()) + break; + } + } + } + + //保存 + //string sizeFileName = Config.Size_SavePath + "\\" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"); + //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//更快 + //File.WriteAllText(defectFileName + ".json", JsonConvert.SerializeObject(res.informationList)); + } + //失败 + else + { + //------TEST + if (res.index > 20 && res.index < 30) + { + lock (lstPT) + { + lstPT.Add(0); + updatePTValueTest(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue); + } + } + //------ + + if (roundIndex > 0) + { + //if (roundIndex >= 7) + //{ + // lock (lstPT) + // { + // lstPT.Add(0); + // lstPT.Add(0); + // updatePTValue(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue); + // } + //} + + lock (lstLineWidth) + { + lstLineWidth.Add(0); + updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue); + } + } + setDgvContentCol(liStatocStepIndex, $"失败:{res.resultInfo}"); + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测失败index:{res.index}:{res.resultInfo}"); + //warning(WarningEnum.Low);//暂停 这里不能暂停,stepIndex和scannerBmpQueue队列也不对了 + } + + //保存 + if (Config.SizeBmp_SavePath != "" && Directory.Exists(Config.SizeBmp_SavePath)) + { + string path = Util.createSubDir(Config.SizeBmp_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); + path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp"; + if (res.bmp != null) + res.bmp.Save(path, ImageFormat.Bmp); + else + API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快 + } + } + } + catch(Exception ex) + { + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测回调处理异常 index:{res.index},ex={ex.Message}"); + } + + // + //if (!asynRun)//是否异步执行endEvent.Set()都没问题 + endEvent.Set();//roundIndex=0成功或失败线程返回 + //--- + if (res.bmp != null) + { + res.bmp.Dispose(); + res.bmp = null; + } + else + { + API.DeleteFile(res.file_path); + } + } + }); + + //需等上面异步回调中的相对偏移校正完成再继续 + if (!asynRun || sizeIndex % 10==0) + { + if (!endEvent.WaitOne(60000)) + AddTextEvent($"{stepIndex + 1}-{processName}", $"{sizeIndex}等待超时,忽略继续!", WarningEnum.Low); + } + #endregion + break; + case "Defect": + #region + limitThresholdVal = processParam.Value("LimitThresholdVal"); + lowerThresholdVal = processParam.Value("LowerThresholdVal"); + if (scannerGBmpQueue.Count < 1) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"缺陷检测异常,无源图像!!", WarningEnum.Low); + warning(WarningEnum.Low);//终止 + return stepIndex; + } + var bmpLoc = scannerGBmpQueue.Dequeue(); + AddTextEvent($"{stepIndex + 1}-{processName}", $"开始缺陷检测,源图索引:{defectBmpNum},图像队列数量: {scannerGBmpQueue.Count}..."); + string[] aarCut_size = processParam.Value("CutSize").Split(','); + string[] aarResize = processParam.Value("Resize").Split(','); + //图纸 + attachmentFile = model.AttachmentList.FirstOrDefault(x => x.Type == 0); + if (attachmentFile != null) + { + gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}"; + if (!File.Exists(gbxBmpPath + attachmentFile.ExtendName)) gbxBmpPath = ""; + } + AddTextEvent($"{stepIndex + 1}-{processName}", $"图纸路径:{gbxBmpPath}"); + devContainer.libDefect.add(new DefectTask() + { + stepIndex= stepIndex, + processName= processName, + drawingPagePath= gbxBmpPath, + index = defectBmpNum++, + bmp = bmpLoc.bmp, + Xmm = bmpLoc.Xmm, + Ymm = bmpLoc.Ymm, + cut_size = new System.Drawing.Size(Convert.ToInt32(aarCut_size[0]), Convert.ToInt32(aarCut_size[1])), + resize = new System.Drawing.Size(Convert.ToInt32(aarResize[0]), Convert.ToInt32(aarResize[1])), + thresholds = processParam.Value("Thresholds"), + thresholdsClass = processParam.Value("ThresholdsClass"), + recAreaThreshold= getProductAreaThreshol(model), //qxName,面积; qxName,面积; qxName,面积; + finishEvent = (res) => + { + if (res.isSucceed) + { + setDgvContentCol(liStatocStepIndex, $"源图索引:{res.index},缺陷数:{res.defectCount},处理时间(ms):{string.Join("->", res.stopwatch.Select(i => i.ToString()).ToArray())}"); + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"缺陷检测完成(源图索引:{res.index}),缺陷数:{res.defectCount},处理时间(ms):{string.Join("->", res.stopwatch.Select(i => i.ToString()).ToArray())}"); + string path; + if (res.defectCount > 0) + { + //UI显示小图 (含统计缺陷类型数量) + showDefectSmallBmps(res.bmps_tag, res.bmps_cut, res.Xmm, res.Ymm, res.informationList); + if (res.defectInfor2RestorationDeskPage != null && res.defectInfor2RestorationDeskPage.Count > 0) + { + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"转换后坐标数据:{JsonConvert.SerializeObject(res.defectInfor2RestorationDeskPage)}"); + if (order.DefectInfoList == null) + order.DefectInfoList = new List(); + foreach (var item in res.defectInfor2RestorationDeskPage) + order.DefectInfoList.Add(new DefectInfo() + { + Type = 0, + Code = item[3], + X = double.Parse(item[1]), + Y = double.Parse(item[2]), + ZXD = double.Parse(item[4]), + ModifyUserCode = Config.loginUser.Code, + CreateUserCode = Config.loginUser.Code, + }); + } + //保存原始大图 + if (Config.Defect_SavePath != "" && Directory.Exists(Config.Defect_SavePath)) + { + path = Util.createSubDir(Config.Defect_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); + path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}"; + //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//比.NET(File.Copy)更快 + //res.bmp.SaveImage(path + ".bmp");//opencv保存格式与BMP不同 + OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save(path + ".bmp", ImageFormat.Bmp); + File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.informationList)); + } + + //保存小图 + if (Config.Defect_Small_SavePath != "" && Directory.Exists(Config.Defect_Small_SavePath)) + { + path = Util.createSubDir(Config.Defect_Small_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); + path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_{ model.StepInfo.Name}"; + for (int i = 0; i < res.bmps_tag.Count(); i++) + res.bmps_tag[i].Save(path + $"_i{i}.bmp", ImageFormat.Bmp); + } + + //保存压缩大图 -- 用于修复台调用 + if (Config.Defect_Compress_SavePath != "" && Directory.Exists(Config.Defect_Compress_SavePath)) + { + path = Util.createSubDir(Config.Defect_Compress_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); + path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}"; + //res.bmpCompress.SaveImage(path + ".bmp");//opencv保存格式与BMP不同 + OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmpCompress).Save(path + ".bmp", ImageFormat.Bmp); + File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.defectInfor2RestorationDesk)); + } + } + else//没有缺陷 + { + if (Config.SaveAllDefectImg && Config.Defect_SavePath != "" && Directory.Exists(Config.Defect_SavePath)) + { + path = Util.createSubDir(Config.Defect_SavePath, new List { order.CreateTime.ToString("yyyyMMdd"), order.SN }); + path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}"; + //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//比.NET(File.Copy)更快 + //res.bmp.SaveImage(path + ".bmp");//opencv保存格式与BMP不同 + OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save(path + ".bmp", ImageFormat.Bmp); + + } + } + } + else + { + setDgvContentCol(liStatocStepIndex, $"失败:{res.resultInfo}"); + AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"缺陷检测失败:{res.resultInfo}"); + //warning(WarningEnum.Low);//暂停 这里不能暂停,stepIndex和scannerBmpQueue队列也不对了 + } + defectBmpNumResult++; + foreach (var item in res.bmps_cut) + item.Dispose(); + res.bmp.Dispose(); + res.bmp = null; + res.bmps_tag = null; + if (res.bmpCompress != null) + { + res.bmpCompress.Dispose(); + res.bmpCompress = null; + } + System.GC.Collect(); + } + }); + #endregion + break; + case "For": + #region + long UniqueId = processParam.Value("UniqueId"); + int GotoStepIndex = processParam.Value("GotoStepIndex");//1-n + int LimitNum = processParam.Value("LimitNum");//1-n + bool Reset = processParam.Value("Reset"); + if (GotoStepIndex - 1 == stepIndex) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"For死循环!!!"); + warning(WarningEnum.High); + return stepIndex; + } + if (!devContainer.libFor.dicData.ContainsKey(UniqueId)) + devContainer.libFor.dicData.Add(UniqueId, 0); + // + int Num = devContainer.libFor.dicData[UniqueId]; + Num++; + if (Num <= LimitNum) + { + if (Num == LimitNum) + { + setDgvContentCol(liStatocStepIndex, $"第[{Num}/{LimitNum}]次,循环完成"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"第[{Num}/{LimitNum}]次,循环完成。"); + } + else + { + setDgvContentCol(liStatocStepIndex, $"第[{Num}/{LimitNum}]次"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"第[{Num}/{LimitNum}]次跳转到步骤[{GotoStepIndex}]..."); + stepIndex = GotoStepIndex - 2; + } + devContainer.libFor.dicData[UniqueId] = Num; + } + else + { + setDgvContentCol(liStatocStepIndex, $"已失效不执行"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"本循环已失效不执行!"); + } + + //达到limit重置0 + if (devContainer.libFor.dicData[UniqueId] >= LimitNum && Reset) + { + devContainer.libFor.dicData[UniqueId] = 0; + setDgvContentCol(liStatocStepIndex, $"第[0/{LimitNum}]次"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器已重置。"); + } + #endregion + break; + case "If": + #region + long UniqueId_if = processParam.Value("UniqueId"); + int GotoStepIndex_if = processParam.Value("GotoStepIndex");//1-n + int LimitNum_if = processParam.Value("LimitNum");//1-n + bool Reset_if = processParam.Value("Reset"); + if (GotoStepIndex_if - 1 == stepIndex) + { + AddTextEvent($"{stepIndex + 1}-{processName}", $"If死循环,不可自我跳转!!!"); + warning(WarningEnum.High); + return stepIndex; + } + // + if (!devContainer.libIF.dicData.ContainsKey(UniqueId_if)) + devContainer.libIF.dicData.Add(UniqueId_if, 0); + // + int Num_if = devContainer.libIF.dicData[UniqueId_if]; + Num_if++; + if (Num_if <= LimitNum_if) + { + if (Num_if == LimitNum_if) + { + setDgvContentCol(liStatocStepIndex, $"第[{Num_if}/{LimitNum_if}]次,跳转至[{GotoStepIndex_if}]"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器[{Num_if}/{LimitNum_if}],跳转至步骤[{GotoStepIndex_if}]..."); + stepIndex = GotoStepIndex_if - 2; + } + else + { + setDgvContentCol(liStatocStepIndex, $"第[{Num_if}/{LimitNum_if}]次,不跳转"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器[{Num_if}/{LimitNum_if}],不跳转。"); + } + // + devContainer.libIF.dicData[UniqueId_if] = Num_if; + } + else + { + setDgvContentCol(liStatocStepIndex, $"已失效不执行"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"本IF已失效不执行。"); + } + + //达到limit重置0 + if (devContainer.libIF.dicData[UniqueId_if] >= LimitNum_if && Reset_if) + { + devContainer.libIF.dicData[UniqueId_if] = 0; + setDgvContentCol(liStatocStepIndex, $"第[0/{LimitNum_if}]次"); + AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器已重置。"); + } + #endregion + break; + default: + AddTextEvent($"{stepIndex + 1}-{processName}", $"未知工序:{processInfo.ProcessCode}"); + warning(WarningEnum.High); + return stepIndex; + } + if (sleepLater > 0) Thread.Sleep((int)sleepLater); + } + + //============结束,判断是否自动下料 + if (stepIndex == processList.Count - 1) + { + //厚度校正 直接更新并保存 + if (isProductRevise) + { + isProductRevise = false; + if (MessageBox.Show($"厚度校正完成,是否保存?\r\nBase值:{model.HeightBaseDec}", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + //保存 //更新指定列 + if (svcProduct.Update(it => new Product() { HeightBaseDec = model.HeightBaseDec }, it => it.Id == model.Id)) + AddTextEvent($"产品校正", $"保存成功。"); + else + AddTextEvent($"产品校正", $"保存失败!!"); + } + //下料 + currentState = CurrentStateEnum.自动流程结束; + gotoDownPT(); + } + else//生产 + { + //等待缺陷图显示完成 + while (defectBmpNum != defectBmpNumResult) + Thread.Sleep(100); + + //判断是否合格 + DefectCodeEnum defectCode; + string defectNames = ""; + if (model.QualifiedCriterionList!= null && model.QualifiedCriterionList.Count >0) + { + int itemDefectCount; + foreach (var item in model.QualifiedCriterionList) + { + defectCode = EnumUtil.Convert2Enum(item.DefectCode); + itemDefectCount = getDefectCountFromCode(order, defectCode); + if (item.MaxDefectCount>-1 && itemDefectCount > item.MaxDefectCount) + { + order.Qualified = false; + defectNames += $"{((DefectNameEnum)(int)defectCode).ToString()}({itemDefectCount}),"; + } + } + } + + stopWatch.Stop(); + long timeLen = stopWatch.ElapsedMilliseconds / 1000; + this.BeginInvoke(new System.Action(() => + { + lblTimeLen.Visible = true; + lblTimeLen.Text = $"检测时长: {timeLen} 秒"; + if (defectNames != "") + { + lblDefectResult.Text = "未通过"; + lblDefectResultCount.Text = defectNames.Substring(0, defectNames.Length - 1); + this.toolTip1.SetToolTip(lblDefectResultCount, lblDefectResultCount.Text); + lblDefectResult.ForeColor = lblDefectResultCount.ForeColor = Color.Red; + } + })); + order.TimeLen = timeLen; + order.DefectCount = (int)this.gboxDefectList.Tag; + order.Succeed = true; + order.ModifyUserCode = order.CreateUserCode = Config.loginUser.Code; + + order.Abnormalities = "";//无异常 + order.RepairCode = "";//无修复人员 + //如SN检测已存在,先删除 + var oldSNOrder= svcOrder.GetFirst(m=> m.SN==order.SN); + if(oldSNOrder!=null) + { + AddTextEvent("删除记录", $"删除上一重复SN检测记录:SN={oldSNOrder.SN}, Date={oldSNOrder.CreateTime}"); + svcOrder.DelNav(oldSNOrder); + } + if (!svcOrder.InsertNav(order))//导航插入 + AddTextEvent("保存失败", $"保存生产记录失败!"); + //更新本批次检测数量 + if (!string.IsNullOrWhiteSpace(model.BatchId)) + { + var expOrder = Expressionable.Create() + .And(m => m.ProductId == model.Id) + .And(m => m.BatchId == model.BatchId) + .ToExpression();//注意 这一句 不能少 + currProductModel.CompleteCount = svcOrder.Count(expOrder); + } + //以主键为条件更新CompleteCount单列值 + svcProduct.Update(it => new Product() { CompleteCount = currProductModel.CompleteCount }, it => it.Id == currProductModel.Id); + + if (Config.MakeTag && order.DefectCount > 0)//要打标 and 有缺陷图 + { + AddTextEvent("完成", $"工序结束,用时 {order.TimeLen} 秒;缺陷 {order.DefectCount} 张."); + //+(Config.MakeTag ? "开始自动打标...":"手动打标...")); + currentPT = CurrentPTEnum.MakeTag; + currentState = CurrentStateEnum.打标中; + setButtonEnabled(tsbtnGoDownPT, true); + setButtonEnabled(tsbtnReset, true); + setButtonEnabled(btnMakeTags, true); + //if (!Config.MakeTag)//自动打标 + { + this.Invoke(new System.Action(() => + { + btnMakeTag_Click(null, null); + })); + } + } + else//下料 + { + AddTextEvent("完成", $"用时 {order.TimeLen} 秒,进行下料..."); + currentState = CurrentStateEnum.自动流程结束; + gotoDownPT(); + } + } + + currProcessIndex = -1; + return -1; + } + else //继续 + { + return ++stepIndex; + //return nextProcess(model, ++stepIndex); + } + } + catch (Exception ex) + { + AddTextEvent("工序", $"[{stepIndex+1}] Err:" + ex.Message+"\n"+ex.StackTrace); + warning(WarningEnum.Low); + return -2; + } + } + private Dictionary getProductAreaThreshol(Product m) + { + Dictionary dic = new Dictionary(); + foreach(var item in m.QualifiedCriterionList) + dic.Add(item.DefectCode, (float)(item.Size * 25.4 * 25.4 / m.HoleCount / m.HoleCount) );//网目 => mm^2 + + //全缺陷项 + var lstDefect = Utils.EnumUtil.GetArrayList(); + foreach (DictionaryEntry item in lstDefect) + { + string code = item.Value.ToString(); + if (!dic.ContainsKey(code)) + dic.Add(code, 0); + } + + return dic; + } + private void setDgvContentCol(int rowIndex, string info) + { + int row = rowIndex;//why -1 ??? + this.Invoke(new System.Action(() => + { + this.dgvProcess.Rows[row].Cells["colValue"].Value = info; + })); + } + /// + /// 报警,只响应low,high + /// + private void warning(WarningEnum level, bool buzzer = true) + { + if (level == WarningEnum.Normal) + return; + + lock(myLock) + warningLevel = level; + if (level == WarningEnum.Low)//暂停 + { + currentState = CurrentStateEnum.暂停; + pauseCommand(buzzer); + } + else if (level == WarningEnum.High)//急停 + { + currentState = CurrentStateEnum.急停; + devContainer.devAxis.stopNow(); + + stopNowCommand(); + } + + //启用报警消除按钮 + this.Invoke(new System.Action(() => + { + tsbtnWarning.Enabled = true; + })); + } + private void updateTensionValue(double upperLimit,double lowerLimit) + { + int count = lstTension.Count(); + if (count < 1) return; + switch (count) + { + case 1: + order.Tension1 = lstTension[count - 1]; + AddTextEvent("张力值", $"张力1:{order.Tension1}"); + break; + case 2: + order.Tension2 = lstTension[count - 1]; + AddTextEvent("张力值", $"张力2:{order.Tension2}"); + break; + case 3: + order.Tension3 = lstTension[count - 1]; + AddTextEvent("张力值", $"张力3:{order.Tension3}"); + break; + case 4: + order.Tension4 = lstTension[count - 1]; + AddTextEvent("张力值", $"张力4:{order.Tension4}"); + break; + case 5: + order.Tension5 = lstTension[count - 1]; + AddTextEvent("张力值", $"张力5:{order.Tension5}"); + break; + } + + double value = Math.Round(lstTension.Average(), 2); + double valueMax = lstTension.Max(); + double valueMin = lstTension.Min(); + if (order != null) order.TensionValue = value; + Color color = (upperLimit+ lowerLimit>0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; + Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; + Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; + this.BeginInvoke(new System.Action(() => + { + this.lblTension.Text = Math.Round(value, 2).ToString(); + this.lblTension.ForeColor = color; + + this.lblTensionMax.Text = Math.Round(valueMax, 2).ToString(); + this.lblTensionMax.ForeColor = colorMax; + + this.lblTensionMin.Text = Math.Round(valueMin, 2).ToString(); + this.lblTensionMin.ForeColor = colorMin; + })); + //不合格 + if (color == Color.Red) order.Qualified = false; + } + private void updateHeightValue(double upperLimit, double lowerLimit) + { + int count = lstHeight.Count(); + if (count < 1) return; + AddTextEvent("厚度", string.Join(",", lstHeight)); + switch (count) + { + case 1: + order.Height1 = lstHeight[count - 1]; + AddTextEvent("厚度值", $"厚度1:{order.Height1}"); + break; + case 2: + order.Height2 = lstHeight[count - 1]; + AddTextEvent("厚度值", $"厚度2:{order.Height2}"); + break; + case 3: + order.Height3 = lstHeight[count - 1]; + AddTextEvent("厚度值", $"厚度3:{order.Height3}"); + break; + case 4: + order.Height4 = lstHeight[count - 1]; + AddTextEvent("厚度值", $"厚度4:{order.Height4}"); + break; + case 5: + order.Height5 = lstHeight[count - 1]; + AddTextEvent("厚度值", $"厚度5:{order.Height5}"); + break; + } + + double value = Math.Round(lstHeight.Average(), 2); + double valueMax = lstHeight.Max(); + double valueMin = lstHeight.Min(); + if (order != null) order.HeightValue = value; + Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; + Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; + Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; + this.Invoke(new System.Action(() => + { + this.lblHeight.Text = Math.Round(value, 2).ToString(); + this.lblHeight.ForeColor = color; + + this.lblHeightMax.Text = Math.Round(valueMax, 2).ToString(); + this.lblHeightMax.ForeColor = colorMax; + + this.lblHeightMin.Text = Math.Round(valueMin, 2).ToString(); + this.lblHeightMin.ForeColor = colorMin; + })); + //不合格 + if (color == Color.Red) order.Qualified = false; + } + private void updateLineWidthValue(double upperLimit, double lowerLimit) + { + int count = lstLineWidth.Count(); + if (count < 1) return; + switch (count) + { + case 1: + order.LineWidth1 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽1:{order.LineWidth1}"); + break; + case 2: + order.LineWidth2 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽2:{order.LineWidth2}"); + break; + case 3: + order.LineWidth3 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽3:{order.LineWidth3}"); + break; + case 4: + order.LineWidth4 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽4:{order.LineWidth4}"); + break; + case 5: + order.LineWidth5 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽5:{order.LineWidth5}"); + break; + case 6: + order.LineWidth6 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽6:{order.LineWidth6}"); + break; + case 7: + order.LineWidth7 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽7:{order.LineWidth7}"); + break; + case 8: + order.LineWidth8 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽8:{order.LineWidth8}"); + break; + case 9: + order.LineWidth9 = lstLineWidth[count - 1]; + AddTextEvent("线宽值", $"线宽9:{order.LineWidth9}"); + break; + } + List lstValidValue = new List(); + for (int i = 0; i < count; i++) + { + if (lstLineWidth[i] > 0) + lstValidValue.Add(lstLineWidth[i]); + } + if (lstValidValue.Count < 1) return;//WLQ 前面失败时会向lstLineWidth.add(0) + + double value = Math.Round(lstValidValue.Average(), 2); + double valueMax = lstValidValue.Max(); + double valueMin = lstValidValue.Min(); + if (order != null) order.LineWidthValue = value; + Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; + Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; + Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; + this.Invoke(new System.Action(() => + { + this.lblLineWidth.Text = Math.Round(value, 2).ToString(); + this.lblLineWidth.ForeColor = color; + + this.lblLineWidthMax.Text = Math.Round(valueMax, 2).ToString(); + this.lblLineWidthMax.ForeColor = colorMax; + + this.lblLineWidthMin.Text = Math.Round(valueMin, 2).ToString(); + this.lblLineWidthMin.ForeColor = colorMin; + })); + //不合格 + if (color == Color.Red) order.Qualified = false; + } + private void updatePTValue(double upperLimit, double lowerLimit) + { + //每次加2个:PT1,PT2 + int count = lstPT.Count(); + if (count < 1) return; + switch (count) + { + case 2: + order.PT1 = lstPT[count - 2]; + order.PT2 = lstPT[count - 1]; + AddTextEvent("PT值",$"PT1:{order.PT1},PT2:{order.PT2}"); + break; + case 4: + order.PT3 = lstPT[count - 2]; + order.PT4 = lstPT[count - 1]; + AddTextEvent("PT值", $"PT3:{order.PT3},PT4:{order.PT4}"); + break; + case 6: + order.PT5 = lstPT[count - 2]; + order.PT6 = lstPT[count - 1]; + AddTextEvent("PT值", $"PT5:{order.PT5},PT6:{order.PT6}"); + break; + } + + List lstValidValue = new List(); + for (int i = 0; i < count; i++) + { + if (lstPT[i] > 0) + lstValidValue.Add(lstPT[i]); + } + double value = Math.Round(lstValidValue.Average(), 4); + double valueMax = lstValidValue.Max(); + double valueMin = lstValidValue.Min(); + if (order != null) order.PTValue = value; + Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; + Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; + Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; + this.Invoke(new System.Action(() => + { + this.lblPT.Text = value.ToString(); + this.lblPT.ForeColor = color; + + this.lblPTMax.Text = Math.Round(valueMax, 4).ToString(); + this.lblPTMax.ForeColor = colorMax; + + this.lblPTMin.Text = Math.Round(valueMin, 4).ToString(); + this.lblPTMin.ForeColor = colorMin; + })); + //不合格 + if (color == Color.Red) order.Qualified = false; + } + private void updatePTValueTest(double upperLimit, double lowerLimit) + { + //每次加2个:PT1,PT2 + int count = lstPT.Count(); + if (count < 1) return; + switch (count) + { + case 1: + order.PT1 = lstPT[count - 1]; + AddTextEvent("PT1", $"PT1:{order.PT1}"); + break; + case 2: + order.PT2 = lstPT[count - 1]; + AddTextEvent("PT2", $"PT2:{order.PT2}"); + break; + case 3: + order.PT3 = lstPT[count - 1]; + order.PT4 = 0; + AddTextEvent("PT3", $"PT3:{order.PT3}"); + break; + case 4: + order.PT5 = lstPT[count - 1]; + AddTextEvent("PT4", $"PT4:{order.PT5}"); + break; + case 5: + order.PT6 = lstPT[count - 1]; + AddTextEvent("PT5", $"PT5:{order.PT6}"); + break; + } + + List lstValidValue = new List(); + for (int i = 0; i < count; i++) + { + if (lstPT[i] > 0) + lstValidValue.Add(lstPT[i]); + } + double value = Math.Round(lstValidValue.Average(), 4); + double valueMax = lstValidValue.Max(); + double valueMin = lstValidValue.Min(); + if (order != null) order.PTValue = value; + Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White; + Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White; + Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White; + this.Invoke(new System.Action(() => + { + this.lblPT.Text = value.ToString(); + this.lblPT.ForeColor = color; + + this.lblPTMax.Text = Math.Round(valueMax, 4).ToString(); + this.lblPTMax.ForeColor = colorMax; + + this.lblPTMin.Text = Math.Round(valueMin, 4).ToString(); + this.lblPTMin.ForeColor = colorMin; + })); + //不合格 + if (color == Color.Red) order.Qualified = false; + } + private void updateCompareResult(bool compareResult) + { + this.Invoke(new System.Action(() => + { + this.lblCompareResult.Text = (order.CompareResult==1 ? "通过" : "未通过"); + if (!compareResult) + { + this.lblCompareResultCount.Text = (Convert.ToInt16(lblCompareResultCount.Text) + 1).ToString(); + this.lblCompareResult.ForeColor = lblCompareResultCount.ForeColor=Color.Red; + //不合格 + order.Qualified = false; + } + })); + } + private void resetUIValue() + { + this.Invoke(new System.Action(() => { //保持产品名称和料号 //txtProductName.Text = txtProductCode.Text = txtProductSN.Text = ""; txtProductSN.Text = ""; - lstHeight.Clear(); - lstLineWidth.Clear(); - lstTension.Clear(); - lstPT.Clear(); - this.lblTension.Text = this.lblHeight.Text = this.lblLineWidth.Text = "0.00"; - this.lblPT.Text = this.lblPTMax.Text= this.lblPTMin.Text="0.0000"; - this.lblCompareResult.Text =this.lblDefectResult.Text = "无"; - - this.lblTensionMax.Text = this.lblHeightMax.Text = this.lblLineWidthMax.Text - = this.lblTensionMin.Text = this.lblHeightMin.Text = this.lblLineWidthMin.Text = "0.00"; - - this.lblCompareResultCount.Text = "0"; - this.lblDefectResultCount.Text = "无"; - this.toolTip1.SetToolTip(lblDefectResultCount, lblDefectResultCount.Text); - // - this.lblTension.ForeColor = this.lblHeight.ForeColor = this.lblLineWidth.ForeColor = this.lblPT.ForeColor = this.lblCompareResult.ForeColor= this.lblDefectResult.ForeColor=Color.White; - this.lblTensionMax.ForeColor = this.lblHeightMax.ForeColor = this.lblLineWidthMax.ForeColor = this.lblPTMax.ForeColor - = this.lblTensionMin.ForeColor = this.lblHeightMin.ForeColor = this.lblLineWidthMin.ForeColor = this.lblPTMin.ForeColor = Color.White; - this.lblCompareResultCount.ForeColor = this.lblDefectResultCount.ForeColor=Color.White; - - this.dgvProcess.DataSource = null; - this.lstLog.Items.Clear(); - this.clearDefectBmps(); - - this.picScanner1.Image = this.picScanner2.Image = null; - picScanner1.Refresh(); - picScanner2.Refresh(); - - this.btnMakeTags.Enabled = false; - })); - } - //info: [{"1":[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]]}, - private void showDefectSmallBmps(Bitmap[] bmps, Mat[] bmps_cut, double Xmm, double Ymm, List[]>> info) - { - this.Invoke(new System.Action(() => - { - int imgWidth = this.pnlBmpList.ClientSize.Width - 50; - int imgHeight = (int)((bmps[0].Height * 1.0f / bmps[0].Width) * imgWidth + 0.5); - int splitWidth = 20; - int pnlWidth = this.pnlBmpList.ClientSize.Width; - int index = (int)this.gboxDefectList.Tag; - for (int x = 0; x < info.Count(); x++) - { - foreach (var item in info[x]) //单个info[x] = {"1":[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]]} - { - //统计缺陷类型 - countDefectClass(item.Value);//[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]] - - // - PictureBox picbox = new PictureBox(); - picbox.Width = imgWidth; - picbox.Height = imgHeight; - CheckBox checkBox = new CheckBox(); - picbox.Image = (Bitmap)bmps[x].Clone(); - picbox.Name = "imgDefect_" + index; - picbox.Tag = item.Key + "," + Xmm + "," + Ymm; - - checkBox.Tag = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(bmps_cut[item.Key]); //Mat转Bitmap ;//原始小图 - checkBox.Name = "chkDefect_" + index; - checkBox.Text = $"第{index + 1}张"; - checkBox.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged); - if (Config.MakeTag)//自动打标 - { - checkBox.Checked = true; - checkBox.Enabled = false; - } - picbox.Click += new EventHandler(defectBmpBox_Click); - picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; - picbox.BorderStyle = BorderStyle.FixedSingle; - picbox.Margin = new Padding((pnlWidth - picbox.Width) / 2, splitWidth,0, 0); - checkBox.Margin = new Padding((pnlWidth - checkBox.Width) / 2 + splitWidth, - 0, 0, 0); - - // - //if (this.pnlBmpList.Controls.Count > 0) - //{ - // if ((this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + imgWidth + splitWidth) > this.pnlBmpList.Width) - // picbox.Location = new System.Drawing.Point(splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Bottom + splitWidth); - // else - // picbox.Location = new System.Drawing.Point(this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Location.Y); - //} - //else - //{ - // picbox.Location = new System.Drawing.Point(splitWidth, 0); - //} - //checkBox.Location = new System.Drawing.Point(picbox.Location.X + 5, picbox.Location.Y + 5); - //checkBox.ForeColor = Color.Black; - this.pnlBmpList.Controls.Add(picbox); - this.pnlBmpList.Controls.Add(checkBox); - break; - } - - // - index++; - }; - this.gboxDefectList.Tag = index; - this.gboxDefectList.Text = $"缺陷图像:{index} 张"; - if (Config.MakeTag) { - lblDefectAddTag.Text = $"待打标数:{index}"; - lblDefectAddTag.Tag = index; - } - pnlBmpList.VerticalScroll.Value = pnlBmpList.VerticalScroll.Maximum; - })); - } - //统计缺陷类型 [["92.7542","80.85799","99.54083","86.05363","dk","0.52"]] - private void countDefectClass(List[] list) - { - string className; - for(int i=0; i - /// 异步输出日志 - /// - /// 模板标识 - /// 内容 - /// - private void AddTextEvent(string tag, string msg, WarningEnum level = WarningEnum.Normal) - { - try - { - if (InvokeRequired) - { - Invoke(new AddTextDelegate(AddTextEvent), new object[] - { - tag, - msg, - level - }); - } - else - { - if (tag != null && tag != "") - tag = $" - [{tag}]"; - - var now = DateTime.Now; - msg = now.ToString("HH:mm:ss fff") + tag + " - " + msg; - //cont = MyHelper.subString(cont, 300); - - //写日志,warn和error日志直接写 - writeLog(now, level, msg); - - // - //if (type > 0) - // cont = $"{cont}"; - - msg = (level == WarningEnum.Normal ? "B" : level == WarningEnum.Low ? "Y" : "R") + msg; - this.Invoke(new System.Action(() => - { - if (this.lstLog.Items.Count > 1000) - this.lstLog.Items.Clear(); - lstLog.Items.Insert(0, msg); - })); - //日志滚动 - //lstLog.SelectedIndex = lstLog.Items.Count - 1; - } - } - catch (Exception ex) - { - //MessageBox.Show("AddTextEvent ex=(" + ex.Message + ")", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - } - } - private void lstLog_DrawItem(object sender, DrawItemEventArgs e) - { - e.DrawBackground(); - if (e.Index < 0) return; - - string str = lstLog.Items[e.Index].ToString(); - e.Graphics.DrawString(str.Substring(1), e.Font, - new SolidBrush(str[0] == 'R' ? Color.Red : (str[0] == 'Y' ? Color.Orange : Color.Black)), - e.Bounds); - } - private void writeLog(DateTime now, WarningEnum level, string text) - { - string directory = Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\"; - //if (type == 0) directory = Application.StartupPath + "\\Log\\Info\\"; - //else if (type == 1) directory = Application.StartupPath + "\\Log\\Warn\\"; - //else directory = Application.StartupPath + "\\Log\\Error\\"; - - if (!System.IO.Directory.Exists(directory)) - System.IO.Directory.CreateDirectory(directory); - - File.AppendAllText(directory + now.ToString("yyyyMMdd") + ".log", text + "\r\n"); - } - - private void FrmMian_FormClosing(object sender, FormClosingEventArgs e) - { - if (devContainer.state) - { - MessageBox.Show("请先停止生产后才能关闭程序!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); - e.Cancel = true; - return; - } - - if (!bExitApp && MessageBox.Show($"确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - e.Cancel = true; - return; - } - } - private void FrmMian_FormClosed(object sender, FormClosedEventArgs e) - { - webService.stop(); - Application.Exit(); - System.GC.Collect(); - System.Environment.Exit(0); - } - private void tsbtnOpenDev_Click(object sender, EventArgs e) - { - //FrmGetPosByPic frr = new FrmGetPosByPic(new SizeLibProp()); - //frr.ShowDialog(); - - Config.LoadAllConfig(); - //设置程序最小/大线程池 - // Get the current settings. - int minWorker, minIOC; - ThreadPool.GetMinThreads(out minWorker, out minIOC); - ThreadPool.SetMinThreads(25, minIOC); - //ThreadPool.SetMaxThreads(256, 256); - - this.tsbtnProductRevise.Enabled = false; - this.tsbtnOpenDev.Enabled = false; - //scannerCBmpIndex = 0; - - isProductRevise = false; - this.resetUIValue(); - currProcessIndex = -1; - currentState = CurrentStateEnum.等待复位; - warningLevel = WarningEnum.Normal; - currentPT = CurrentPTEnum.InitPT; - this.tsbtnWarning.Enabled=this.tsbtnGoDownPT.Enabled=this.tsbtnStart.Enabled=this.tsbtnStopNow.Enabled=this.tsbtnPause.Enabled=this.tsbtnReset.Enabled=false; - //后台线程回调事件 - devContainer.StateChange = (state, msg) => - { - if (state) - { - //全局中断 - devContainer.devIOCard.INEvent = globalBreakEvent; - devContainer.OutDebugEvent = (tag, debugInfo) => - { - AddTextEvent(tag, debugInfo); - }; - // - AddTextEvent("设备启动", "请先进行复位操作!"); - this.Invoke(new System.Action(() => - { - this.tsbtnReset.Enabled = true; - tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled - = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = false; - - this.tsbtnOpenDev.Enabled = true; - this.tsbtnOpenDev.Visible = false; - this.tsbtnCloseDev.Visible = true; - })); - - timer.Elapsed += Timer_Elapsed; - timer.Interval = 500; - timer.Start(); - } - else - { - AddTextEvent("设备启动", $"启动失败,{msg}", WarningEnum.High); - this.Invoke(new System.Action(() => - { - this.tsbtnOpenDev.Enabled = true; - this.tsbtnOpenDev.Visible = true; - this.tsbtnCloseDev.Visible = false; - })); - } - - }; - devContainer.WarningEvent = (level, msg) => - { - AddTextEvent("设备事件", msg, level); - if (level == WarningEnum.High) - warning(level,true); - }; - devContainer.start(this.picScanner1.Handle, this.picScanner2.Handle); - } - - private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) - { - this.Invoke(new System.Action(() => - { - this.tsAxisState.Text = $"[命令位:{devContainer.devAxis.CmdPos[0]} 反馈位:{devContainer.devAxis.ActualPos[0]}] | " + - $"[命令位:{devContainer.devAxis.CmdPos[1]} 反馈位:{devContainer.devAxis.ActualPos[1]}] | " + - $"[命令位:{devContainer.devAxis.CmdPos[2]} 反馈位:{devContainer.devAxis.ActualPos[2]}] | " + - $"[命令位:{devContainer.devAxis.CmdPos[3]} 反馈位:{devContainer.devAxis.ActualPos[3]}]"; - })); - } - - private void tsbtnCloseDev_Click(object sender, EventArgs e) - { - AddTextEvent("设备停止", $"设备停止..."); - this.tsbtnProductRevise.Enabled = false; - this.tsbtnOpenDev.Visible = true; - this.tsbtnCloseDev.Visible = false; - this.btnMakeTags.Enabled = false; - this.lblTimeLen.Visible = false; - - this.tsbtnReset.Enabled = tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled - = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = false; - - this.tsbtnSizeTag.Enabled = tsbtnSizeImage.Enabled = tsbtnDefectImage.Enabled = false; - if (devContainer.state) - { - devContainer.devIOCard.reset(); - devContainer.io_output(CMDName.IO默认输出); - } - timer.Stop(); - devContainer.stop(); - } - /// - /// 全局中断 - /// - private void globalBreakEvent(int portIndex, byte data) - { - if (compareIOInput(CMDName.启动按钮) && this.tsbtnStart.Enabled) - startCommand(); - else if (compareIOInput(CMDName.暂停按钮) && this.tsbtnPause.Enabled) - warning(WarningEnum.Low, false); - else if (compareIOInput(CMDName.复位按钮) && this.tsbtnReset.Enabled) - resetCommand(); - else if (compareIOInput(CMDName.张力读取) && currentPT == CurrentPTEnum.Moving) - readTension(); - else if (!this.disableBuzzer && compareIOInput(CMDName.门磁告警输入)) - warning(WarningEnum.Low, true); - else if (!this.disableBuzzer && compareIOInput(CMDName.喷墨告警输入)) - warning(WarningEnum.Low, true); - } - private bool compareIOInput(CMDName key) - { - JObject joJson = Config.CMDProcess[key]; - IODirectionEnum direction = (IODirectionEnum)joJson.Value("Direction"); - if (direction == IODirectionEnum.输入 || direction == IODirectionEnum.输入输出) - { - return Util.compareIOInput( - joJson.Value("IN_OP_SHOW").ToObject>().ToArray(), - devContainer.devIOCard.DIData); - } - return false; - } - private void readTension() - { - if (Config.SkipTension) - { - AddTextEvent("张力读取", $"张力设备禁用,忽略此步骤!"); - return; - } - devContainer.io_output(CMDName.张力读取); - double tensionValue = devContainer.devTension.getValue(); - tensionValue=Math.Round(tensionValue, 2);//保留2位小数 - AddTextEvent("张力读取", $"张力值:{tensionValue}"); - devContainer.io_output(CMDName.张力读取,false,true,500); - lstTension.Add(tensionValue); - updateTensionValue(currProductModel.TensionBaseValue + currProductModel.TensionUpFloatValue, currProductModel.TensionBaseValue - currProductModel.TensionDownFloatValue); - } - /// - /// 启动 - /// - private void startCommand() - { - this.setButtonEnabled(this.tsbtnProductRevise, false); + lstHeight.Clear(); + lstLineWidth.Clear(); + lstTension.Clear(); + lstPT.Clear(); + this.lblTension.Text = this.lblHeight.Text = this.lblLineWidth.Text = "0.00"; + this.lblPT.Text = this.lblPTMax.Text= this.lblPTMin.Text="0.0000"; + this.lblCompareResult.Text =this.lblDefectResult.Text = "无"; + + this.lblTensionMax.Text = this.lblHeightMax.Text = this.lblLineWidthMax.Text + = this.lblTensionMin.Text = this.lblHeightMin.Text = this.lblLineWidthMin.Text = "0.00"; + + this.lblCompareResultCount.Text = "0"; + this.lblDefectResultCount.Text = "无"; + this.toolTip1.SetToolTip(lblDefectResultCount, lblDefectResultCount.Text); + // + this.lblTension.ForeColor = this.lblHeight.ForeColor = this.lblLineWidth.ForeColor = this.lblPT.ForeColor = this.lblCompareResult.ForeColor= this.lblDefectResult.ForeColor=Color.White; + this.lblTensionMax.ForeColor = this.lblHeightMax.ForeColor = this.lblLineWidthMax.ForeColor = this.lblPTMax.ForeColor + = this.lblTensionMin.ForeColor = this.lblHeightMin.ForeColor = this.lblLineWidthMin.ForeColor = this.lblPTMin.ForeColor = Color.White; + this.lblCompareResultCount.ForeColor = this.lblDefectResultCount.ForeColor=Color.White; + + this.dgvProcess.DataSource = null; + this.lstLog.Items.Clear(); + this.clearDefectBmps(); + + this.picScanner1.Image = this.picScanner2.Image = null; + picScanner1.Refresh(); + picScanner2.Refresh(); + + this.btnMakeTags.Enabled = false; + })); + } + //info: [{"1":[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]]}, + private void showDefectSmallBmps(Bitmap[] bmps, Mat[] bmps_cut, double Xmm, double Ymm, List[]>> info) + { + this.Invoke(new System.Action(() => + { + int imgWidth = this.pnlBmpList.ClientSize.Width - 50; + int imgHeight = (int)((bmps[0].Height * 1.0f / bmps[0].Width) * imgWidth + 0.5); + int splitWidth = 20; + int pnlWidth = this.pnlBmpList.ClientSize.Width; + int index = (int)this.gboxDefectList.Tag; + for (int x = 0; x < info.Count(); x++) + { + foreach (var item in info[x]) //单个info[x] = {"1":[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]]} + { + //统计缺陷类型 + countDefectClass(item.Value);//[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]] + + // + PictureBox picbox = new PictureBox(); + picbox.Width = imgWidth; + picbox.Height = imgHeight; + CheckBox checkBox = new CheckBox(); + picbox.Image = (Bitmap)bmps[x].Clone(); + picbox.Name = "imgDefect_" + index; + picbox.Tag = item.Key + "," + Xmm + "," + Ymm; + + checkBox.Tag = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(bmps_cut[item.Key]); //Mat转Bitmap ;//原始小图 + checkBox.Name = "chkDefect_" + index; + checkBox.Text = $"第{index + 1}张"; + checkBox.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged); + if (Config.MakeTag)//自动打标 + { + checkBox.Checked = true; + checkBox.Enabled = false; + } + picbox.Click += new EventHandler(defectBmpBox_Click); + picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + picbox.BorderStyle = BorderStyle.FixedSingle; + picbox.Margin = new Padding((pnlWidth - picbox.Width) / 2, splitWidth,0, 0); + checkBox.Margin = new Padding((pnlWidth - checkBox.Width) / 2 + splitWidth, + 0, 0, 0); + + // + //if (this.pnlBmpList.Controls.Count > 0) + //{ + // if ((this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + imgWidth + splitWidth) > this.pnlBmpList.Width) + // picbox.Location = new System.Drawing.Point(splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Bottom + splitWidth); + // else + // picbox.Location = new System.Drawing.Point(this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Location.Y); + //} + //else + //{ + // picbox.Location = new System.Drawing.Point(splitWidth, 0); + //} + //checkBox.Location = new System.Drawing.Point(picbox.Location.X + 5, picbox.Location.Y + 5); + //checkBox.ForeColor = Color.Black; + this.pnlBmpList.Controls.Add(picbox); + this.pnlBmpList.Controls.Add(checkBox); + break; + } + + // + index++; + }; + this.gboxDefectList.Tag = index; + this.gboxDefectList.Text = $"缺陷图像:{index} 张"; + if (Config.MakeTag) { + lblDefectAddTag.Text = $"待打标数:{index}"; + lblDefectAddTag.Tag = index; + } + pnlBmpList.VerticalScroll.Value = pnlBmpList.VerticalScroll.Maximum; + })); + } + //统计缺陷类型 [["92.7542","80.85799","99.54083","86.05363","dk","0.52"]] + private void countDefectClass(List[] list) + { + string className; + for(int i=0; i + /// 异步输出日志 + /// + /// 模板标识 + /// 内容 + /// + private void AddTextEvent(string tag, string msg, WarningEnum level = WarningEnum.Normal) + { + try + { + if (InvokeRequired) + { + Invoke(new AddTextDelegate(AddTextEvent), new object[] + { + tag, + msg, + level + }); + } + else + { + if (tag != null && tag != "") + tag = $" - [{tag}]"; + + var now = DateTime.Now; + msg = now.ToString("HH:mm:ss fff") + tag + " - " + msg; + //cont = MyHelper.subString(cont, 300); + + //写日志,warn和error日志直接写 + writeLog(now, level, msg); + + // + //if (type > 0) + // cont = $"{cont}"; + + msg = (level == WarningEnum.Normal ? "B" : level == WarningEnum.Low ? "Y" : "R") + msg; + this.Invoke(new System.Action(() => + { + if (this.lstLog.Items.Count > 1000) + this.lstLog.Items.Clear(); + lstLog.Items.Insert(0, msg); + })); + //日志滚动 + //lstLog.SelectedIndex = lstLog.Items.Count - 1; + } + } + catch (Exception ex) + { + //MessageBox.Show("AddTextEvent ex=(" + ex.Message + ")", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); + } + } + private void lstLog_DrawItem(object sender, DrawItemEventArgs e) + { + e.DrawBackground(); + if (e.Index < 0) return; + + string str = lstLog.Items[e.Index].ToString(); + e.Graphics.DrawString(str.Substring(1), e.Font, + new SolidBrush(str[0] == 'R' ? Color.Red : (str[0] == 'Y' ? Color.Orange : Color.Black)), + e.Bounds); + } + private void writeLog(DateTime now, WarningEnum level, string text) + { + string directory = Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\"; + //if (type == 0) directory = Application.StartupPath + "\\Log\\Info\\"; + //else if (type == 1) directory = Application.StartupPath + "\\Log\\Warn\\"; + //else directory = Application.StartupPath + "\\Log\\Error\\"; + + if (!System.IO.Directory.Exists(directory)) + System.IO.Directory.CreateDirectory(directory); + + File.AppendAllText(directory + now.ToString("yyyyMMdd") + ".log", text + "\r\n"); + } + + private void FrmMian_FormClosing(object sender, FormClosingEventArgs e) + { + if (devContainer.state) + { + MessageBox.Show("请先停止生产后才能关闭程序!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); + e.Cancel = true; + return; + } + + if (!bExitApp && MessageBox.Show($"确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + e.Cancel = true; + return; + } + } + private void FrmMian_FormClosed(object sender, FormClosedEventArgs e) + { + webService.stop(); + Application.Exit(); + System.GC.Collect(); + System.Environment.Exit(0); + } + private void tsbtnOpenDev_Click(object sender, EventArgs e) + { + //FrmGetPosByPic frr = new FrmGetPosByPic(new SizeLibProp()); + //frr.ShowDialog(); + + Config.LoadAllConfig(); + //设置程序最小/大线程池 + // Get the current settings. + int minWorker, minIOC; + ThreadPool.GetMinThreads(out minWorker, out minIOC); + ThreadPool.SetMinThreads(25, minIOC); + //ThreadPool.SetMaxThreads(256, 256); + + this.tsbtnProductRevise.Enabled = false; + this.tsbtnOpenDev.Enabled = false; + //scannerCBmpIndex = 0; + + isProductRevise = false; + this.resetUIValue(); + currProcessIndex = -1; + currentState = CurrentStateEnum.等待复位; + warningLevel = WarningEnum.Normal; + currentPT = CurrentPTEnum.InitPT; + this.tsbtnWarning.Enabled=this.tsbtnGoDownPT.Enabled=this.tsbtnStart.Enabled=this.tsbtnStopNow.Enabled=this.tsbtnPause.Enabled=this.tsbtnReset.Enabled=false; + //后台线程回调事件 + devContainer.StateChange = (state, msg) => + { + if (state) + { + //全局中断 + devContainer.devIOCard.INEvent = globalBreakEvent; + devContainer.OutDebugEvent = (tag, debugInfo) => + { + AddTextEvent(tag, debugInfo); + }; + // + AddTextEvent("设备启动", "请先进行复位操作!"); + this.Invoke(new System.Action(() => + { + this.tsbtnReset.Enabled = true; + tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled + = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = false; + + this.tsbtnOpenDev.Enabled = true; + this.tsbtnOpenDev.Visible = false; + this.tsbtnCloseDev.Visible = true; + })); + + timer.Elapsed += Timer_Elapsed; + timer.Interval = 500; + timer.Start(); + } + else + { + AddTextEvent("设备启动", $"启动失败,{msg}", WarningEnum.High); + this.Invoke(new System.Action(() => + { + this.tsbtnOpenDev.Enabled = true; + this.tsbtnOpenDev.Visible = true; + this.tsbtnCloseDev.Visible = false; + })); + } + + }; + devContainer.WarningEvent = (level, msg) => + { + AddTextEvent("设备事件", msg, level); + if (level == WarningEnum.High) + warning(level,true); + }; + devContainer.start(this.picScanner1.Handle, this.picScanner2.Handle); + } + + private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + this.Invoke(new System.Action(() => + { + this.tsAxisState.Text = $"[命令位:{devContainer.devAxis.CmdPos[0]} 反馈位:{devContainer.devAxis.ActualPos[0]}] | " + + $"[命令位:{devContainer.devAxis.CmdPos[1]} 反馈位:{devContainer.devAxis.ActualPos[1]}] | " + + $"[命令位:{devContainer.devAxis.CmdPos[2]} 反馈位:{devContainer.devAxis.ActualPos[2]}] | " + + $"[命令位:{devContainer.devAxis.CmdPos[3]} 反馈位:{devContainer.devAxis.ActualPos[3]}]"; + })); + } + + private void tsbtnCloseDev_Click(object sender, EventArgs e) + { + AddTextEvent("设备停止", $"设备停止..."); + this.tsbtnProductRevise.Enabled = false; + this.tsbtnOpenDev.Visible = true; + this.tsbtnCloseDev.Visible = false; + this.btnMakeTags.Enabled = false; + this.lblTimeLen.Visible = false; + + this.tsbtnReset.Enabled = tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled + = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = false; + + this.tsbtnSizeTag.Enabled = tsbtnSizeImage.Enabled = tsbtnDefectImage.Enabled = false; + if (devContainer.state) + { + devContainer.devIOCard.reset(); + devContainer.io_output(CMDName.IO默认输出); + } + timer.Stop(); + devContainer.stop(); + } + /// + /// 全局中断 + /// + private void globalBreakEvent(int portIndex, byte data) + { + if (compareIOInput(CMDName.启动按钮) && this.tsbtnStart.Enabled) + startCommand(); + else if (compareIOInput(CMDName.暂停按钮) && this.tsbtnPause.Enabled) + warning(WarningEnum.Low, false); + else if (compareIOInput(CMDName.复位按钮) && this.tsbtnReset.Enabled) + resetCommand(); + else if (compareIOInput(CMDName.张力读取) && currentPT == CurrentPTEnum.Moving) + readTension(); + else if (!this.disableBuzzer && compareIOInput(CMDName.门磁告警输入)) + warning(WarningEnum.Low, true); + else if (!this.disableBuzzer && compareIOInput(CMDName.喷墨告警输入)) + warning(WarningEnum.Low, true); + } + private bool compareIOInput(CMDName key) + { + JObject joJson = Config.CMDProcess[key]; + IODirectionEnum direction = (IODirectionEnum)joJson.Value("Direction"); + if (direction == IODirectionEnum.输入 || direction == IODirectionEnum.输入输出) + { + return Util.compareIOInput( + joJson.Value("IN_OP_SHOW").ToObject>().ToArray(), + devContainer.devIOCard.DIData); + } + return false; + } + private void readTension() + { + if (Config.SkipTension) + { + AddTextEvent("张力读取", $"张力设备禁用,忽略此步骤!"); + return; + } + devContainer.io_output(CMDName.张力读取); + double tensionValue = devContainer.devTension.getValue() + Config.Tension_Offset;//加入张力偏差 + tensionValue=Math.Round(tensionValue, 2);//保留2位小数 + AddTextEvent("张力读取", $"张力值:{tensionValue}"); + devContainer.io_output(CMDName.张力读取,false,true,500); + lstTension.Add(tensionValue); + updateTensionValue(currProductModel.TensionBaseValue + currProductModel.TensionUpFloatValue, currProductModel.TensionBaseValue - currProductModel.TensionDownFloatValue); + } + /// + /// 启动 + /// + private void startCommand() + { + this.setButtonEnabled(this.tsbtnProductRevise, false); //2023-10-23 运行前清除过期图片文件 - Config.DelectPictureFile(); - if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.等待启动) - return; - if (currentPT == CurrentPTEnum.MakeTag) - { - AddTextEvent("启动", "打标未结束,非可启动状态!", warningLevel); - return; - } - - if (!devContainer.devAxis.isReady()) - { - AddTextEvent("启动", "轴状态异常,不可启动!", warningLevel); - return; - } - if (!devContainer.devAxis.IsReset) - { - AddTextEvent("启动", "轴需先进行复位操作!", WarningEnum.High); - return; - } - - devContainer.io_output(CMDName.启动按钮); - devContainer.io_output(CMDName.绿灯输出); - devContainer.io_output(CMDName.暂停按钮, false, true, 0); - devContainer.io_output(CMDName.红灯输出, false, true, 0); - devContainer.io_output(CMDName.黄灯输出, false, true, 0); - - //暂停-》继续 - if (currProcessIndex >= 0 && currentPT == CurrentPTEnum.Moving && currentState == CurrentStateEnum.等待启动) - { - AddTextEvent("启动", $"暂停 -> 继续 当前工序索引:{currProcessIndex + 1}"); - threadProcess = new System.Threading.Thread(() => - { - int nextStepId = currProcessIndex; - do - { - currentState = CurrentStateEnum.运行中; - nextStepId = nextProcess(currProductModel, nextStepId); - } while (nextStepId >= 0 && !isBreakProcessRun()); - //nextProcess(currProductModel, currProcessIndex); - }); - threadProcess.IsBackground = true; - threadProcess.Start(); - this.setButtonEnabled(this.tsbtnPause, true); - this.setButtonEnabled(this.tsbtnStopNow, true); - } - else//开始/重新开始 - { - //校正从复位-》运行,不会新启动 - isProductRevise = false; - resetUIValue(); - AddTextEvent("启动", "移动至上料位..."); - gotoUpPT(); - - this.Invoke(new System.Action(() => - { - //新开始 - lblTimeLen.Visible = false; - runStep(); - })); - this.setButtonEnabled(this.tsbtnPause, false); - this.setButtonEnabled(this.tsbtnStopNow, false); - } - - this.setButtonEnabled(this.tsbtnStart, false); - this.setButtonEnabled(this.tsbtnReset, false); - this.setButtonEnabled(this.tsbtnGoDownPT, false); - } - /// - /// 暂停 - /// - /// 是否响蜂鸣 - private void pauseCommand(bool buzzer = false) - { - devContainer.io_output(CMDName.暂停按钮); - if (buzzer) - { - devContainer.io_output(CMDName.红灯输出); - devContainer.io_output(CMDName.蜂鸣器输出); - } - else - devContainer.io_output(CMDName.黄灯输出); - devContainer.io_output(CMDName.启动按钮, false, true, 0); - devContainer.io_output(CMDName.绿灯输出, false, true, 0); - - this.setButtonEnabled(this.tsbtnWarning, true); - this.setButtonEnabled(this.tsbtnGoDownPT, false); - this.setButtonEnabled(this.tsbtnStart, false); - this.setButtonEnabled(this.tsbtnPause, false); - this.setButtonEnabled(this.tsbtnStopNow, false); - this.setButtonEnabled(this.tsbtnReset, false); - AddTextEvent("暂停", $"当前工序索引:{currProcessIndex + 1}", WarningEnum.Low); - } - /// - /// 急停 - /// - private void stopNowCommand() - { - if (!devContainer.state) - { - this.setButtonEnabled(this.tsbtnStopNow, false); - return; - } - - devContainer.io_output(CMDName.Y轴复位输出, false, true, 0); - devContainer.io_output(CMDName.红灯输出); - if (!this.disableBuzzer) devContainer.io_output(CMDName.蜂鸣器输出); - devContainer.io_output(CMDName.暂停按钮, false, true, 0); - devContainer.io_output(CMDName.黄灯输出, false, true, 0); - devContainer.io_output(CMDName.启动按钮, false, true, 0); - devContainer.io_output(CMDName.绿灯输出, false, true, 0); - - this.setButtonEnabled(this.tsbtnWarning, true); - this.setButtonEnabled(this.tsbtnGoDownPT, false); - this.setButtonEnabled(this.tsbtnStart, false); - this.setButtonEnabled(this.tsbtnPause, false); - this.setButtonEnabled(this.tsbtnStopNow, false); - this.setButtonEnabled(this.tsbtnReset, false); - AddTextEvent("急停", $"当前工序索引:{currProcessIndex + 1}", WarningEnum.High); - } - private bool reseting = false; - private void resetCommand() - { - currentState = CurrentStateEnum.等待复位; - warningLevel = WarningEnum.Normal; - currentPT = CurrentPTEnum.InitPT; - this.Invoke(new System.Action(() => - { - lblTimeLen.Visible = false; - this.tsbtnWarning.Enabled = this.tsbtnGoDownPT.Enabled = this.tsbtnStart.Enabled = this.tsbtnStopNow.Enabled = this.tsbtnPause.Enabled = this.tsbtnReset.Enabled = false; - })); - - try - { - if (devContainer.state && !reseting) - { - reseting = true; - isProductRevise = false; - resetUIValue(); - AddTextEvent("复位", $"设备复位中..."); - currProcessIndex = -1; - - this.setButtonEnabled(this.tsbtnReset, false); - - // I/O reset后,输出默认状态 - AddTextEvent("复位", $"I/O复位中..."); - if (!devContainer.devIOCard.reset()) - { - AddTextEvent("复位", "I/O板卡复位失败!", WarningEnum.High); - return; - } - if (!devContainer.io_output(CMDName.IO默认输出)) - { - //AddTextEvent("复位", "I/O板卡复位默认值失败!", WarningEnum.High); - //return; - } - - //板卡复位输出灯 - devContainer.io_output(CMDName.复位按钮); - devContainer.io_output(CMDName.黄灯输出, true); - - //4.5X - if(!Config.SkipSmallAxis) - devContainer.devSmallAxis.gotoPos((int)SmallAxCmdPos.倍率4_5X, false); - - //移动Axis前等待厚度传感器收回 - AddTextEvent("复位", $"检测厚度传感器安全值..."); - if (!Config.SkipHeight) - { - while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue)) - { - if (!devContainer.state || currentState != CurrentStateEnum.等待复位) - return; - Thread.Sleep(100); - Application.DoEvents(); - } - } - - //goto ORG - AddTextEvent("复位", $"轴正在回原点..."); - devContainer.devAxis.closeJogMode(); - devContainer.devAxis.resetAxisState(-1);//reset state - //AddTextEvent("复位", $"重置轴状态..."); - for (int i = 0; i < Config.Axis_HomeMode.Length; i++) - { - //到起始位速度使用回HOME速度 - devContainer.devAxis.setAxisVelParam((double)Config.Axis_HomeVelLow[i], (double)Config.Axis_HomeVelHigh[i], - (double)Config.Axis_HomeAcc[i], (double)Config.Axis_HomeDec[i], i); - if (i != 2) - { - //devContainer.devAxis.setAxisVelParam(40000,200000,5000000, 5000000,i,true); - devContainer.devAxis.home(i, (uint)Config.Axis_HomeMode[i], (uint)Config.Axis_HomeDir[i]); - } - else//Y轴 I/O控制回HOME - { - devContainer.io_output(CMDName.Y轴复位输出); - } - } - AddTextEvent("复位", $"等待轴状态完成..."); - while (!devContainer.devAxis.isReady()) - { - if (!devContainer.state || currentState != CurrentStateEnum.等待复位) - { - AddTextEvent("复位", $"当前状态:"+ ((CurrentStateEnum)currentState).ToString()); - return; - } - //AddTextEvent("复位", $"轴0状态:"+ ((AxisState)devContainer.devAxis.AxState[0]).ToString()); - //AddTextEvent("复位", $"轴1状态:" + ((AxisState)devContainer.devAxis.AxState[1]).ToString()); - //AddTextEvent("复位", $"轴2状态:" + ((AxisState)devContainer.devAxis.AxState[2]).ToString()); - //AddTextEvent("复位", $"轴3状态:" + ((AxisState)devContainer.devAxis.AxState[3]).ToString()); - - Thread.Sleep(1000); - Application.DoEvents(); - } - //判断Y轴回原点完成I/O信号 - AddTextEvent("复位", $"等待Y轴回HOME完成..."); - while (!this.compareIOInput(CMDName.Y轴复位完成输入)) - { - Thread.Sleep(100); - Application.DoEvents(); - } - AddTextEvent("复位", $"Y轴回HOME已完成."); - devContainer.io_output(CMDName.Y轴复位输出, false, true, 0); - AddTextEvent("复位", $"重置Y轴反馈位置与命令位置."); - devContainer.devAxis.resetCmdPosition(2); - devContainer.devAxis.resetActualPosition(2); - - // - if (devContainer.devAxis.isError()) - throw new Exception("轴回原点失败!"); - - // - //goto InitPT - //AddTextEvent("复位", $"轴回原点完成,回到初始位..."); - JArray arrPT = Config.joPTSetting.Value("initPT"); - for (int i = 0; i < arrPT.Count; i++) - { - if (!devContainer.state || currentState != CurrentStateEnum.等待复位) - return; - - AddTextEvent($"复位", $"轴{i}准备运动至初始位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})..."); - devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置); - } - while (!devContainer.devAxis.isReady()) - { - if (!devContainer.state || warningLevel != WarningEnum.Normal) - return; - Thread.Sleep(100); - } - if (devContainer.devAxis.isError()) - throw new Exception("轴移动至初始位失败!"); - - // - this.setButtonEnabled(this.tsbtnReset, true); - this.setButtonEnabled(this.tsbtnStart, true); - this.setButtonEnabled(this.tsbtnStopNow, true); - this.setButtonEnabled(this.tsbtnPause, false); - this.setButtonEnabled(this.tsbtnGoDownPT, false); - this.setButtonEnabled(this.tsbtnWarning, false); - - devContainer.io_output(CMDName.复位按钮, false, true, 0);//熄灭 - devContainer.io_output(CMDName.黄灯输出);//长亮 - currentPT = CurrentPTEnum.InitPT; - currentState = CurrentStateEnum.等待启动; - AddTextEvent("复位", $"复位完成。"); - this.setButtonEnabled(this.tsbtnProductRevise, true); - } - else - { - AddTextEvent("复位", "非可复位状态,请先停止后再复位!", WarningEnum.High); - } - } - catch (Exception ex) - { - AddTextEvent("复位", "复位失败 Err:" + ex.Message, WarningEnum.High); - warning(WarningEnum.High, true); - } - finally - { - reseting = false; - } - } - /// - /// 上料 - /// - private void gotoUpPT() - { - try - { - JArray arrPT = Config.joPTSetting.Value("upPT"); - for (int i = 0; i < arrPT.Count; i++) - { - if (!devContainer.state || warningLevel != WarningEnum.Normal) - return; - - AddTextEvent($"上料", $"轴{i}准备运动至上料位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})..."); - devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置); - } - while (!devContainer.devAxis.isReady()) - { - if (!devContainer.state || warningLevel != WarningEnum.Normal) - return; - Thread.Sleep(100); - } - if (devContainer.devAxis.isError()) - throw new Exception("轴移动至上料位失败!"); - - // - currentPT = CurrentPTEnum.UpPT; - currentState = CurrentStateEnum.等待扫码; - AddTextEvent($"上料", "到达上料位!"); - } - catch (Exception ex) - { - AddTextEvent("上料", "上料初始失败 Err:" + ex.Message, WarningEnum.High); - warning(WarningEnum.High); - } - } - /// - /// 下料 - /// - private void gotoDownPT() - { - try - { - if (currentState != CurrentStateEnum.打标中 && currentState != CurrentStateEnum.等待启动 && currentState != CurrentStateEnum.自动流程结束) - { - AddTextEvent($"下料", $"非可下料状态:{currentState.ToString()}"); - return; - } - - currentState = CurrentStateEnum.下料中; - isProductRevise = false; - - JArray arrPT = Config.joPTSetting.Value("downPT"); - for (int i = 0; i < arrPT.Count; i++) - { - if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.下料中) - return; - - AddTextEvent($"下料", $"轴{i}准备运动至下料位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})..."); - devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置); - } - - while (!devContainer.devAxis.isReady()) - { - if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.下料中) - return; - Thread.Sleep(100); - } - if (devContainer.devAxis.isError()) - throw new Exception("轴移动至下料位失败!"); - - // - currentPT = CurrentPTEnum.DownPT; - currentState = CurrentStateEnum.等待启动; - devContainer.io_output(CMDName.下料完成输出); - setButtonEnabled(tsbtnStart, true); - AddTextEvent($"下料", "下料完成!"); - } - catch (Exception ex) - { - AddTextEvent("下料", "下料失败 Err:" + ex.Message, WarningEnum.High); - warning(WarningEnum.High); - } - } - private void setButtonEnabled(ToolStripButton button, bool Enabled) - { - this.Invoke(new System.Action(() => - { - button.Enabled = Enabled; - })); - } - private void setButtonEnabled(ToolStripMenuItem button, bool Enabled) - { - this.Invoke(new System.Action(() => - { - button.Enabled = Enabled; - })); - } - private void setButtonEnabled(Control button, bool Enabled) - { - this.Invoke(new System.Action(() => - { - button.Enabled = Enabled; - })); - } - - private void FrmMian_Shown(object sender, EventArgs e) - { - } - - private void FrmMian_Resize(object sender, EventArgs e) - { - - } - - private void 流程管理ToolStripMenuItem_Click(object sender, EventArgs e) - { - if (devContainer.state) - { - MessageBox.Show("请先停止生产,再进行流程修改!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return; - } - - FrmStepList frm = new FrmStepList(); - frm.ShowDialog(); - } - - private void 产品管理ToolStripMenuItem_Click(object sender, EventArgs e) - { - if (devContainer.state) - { - MessageBox.Show("请先停止生产,再进行产品修改!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return; - } - - FrmProductList frm = new FrmProductList(); - frm.ShowDialog(); - loadProductCodeList(); - } - private void tsbtnProductRevise_Click(object sender, EventArgs e) - { - if (!devContainer.state) - { - MessageBox.Show("请先启动设备!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - if (currentPT != CurrentPTEnum.InitPT || currentState != CurrentStateEnum.等待启动) - { - MessageBox.Show("请先复位设备!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - - FrmProductList frm = new FrmProductList(true); - if (frm.ShowDialog() == DialogResult.Yes && frm.Product != null)//执行校正 - { - AddTextEvent("校正", "开始执行产品base厚度校正..."); - - isProductRevise = true; - currProductModel = frm.Product; - currProductModel.HeightBaseDec = ""; - this.txtProductCode.Text = currProductModel.Code; - this.txtProductName.Text = currProductModel.Name; - this.txtProductSN.Text = ""; - this.dgvProcess.DataSource = new BindingSource(currProductModel.ReviseStepInfo.ProcessList, null); - devContainer.libFor.clear(); - devContainer.libIF.clear(); - - // - this.setButtonEnabled(this.tsbtnStart, false); - this.setButtonEnabled(this.tsbtnPause, true); - this.setButtonEnabled(this.tsbtnStopNow, true); - threadProcess = new System.Threading.Thread(() => - { - int nextStepId = 0; - do - { - currentState = CurrentStateEnum.运行中; - nextStepId = nextProcess(currProductModel, nextStepId); - } while (nextStepId >= 0 && !isBreakProcessRun()); - }); - threadProcess.IsBackground = true; - threadProcess.Start(); - } - } - private void 设备调试ToolStripMenuItem_Click(object sender, EventArgs e) - { - if (devContainer.state) - { - MessageBox.Show("请先停止生产,再进行设备调试!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return; - } - - FrmDebug3 frm = new FrmDebug3(); - frm.ShowDialog(); - } - - private void 角色管理ToolStripMenuItem_Click(object sender, EventArgs e) - { - FrmRoleRight frm = new FrmRoleRight(); - frm.ShowDialog(this); - } - - private void 用户管理ToolStripMenuItem_Click(object sender, EventArgs e) - { - FrmUserList frm = new FrmUserList(); - frm.ShowDialog(this); - } - - private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) - { - Application.Exit(); - System.GC.Collect(); - System.Environment.Exit(0); - } - - private void 注销ToolStripMenuItem_Click(object sender, EventArgs e) - { - if (devContainer.state) - { - MessageBox.Show("请先停止生产再退出!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return; - } - - if (MessageBox.Show($"确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - this.bExitApp = true; - Process.Start(Application.StartupPath + "\\ProductionControl.exe"); - this.Close(); - } - } - - private void splitContainer1_Panel1_Resize(object sender, EventArgs e) - { - int allWidth = this.splitContainer1.Panel1.Width; - this.gpbProductInfo.Width = this.flpnlResultData.Width = this.gpbProcessList.Width = this.gpbLog.Width = allWidth; - - // - this.txtProductName.Width = this.txtProductCode.Width = this.gpbProductInfo.Width - this.txtProductName.Left - 8; - this.txtProductSN.Width = this.txtBatchId.Width = (this.txtProductName.Width- lblBatchId.Width)/2; - this.lblBatchId.Left = this.txtProductSN.Right ; - this.txtBatchId.Left = this.lblBatchId.Right; - - - // - int spliceWidth = 5; + Config.DelectPictureFile(); + if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.等待启动) + return; + if (currentPT == CurrentPTEnum.MakeTag) + { + AddTextEvent("启动", "打标未结束,非可启动状态!", warningLevel); + return; + } + + if (!devContainer.devAxis.isReady()) + { + AddTextEvent("启动", "轴状态异常,不可启动!", warningLevel); + return; + } + if (!devContainer.devAxis.IsReset) + { + AddTextEvent("启动", "轴需先进行复位操作!", WarningEnum.High); + return; + } + + devContainer.io_output(CMDName.启动按钮); + devContainer.io_output(CMDName.绿灯输出); + devContainer.io_output(CMDName.暂停按钮, false, true, 0); + devContainer.io_output(CMDName.红灯输出, false, true, 0); + devContainer.io_output(CMDName.黄灯输出, false, true, 0); + + //暂停-》继续 + if (currProcessIndex >= 0 && currentPT == CurrentPTEnum.Moving && currentState == CurrentStateEnum.等待启动) + { + AddTextEvent("启动", $"暂停 -> 继续 当前工序索引:{currProcessIndex + 1}"); + threadProcess = new System.Threading.Thread(() => + { + int nextStepId = currProcessIndex; + do + { + currentState = CurrentStateEnum.运行中; + nextStepId = nextProcess(currProductModel, nextStepId); + } while (nextStepId >= 0 && !isBreakProcessRun()); + //nextProcess(currProductModel, currProcessIndex); + }); + threadProcess.IsBackground = true; + threadProcess.Start(); + this.setButtonEnabled(this.tsbtnPause, true); + this.setButtonEnabled(this.tsbtnStopNow, true); + } + else//开始/重新开始 + { + //校正从复位-》运行,不会新启动 + isProductRevise = false; + resetUIValue(); + AddTextEvent("启动", "移动至上料位..."); + gotoUpPT(); + + this.Invoke(new System.Action(() => + { + //新开始 + lblTimeLen.Visible = false; + runStep(); + })); + this.setButtonEnabled(this.tsbtnPause, false); + this.setButtonEnabled(this.tsbtnStopNow, false); + } + + this.setButtonEnabled(this.tsbtnStart, false); + this.setButtonEnabled(this.tsbtnReset, false); + this.setButtonEnabled(this.tsbtnGoDownPT, false); + } + /// + /// 暂停 + /// + /// 是否响蜂鸣 + private void pauseCommand(bool buzzer = false) + { + devContainer.io_output(CMDName.暂停按钮); + if (buzzer) + { + devContainer.io_output(CMDName.红灯输出); + devContainer.io_output(CMDName.蜂鸣器输出); + } + else + devContainer.io_output(CMDName.黄灯输出); + devContainer.io_output(CMDName.启动按钮, false, true, 0); + devContainer.io_output(CMDName.绿灯输出, false, true, 0); + + this.setButtonEnabled(this.tsbtnWarning, true); + this.setButtonEnabled(this.tsbtnGoDownPT, false); + this.setButtonEnabled(this.tsbtnStart, false); + this.setButtonEnabled(this.tsbtnPause, false); + this.setButtonEnabled(this.tsbtnStopNow, false); + this.setButtonEnabled(this.tsbtnReset, false); + AddTextEvent("暂停", $"当前工序索引:{currProcessIndex + 1}", WarningEnum.Low); + } + /// + /// 急停 + /// + private void stopNowCommand() + { + if (!devContainer.state) + { + this.setButtonEnabled(this.tsbtnStopNow, false); + return; + } + + devContainer.io_output(CMDName.Y轴复位输出, false, true, 0); + devContainer.io_output(CMDName.红灯输出); + if (!this.disableBuzzer) devContainer.io_output(CMDName.蜂鸣器输出); + devContainer.io_output(CMDName.暂停按钮, false, true, 0); + devContainer.io_output(CMDName.黄灯输出, false, true, 0); + devContainer.io_output(CMDName.启动按钮, false, true, 0); + devContainer.io_output(CMDName.绿灯输出, false, true, 0); + + this.setButtonEnabled(this.tsbtnWarning, true); + this.setButtonEnabled(this.tsbtnGoDownPT, false); + this.setButtonEnabled(this.tsbtnStart, false); + this.setButtonEnabled(this.tsbtnPause, false); + this.setButtonEnabled(this.tsbtnStopNow, false); + this.setButtonEnabled(this.tsbtnReset, false); + AddTextEvent("急停", $"当前工序索引:{currProcessIndex + 1}", WarningEnum.High); + } + private bool reseting = false; + private void resetCommand() + { + currentState = CurrentStateEnum.等待复位; + warningLevel = WarningEnum.Normal; + currentPT = CurrentPTEnum.InitPT; + this.Invoke(new System.Action(() => + { + lblTimeLen.Visible = false; + this.tsbtnWarning.Enabled = this.tsbtnGoDownPT.Enabled = this.tsbtnStart.Enabled = this.tsbtnStopNow.Enabled = this.tsbtnPause.Enabled = this.tsbtnReset.Enabled = false; + })); + + try + { + if (devContainer.state && !reseting) + { + reseting = true; + isProductRevise = false; + resetUIValue(); + AddTextEvent("复位", $"设备复位中..."); + currProcessIndex = -1; + + this.setButtonEnabled(this.tsbtnReset, false); + + // I/O reset后,输出默认状态 + AddTextEvent("复位", $"I/O复位中..."); + if (!devContainer.devIOCard.reset()) + { + AddTextEvent("复位", "I/O板卡复位失败!", WarningEnum.High); + return; + } + if (!devContainer.io_output(CMDName.IO默认输出)) + { + //AddTextEvent("复位", "I/O板卡复位默认值失败!", WarningEnum.High); + //return; + } + + //板卡复位输出灯 + devContainer.io_output(CMDName.复位按钮); + devContainer.io_output(CMDName.黄灯输出, true); + + //4.5X + if(!Config.SkipSmallAxis) + devContainer.devSmallAxis.gotoPos((int)SmallAxCmdPos.倍率4_5X, false); + + //移动Axis前等待厚度传感器收回 + AddTextEvent("复位", $"检测厚度传感器安全值..."); + if (!Config.SkipHeight) + { + while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue)) + { + if (!devContainer.state || currentState != CurrentStateEnum.等待复位) + return; + Thread.Sleep(100); + Application.DoEvents(); + } + } + + //goto ORG + AddTextEvent("复位", $"轴正在回原点..."); + devContainer.devAxis.closeJogMode(); + devContainer.devAxis.resetAxisState(-1);//reset state + //AddTextEvent("复位", $"重置轴状态..."); + for (int i = 0; i < Config.Axis_HomeMode.Length; i++) + { + //到起始位速度使用回HOME速度 + devContainer.devAxis.setAxisVelParam((double)Config.Axis_HomeVelLow[i], (double)Config.Axis_HomeVelHigh[i], + (double)Config.Axis_HomeAcc[i], (double)Config.Axis_HomeDec[i], i); + if (i != 2) + { + //devContainer.devAxis.setAxisVelParam(40000,200000,5000000, 5000000,i,true); + devContainer.devAxis.home(i, (uint)Config.Axis_HomeMode[i], (uint)Config.Axis_HomeDir[i]); + } + else//Y轴 I/O控制回HOME + { + devContainer.io_output(CMDName.Y轴复位输出); + } + } + AddTextEvent("复位", $"等待轴状态完成..."); + while (!devContainer.devAxis.isReady()) + { + if (!devContainer.state || currentState != CurrentStateEnum.等待复位) + { + AddTextEvent("复位", $"当前状态:"+ ((CurrentStateEnum)currentState).ToString()); + return; + } + //AddTextEvent("复位", $"轴0状态:"+ ((AxisState)devContainer.devAxis.AxState[0]).ToString()); + //AddTextEvent("复位", $"轴1状态:" + ((AxisState)devContainer.devAxis.AxState[1]).ToString()); + //AddTextEvent("复位", $"轴2状态:" + ((AxisState)devContainer.devAxis.AxState[2]).ToString()); + //AddTextEvent("复位", $"轴3状态:" + ((AxisState)devContainer.devAxis.AxState[3]).ToString()); + + Thread.Sleep(1000); + Application.DoEvents(); + } + //判断Y轴回原点完成I/O信号 + AddTextEvent("复位", $"等待Y轴回HOME完成..."); + while (!this.compareIOInput(CMDName.Y轴复位完成输入)) + { + Thread.Sleep(100); + Application.DoEvents(); + } + AddTextEvent("复位", $"Y轴回HOME已完成."); + devContainer.io_output(CMDName.Y轴复位输出, false, true, 0); + AddTextEvent("复位", $"重置Y轴反馈位置与命令位置."); + devContainer.devAxis.resetCmdPosition(2); + devContainer.devAxis.resetActualPosition(2); + + // + if (devContainer.devAxis.isError()) + throw new Exception("轴回原点失败!"); + + // + //goto InitPT + //AddTextEvent("复位", $"轴回原点完成,回到初始位..."); + JArray arrPT = Config.joPTSetting.Value("initPT"); + for (int i = 0; i < arrPT.Count; i++) + { + if (!devContainer.state || currentState != CurrentStateEnum.等待复位) + return; + + AddTextEvent($"复位", $"轴{i}准备运动至初始位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})..."); + devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置); + } + while (!devContainer.devAxis.isReady()) + { + if (!devContainer.state || warningLevel != WarningEnum.Normal) + return; + Thread.Sleep(100); + } + if (devContainer.devAxis.isError()) + throw new Exception("轴移动至初始位失败!"); + + // + this.setButtonEnabled(this.tsbtnReset, true); + this.setButtonEnabled(this.tsbtnStart, true); + this.setButtonEnabled(this.tsbtnStopNow, true); + this.setButtonEnabled(this.tsbtnPause, false); + this.setButtonEnabled(this.tsbtnGoDownPT, false); + this.setButtonEnabled(this.tsbtnWarning, false); + + devContainer.io_output(CMDName.复位按钮, false, true, 0);//熄灭 + devContainer.io_output(CMDName.黄灯输出);//长亮 + currentPT = CurrentPTEnum.InitPT; + currentState = CurrentStateEnum.等待启动; + AddTextEvent("复位", $"复位完成。"); + this.setButtonEnabled(this.tsbtnProductRevise, true); + } + else + { + AddTextEvent("复位", "非可复位状态,请先停止后再复位!", WarningEnum.High); + } + } + catch (Exception ex) + { + AddTextEvent("复位", "复位失败 Err:" + ex.Message, WarningEnum.High); + warning(WarningEnum.High, true); + } + finally + { + reseting = false; + } + } + /// + /// 上料 + /// + private void gotoUpPT() + { + try + { + JArray arrPT = Config.joPTSetting.Value("upPT"); + for (int i = 0; i < arrPT.Count; i++) + { + if (!devContainer.state || warningLevel != WarningEnum.Normal) + return; + + AddTextEvent($"上料", $"轴{i}准备运动至上料位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})..."); + devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置); + } + while (!devContainer.devAxis.isReady()) + { + if (!devContainer.state || warningLevel != WarningEnum.Normal) + return; + Thread.Sleep(100); + } + if (devContainer.devAxis.isError()) + throw new Exception("轴移动至上料位失败!"); + + // + currentPT = CurrentPTEnum.UpPT; + currentState = CurrentStateEnum.等待扫码; + AddTextEvent($"上料", "到达上料位!"); + } + catch (Exception ex) + { + AddTextEvent("上料", "上料初始失败 Err:" + ex.Message, WarningEnum.High); + warning(WarningEnum.High); + } + } + /// + /// 下料 + /// + private void gotoDownPT() + { + try + { + if (currentState != CurrentStateEnum.打标中 && currentState != CurrentStateEnum.等待启动 && currentState != CurrentStateEnum.自动流程结束) + { + AddTextEvent($"下料", $"非可下料状态:{currentState.ToString()}"); + return; + } + + currentState = CurrentStateEnum.下料中; + isProductRevise = false; + + JArray arrPT = Config.joPTSetting.Value("downPT"); + for (int i = 0; i < arrPT.Count; i++) + { + if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.下料中) + return; + + AddTextEvent($"下料", $"轴{i}准备运动至下料位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})..."); + devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置); + } + + while (!devContainer.devAxis.isReady()) + { + if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.下料中) + return; + Thread.Sleep(100); + } + if (devContainer.devAxis.isError()) + throw new Exception("轴移动至下料位失败!"); + + // + currentPT = CurrentPTEnum.DownPT; + currentState = CurrentStateEnum.等待启动; + devContainer.io_output(CMDName.下料完成输出); + setButtonEnabled(tsbtnStart, true); + AddTextEvent($"下料", "下料完成!"); + } + catch (Exception ex) + { + AddTextEvent("下料", "下料失败 Err:" + ex.Message, WarningEnum.High); + warning(WarningEnum.High); + } + } + private void setButtonEnabled(ToolStripButton button, bool Enabled) + { + this.Invoke(new System.Action(() => + { + button.Enabled = Enabled; + })); + } + private void setButtonEnabled(ToolStripMenuItem button, bool Enabled) + { + this.Invoke(new System.Action(() => + { + button.Enabled = Enabled; + })); + } + private void setButtonEnabled(Control button, bool Enabled) + { + this.Invoke(new System.Action(() => + { + button.Enabled = Enabled; + })); + } + + private void FrmMian_Shown(object sender, EventArgs e) + { + } + + private void FrmMian_Resize(object sender, EventArgs e) + { + + } + + private void 流程管理ToolStripMenuItem_Click(object sender, EventArgs e) + { + if (devContainer.state) + { + MessageBox.Show("请先停止生产,再进行流程修改!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + FrmStepList frm = new FrmStepList(); + frm.ShowDialog(); + } + + private void 产品管理ToolStripMenuItem_Click(object sender, EventArgs e) + { + if (devContainer.state) + { + MessageBox.Show("请先停止生产,再进行产品修改!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + FrmProductList frm = new FrmProductList(); + frm.ShowDialog(); + loadProductCodeList(); + } + private void tsbtnProductRevise_Click(object sender, EventArgs e) + { + if (!devContainer.state) + { + MessageBox.Show("请先启动设备!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (currentPT != CurrentPTEnum.InitPT || currentState != CurrentStateEnum.等待启动) + { + MessageBox.Show("请先复位设备!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + FrmProductList frm = new FrmProductList(true); + if (frm.ShowDialog() == DialogResult.Yes && frm.Product != null)//执行校正 + { + AddTextEvent("校正", "开始执行产品base厚度校正..."); + + isProductRevise = true; + currProductModel = frm.Product; + currProductModel.HeightBaseDec = ""; + this.txtProductCode.Text = currProductModel.Code; + this.txtProductName.Text = currProductModel.Name; + this.txtProductSN.Text = ""; + this.dgvProcess.DataSource = new BindingSource(currProductModel.ReviseStepInfo.ProcessList, null); + devContainer.libFor.clear(); + devContainer.libIF.clear(); + + // + this.setButtonEnabled(this.tsbtnStart, false); + this.setButtonEnabled(this.tsbtnPause, true); + this.setButtonEnabled(this.tsbtnStopNow, true); + threadProcess = new System.Threading.Thread(() => + { + int nextStepId = 0; + do + { + currentState = CurrentStateEnum.运行中; + nextStepId = nextProcess(currProductModel, nextStepId); + } while (nextStepId >= 0 && !isBreakProcessRun()); + }); + threadProcess.IsBackground = true; + threadProcess.Start(); + } + } + private void 设备调试ToolStripMenuItem_Click(object sender, EventArgs e) + { + if (devContainer.state) + { + MessageBox.Show("请先停止生产,再进行设备调试!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + FrmDebug3 frm = new FrmDebug3(); + frm.ShowDialog(); + } + + private void 角色管理ToolStripMenuItem_Click(object sender, EventArgs e) + { + FrmRoleRight frm = new FrmRoleRight(); + frm.ShowDialog(this); + } + + private void 用户管理ToolStripMenuItem_Click(object sender, EventArgs e) + { + FrmUserList frm = new FrmUserList(); + frm.ShowDialog(this); + } + + private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) + { + Application.Exit(); + System.GC.Collect(); + System.Environment.Exit(0); + } + + private void 注销ToolStripMenuItem_Click(object sender, EventArgs e) + { + if (devContainer.state) + { + MessageBox.Show("请先停止生产再退出!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + if (MessageBox.Show($"确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + this.bExitApp = true; + Process.Start(Application.StartupPath + "\\ProductionControl.exe"); + this.Close(); + } + } + + private void splitContainer1_Panel1_Resize(object sender, EventArgs e) + { + int allWidth = this.splitContainer1.Panel1.Width; + this.gpbProductInfo.Width = this.flpnlResultData.Width = this.gpbProcessList.Width = this.gpbLog.Width = allWidth; + + // + this.txtProductName.Width = this.txtProductCode.Width = this.gpbProductInfo.Width - this.txtProductName.Left - 8; + this.txtProductSN.Width = this.txtBatchId.Width = (this.txtProductName.Width- lblBatchId.Width)/2; + this.lblBatchId.Left = this.txtProductSN.Right ; + this.txtBatchId.Left = this.lblBatchId.Right; + + + // + int spliceWidth = 5; kanban1.Width = kanban2.Width = kanban3.Width = kanban4.Width = kanban5.Width = kanban6.Width = (flpnlResultData.Width-20) / 6; //2023-10-17 更新log和步骤列表显示 this.gpbProcessList.Height = this.splitContainer1.Panel1.Height - this.gpbProcessList.Top - this.gpbLog.Height; - this.gpbLog.Top = this.splitContainer1.Panel1.Height - this.gpbLog.Height; - } - - - private void 关于ToolStripMenuItem_Click(object sender, EventArgs e) - { - AboutBox1 aboutBox1 = new AboutBox1(); - aboutBox1.Show(); - } - - - private void 系统设置ToolStripMenuItem_Click(object sender, EventArgs e) - { - FrmSysSetting frmSetting = new FrmSysSetting(); - frmSetting.ShowDialog(); - } - - - - private void dgvProcess_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) - { - //string processCode; - //for (int i = 0; i < this.dgvProcess.Rows.Count; i++) - //{ - //processCode = dgvProcess.Rows[i].Cells[0].Value.ToString(); - //dgvProcess.Rows[i].Cells[1].Value = Config.dicDevType[processCode]; - //} - } - - private void tsbtnWarning_Click(object sender, EventArgs e) - { - //if (warningLevel == WarningEnum.Normal) - //{ - // tsbtnWarning.Enabled = false; - // return; - //} - - //重置AXIS状态 - devContainer.devAxis.resetAxisState(); - if (!devContainer.devAxis.isReady()) - { - AddTextEvent("解除报警", "轴状态未恢复,解除报警失败!", warningLevel); - return; - } - if (devContainer.devAxis.isError()) - { - AddTextEvent("解除报警", "轴IO状态异常,解除报警失败!", warningLevel); - return; - } - if (!this.disableDoorSensor && compareIOInput(CMDName.门磁告警输入)) - { - AddTextEvent("解除报警", "门磁告警未清除 ,解除报警失败!", warningLevel); - return; - } - if (!this.disableDoorSensor && compareIOInput(CMDName.喷墨告警输入)) - { - AddTextEvent("解除报警", "喷墨告警输入未清除 ,解除报警失败!", warningLevel); - return; - } - //关闭蜂鸣器 - devContainer.io_output(CMDName.蜂鸣器输出, false, true, 0); - devContainer.io_output(CMDName.红灯输出, false, true, 0); - devContainer.io_output(CMDName.复位按钮, false, true, 0); - if (warningLevel == WarningEnum.High) - { - AddTextEvent("解除报警", "急停告警已解除,但必需进行复位操作!", warningLevel); - currentState = CurrentStateEnum.等待复位; - this.tsbtnReset.Enabled = true; - tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled - = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = this.btnMakeTags.Enabled= false; - } - else - { - devContainer.io_output(CMDName.黄灯输出); - AddTextEvent("解除报警", "告警已解除,请继续选择下一步操作!", warningLevel); - if (currentPT == CurrentPTEnum.MakeTag) - currentState = CurrentStateEnum.打标中; - else - currentState = CurrentStateEnum.等待启动; - - tsbtnWarning.Enabled = false; - this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled = true; - this.tsbtnReset.Enabled = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = true; - } - warningLevel = WarningEnum.Normal; - } - private void tsbtnGoDownPT_Click(object sender, EventArgs e) - { - if (!devContainer.state || warningLevel!= WarningEnum.Normal) - return; - if (!devContainer.devAxis.isReady()) - { - AddTextEvent("下料失败", "轴状态异常!", WarningEnum.Low); - return; - } - - gotoDownPT(); - } - //急停 - private void tsbtnStopNow_Click(object sender, EventArgs e) - { - this.warning(WarningEnum.High); - } - private Thread threadProcess; - - private void tsbtnStart_Click(object sender, EventArgs e) - { - this.startCommand(); - } - - private void tsbtnPause_Click(object sender, EventArgs e) - { - warning(WarningEnum.Low,false); - } - //复位 - private void tsbtnReset_Click(object sender, EventArgs e) - { - this.resetCommand(); - } - - private void tsbtnGButSetting_Click(object sender, EventArgs e) - { - if (devContainer.state) - { - MessageBox.Show("请先停止生产,再进行设置!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return; - } - - FrmCMDProcess from = new FrmCMDProcess(); - from.ShowDialog(); - } - - private void tsbtnPTSetting_Click(object sender, EventArgs e) - { - if (devContainer.state) - { - MessageBox.Show("请先停止生产,再进行设置!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return; - } - - FrmPTSetting from = new FrmPTSetting(); - from.ShowDialog(); - } - - private void tsMenuModifyPW_Click(object sender, EventArgs e) - { - FrmModifyPW frm = new FrmModifyPW(); - frm.ShowDialog(); - } - - //分拆面板平均分配 - private void splitContainer1_ClientSizeChanged(object sender, EventArgs e) - { - if (this.WindowState == FormWindowState.Minimized) - return; - - SplitContainer sc = (SplitContainer)sender; - sc.SplitterDistance = sc.Width / 7*3; - } - private void splitContainer3_ClientSizeChanged(object sender, EventArgs e) - { - if (this.WindowState == FormWindowState.Minimized) - return; - - SplitContainer sc = (SplitContainer)sender; - sc.SplitterDistance = sc.Height / 2; - } - private void Menu查询统计_Click(object sender, EventArgs e) - { - FrmWeb frm = new FrmWeb("查询统计", $"reportRecordSN?CustomerVer={Config.CustomerVer}"); - frm.Show(); - } - - private void tsMenuOrder_Click(object sender, EventArgs e) - { - //FrmOrderList frm = new FrmOrderList(); - string subject = (sender as ToolStripMenuItem).Text; - FrmWeb frm = new FrmWeb(subject, $"reportRecordSN?CustomerVer={Config.CustomerVer}"); - frm.Show(); - } - private void tsMenuOrderProduct_Click(object sender, EventArgs e) - { - string subject = (sender as ToolStripMenuItem).Text; - FrmWeb frm = new FrmWeb(subject, $"reportRecordProduct?CustomerVer={Config.CustomerVer}"); - frm.Show(); - } - private void tsMenuStatistics_Click(object sender, EventArgs e) - { - string subject = (sender as ToolStripMenuItem).Text; - FrmWeb frm = new FrmWeb(subject, $"bigscreen/index.html", "http://127.0.0.1:18082/static/"); - frm.Show(); - } - private void toolStripButton1_Click(object sender, EventArgs e) - { - //Bitmap[] bmps = new Bitmap[2]; - //bmps[0] = new Bitmap(@"f:\1.bmp"); - //bmps[1] = new Bitmap(@"f:\111.bmp"); - //List[]>> list = new List[]>>(); - //Dictionary[]> dir = new Dictionary[]>(); - //List[] vs = new List[1]; - //vs[0] = new List(); - //dir.Add(0, vs); - //list.Add(dir); - //showDefectSmallBmps(bmps, list); - var bmp = Bitmap.FromFile("f:\\1.jpg"); - int pnlWidth = this.pnlBmpList.ClientSize.Width; - for (int i = 0; i < 5; i++) - { - int x = i; - this.Invoke(new System.Action(() => - { - int imgWidth = 224; - int imgHeight = 200; - int splitWidth = 10; - int index = Convert.ToInt32(this.gboxDefectList.Tag); - - PictureBox picbox = new PictureBox(); - picbox.Width = imgWidth; - picbox.Height = imgHeight; - CheckBox checkBox = new CheckBox(); - picbox.Image = bmp; - picbox.Name = "imgDefect_" + index; - picbox.Tag ="1,2,3"; - checkBox.Name = "chkDefect_" + index; - checkBox.Text = $"第{index + 1}张"; - checkBox.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged); - - picbox.Click += new EventHandler(defectBmpBox_Click); - picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; - picbox.BorderStyle = BorderStyle.FixedSingle; - picbox.Margin = new Padding((pnlWidth - picbox.Width) / 2, splitWidth, 0, 0); - checkBox.Margin = new Padding((pnlWidth - checkBox.Width) / 2+ splitWidth, 0, 0, 0); - // - //if (this.pnlBmpList.Controls.Count > 0) - // { - // if ((this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + imgWidth + splitWidth) > this.pnlBmpList.Width) - // picbox.Location = new System.Drawing.Point(splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Bottom + splitWidth); - // else - // picbox.Location = new System.Drawing.Point(this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Location.Y); - // } - // else - // { - // picbox.Location = new System.Drawing.Point(splitWidth, 0); - // } - // checkBox.Location = new System.Drawing.Point(picbox.Location.X + 5, picbox.Location.Y + 5); - // checkBox.ForeColor = Color.Black; - //} - this.pnlBmpList.Controls.Add(picbox); - this.pnlBmpList.Controls.Add(checkBox); - - // - index++; - this.gboxDefectList.Tag = index; - this.gboxDefectList.Text = $"缺陷图像:{index} 张"; - pnlBmpList.VerticalScroll.Value = pnlBmpList.VerticalScroll.Maximum; - })); - } - } - - - private void chkBuzzer_CheckedChanged(object sender, EventArgs e) - { - this.disableBuzzer = chkBuzzer.Checked; - if (devContainer.state && this.disableBuzzer) - devContainer.io_output(CMDName.蜂鸣器输出, false, true, 0); - } - - private void chkDoorSensor_CheckedChanged(object sender, EventArgs e) - { - this.disableDoorSensor = chkDoorSensor.Checked; - } - - private void tsbtnLight_Click(object sender, EventArgs e) - { - if (devContainer.state) - { - if(tsbtnLight.Text.Trim()== "开灯") - { - if(devContainer.io_output(CMDName.日光灯输出)) - tsbtnLight.Text = " 关灯 "; - } - else - { - if (devContainer.io_output(CMDName.日光灯输出, false, true, 0)) - tsbtnLight.Text = " 开灯 "; - } - } - } - - private void btnMakeTag_Click(object sender, EventArgs e) - { - if(currentPT != CurrentPTEnum.MakeTag) - { - AddTextEvent("打标失败", "非可打标状态!"); - return; - } - btnMakeTags.Enabled = false; - autoMakeTagRuning = true; - Thread threadtest = new System.Threading.Thread(() => - { - try - { - if (!devContainer.state) - { - AddTextEvent("打标", "设备已停机!"); - return; - } - if ((int)this.lblDefectAddTag.Tag < 1) - { - AddTextEvent("打标", "打标队列为空!"); - return; - } - - int tagIndex; - double Xmm, Ymm; - Bitmap currBmp; - string[] tags; - for (int i = 0; i < this.pnlBmpList.Controls.Count; i += 2) - { - CheckBox cb = this.pnlBmpList.Controls[i + 1] as CheckBox; - if (cb.Checked) - { - PictureBox picBox = this.pnlBmpList.Controls[i] as PictureBox; - tags = picBox.Tag.ToString().Split(','); - tagIndex = Convert.ToInt32(tags[0]); - Xmm = Convert.ToDouble(tags[1]); - Ymm = Convert.ToDouble(tags[2]); - currBmp = (Bitmap)picBox.Image; - - //打标 - AddTextEvent("打标", $"第{i / 2 + 1}/{this.pnlBmpList.Controls.Count / 2}张 [索引:{tagIndex}, X:{Xmm}mm, Y:{Ymm}mm]"); - var list = devContainer.libDefect.makeTag(tagIndex, Xmm, Ymm, currBmp.Width, currBmp.Height); - devContainer.devAxis.move_ptp(1, list[0], AxMoveMode.绝对位置); - devContainer.devAxis.move_ptp(2, list[1], AxMoveMode.绝对位置); - while (!devContainer.devAxis.isReady(1) || !devContainer.devAxis.isReady(2)) - { - Application.DoEvents(); - Thread.Sleep(100); - if (!devContainer.state) - throw new Exception("设备停止,打标中止!"); - } - // - if (!devContainer.io_output(CMDName.喷墨输出, false, true, 500)) - throw new Exception("请确认[喷墨输出]指令设置是否正确!"); - - this.Invoke(new System.Action(() => - { - cb.Checked = false; - })); - } - } - - //自动下料 - AddTextEvent("打标完成", $"批量打标完成,进行下料..."); - currentState = CurrentStateEnum.自动流程结束; - gotoDownPT(); - } - catch (Exception ex) - { - AddTextEvent("打标失败", ex.Message, WarningEnum.High); - warning(WarningEnum.Low, true); - } - finally { autoMakeTagRuning=false; } - }); - threadtest.IsBackground = true; - threadtest.Start(); - } - - private void btnInputCode_Click(object sender, EventArgs e) - { - txtProductCode_DoubleClick(null, null); - } - private void txtProductName_DoubleClick(object sender, EventArgs e) - { - txtProductCode_DoubleClick(null, null); - } - private void txtProductCode_DoubleClick(object sender, EventArgs e) - { - //不需要等待扫码才能选择 - //if (currentState != CurrentStateEnum.等待扫码) return; - - FrmInput frm = new FrmInput(productCodeList, "请选择产品料号:"); - if (frm.ShowDialog() != DialogResult.OK && string.IsNullOrWhiteSpace(frm.inputData)) - return; + this.gpbLog.Top = this.splitContainer1.Panel1.Height - this.gpbLog.Height; + } + + + private void 关于ToolStripMenuItem_Click(object sender, EventArgs e) + { + AboutBox1 aboutBox1 = new AboutBox1(); + aboutBox1.Show(); + } + + + private void 系统设置ToolStripMenuItem_Click(object sender, EventArgs e) + { + FrmSysSetting frmSetting = new FrmSysSetting(); + frmSetting.ShowDialog(); + } + + + + private void dgvProcess_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) + { + //string processCode; + //for (int i = 0; i < this.dgvProcess.Rows.Count; i++) + //{ + //processCode = dgvProcess.Rows[i].Cells[0].Value.ToString(); + //dgvProcess.Rows[i].Cells[1].Value = Config.dicDevType[processCode]; + //} + } + + private void tsbtnWarning_Click(object sender, EventArgs e) + { + //if (warningLevel == WarningEnum.Normal) + //{ + // tsbtnWarning.Enabled = false; + // return; + //} + + //重置AXIS状态 + devContainer.devAxis.resetAxisState(); + if (!devContainer.devAxis.isReady()) + { + AddTextEvent("解除报警", "轴状态未恢复,解除报警失败!", warningLevel); + return; + } + if (devContainer.devAxis.isError()) + { + AddTextEvent("解除报警", "轴IO状态异常,解除报警失败!", warningLevel); + return; + } + if (!this.disableDoorSensor && compareIOInput(CMDName.门磁告警输入)) + { + AddTextEvent("解除报警", "门磁告警未清除 ,解除报警失败!", warningLevel); + return; + } + if (!this.disableDoorSensor && compareIOInput(CMDName.喷墨告警输入)) + { + AddTextEvent("解除报警", "喷墨告警输入未清除 ,解除报警失败!", warningLevel); + return; + } + //关闭蜂鸣器 + devContainer.io_output(CMDName.蜂鸣器输出, false, true, 0); + devContainer.io_output(CMDName.红灯输出, false, true, 0); + devContainer.io_output(CMDName.复位按钮, false, true, 0); + if (warningLevel == WarningEnum.High) + { + AddTextEvent("解除报警", "急停告警已解除,但必需进行复位操作!", warningLevel); + currentState = CurrentStateEnum.等待复位; + this.tsbtnReset.Enabled = true; + tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled + = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = this.btnMakeTags.Enabled= false; + } + else + { + devContainer.io_output(CMDName.黄灯输出); + AddTextEvent("解除报警", "告警已解除,请继续选择下一步操作!", warningLevel); + if (currentPT == CurrentPTEnum.MakeTag) + currentState = CurrentStateEnum.打标中; + else + currentState = CurrentStateEnum.等待启动; + + tsbtnWarning.Enabled = false; + this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled = true; + this.tsbtnReset.Enabled = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = true; + } + warningLevel = WarningEnum.Normal; + } + private void tsbtnGoDownPT_Click(object sender, EventArgs e) + { + if (!devContainer.state || warningLevel!= WarningEnum.Normal) + return; + if (!devContainer.devAxis.isReady()) + { + AddTextEvent("下料失败", "轴状态异常!", WarningEnum.Low); + return; + } + + gotoDownPT(); + } + //急停 + private void tsbtnStopNow_Click(object sender, EventArgs e) + { + this.warning(WarningEnum.High); + } + private Thread threadProcess; + + private void tsbtnStart_Click(object sender, EventArgs e) + { + this.startCommand(); + } + + private void tsbtnPause_Click(object sender, EventArgs e) + { + warning(WarningEnum.Low,false); + } + //复位 + private void tsbtnReset_Click(object sender, EventArgs e) + { + this.resetCommand(); + } + + private void tsbtnGButSetting_Click(object sender, EventArgs e) + { + if (devContainer.state) + { + MessageBox.Show("请先停止生产,再进行设置!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + FrmCMDProcess from = new FrmCMDProcess(); + from.ShowDialog(); + } + + private void tsbtnPTSetting_Click(object sender, EventArgs e) + { + if (devContainer.state) + { + MessageBox.Show("请先停止生产,再进行设置!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + FrmPTSetting from = new FrmPTSetting(); + from.ShowDialog(); + } + + private void tsMenuModifyPW_Click(object sender, EventArgs e) + { + FrmModifyPW frm = new FrmModifyPW(); + frm.ShowDialog(); + } + + //分拆面板平均分配 + private void splitContainer1_ClientSizeChanged(object sender, EventArgs e) + { + if (this.WindowState == FormWindowState.Minimized) + return; + + SplitContainer sc = (SplitContainer)sender; + sc.SplitterDistance = sc.Width / 7*3; + } + private void splitContainer3_ClientSizeChanged(object sender, EventArgs e) + { + if (this.WindowState == FormWindowState.Minimized) + return; + + SplitContainer sc = (SplitContainer)sender; + sc.SplitterDistance = sc.Height / 2; + } + private void Menu查询统计_Click(object sender, EventArgs e) + { + FrmWeb frm = new FrmWeb("查询统计", $"reportRecordSN?CustomerVer={Config.CustomerVer}"); + frm.Show(); + } + + private void tsMenuOrder_Click(object sender, EventArgs e) + { + //FrmOrderList frm = new FrmOrderList(); + string subject = (sender as ToolStripMenuItem).Text; + FrmWeb frm = new FrmWeb(subject, $"reportRecordSN?CustomerVer={Config.CustomerVer}"); + frm.Show(); + } + private void tsMenuOrderProduct_Click(object sender, EventArgs e) + { + string subject = (sender as ToolStripMenuItem).Text; + FrmWeb frm = new FrmWeb(subject, $"reportRecordProduct?CustomerVer={Config.CustomerVer}"); + frm.Show(); + } + private void tsMenuStatistics_Click(object sender, EventArgs e) + { + string subject = (sender as ToolStripMenuItem).Text; + FrmWeb frm = new FrmWeb(subject, $"bigscreen/index.html", "http://127.0.0.1:18082/static/"); + frm.Show(); + } + private void toolStripButton1_Click(object sender, EventArgs e) + { + //Bitmap[] bmps = new Bitmap[2]; + //bmps[0] = new Bitmap(@"f:\1.bmp"); + //bmps[1] = new Bitmap(@"f:\111.bmp"); + //List[]>> list = new List[]>>(); + //Dictionary[]> dir = new Dictionary[]>(); + //List[] vs = new List[1]; + //vs[0] = new List(); + //dir.Add(0, vs); + //list.Add(dir); + //showDefectSmallBmps(bmps, list); + var bmp = Bitmap.FromFile("f:\\1.jpg"); + int pnlWidth = this.pnlBmpList.ClientSize.Width; + for (int i = 0; i < 5; i++) + { + int x = i; + this.Invoke(new System.Action(() => + { + int imgWidth = 224; + int imgHeight = 200; + int splitWidth = 10; + int index = Convert.ToInt32(this.gboxDefectList.Tag); + + PictureBox picbox = new PictureBox(); + picbox.Width = imgWidth; + picbox.Height = imgHeight; + CheckBox checkBox = new CheckBox(); + picbox.Image = bmp; + picbox.Name = "imgDefect_" + index; + picbox.Tag ="1,2,3"; + checkBox.Name = "chkDefect_" + index; + checkBox.Text = $"第{index + 1}张"; + checkBox.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged); + + picbox.Click += new EventHandler(defectBmpBox_Click); + picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + picbox.BorderStyle = BorderStyle.FixedSingle; + picbox.Margin = new Padding((pnlWidth - picbox.Width) / 2, splitWidth, 0, 0); + checkBox.Margin = new Padding((pnlWidth - checkBox.Width) / 2+ splitWidth, 0, 0, 0); + // + //if (this.pnlBmpList.Controls.Count > 0) + // { + // if ((this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + imgWidth + splitWidth) > this.pnlBmpList.Width) + // picbox.Location = new System.Drawing.Point(splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Bottom + splitWidth); + // else + // picbox.Location = new System.Drawing.Point(this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Location.Y); + // } + // else + // { + // picbox.Location = new System.Drawing.Point(splitWidth, 0); + // } + // checkBox.Location = new System.Drawing.Point(picbox.Location.X + 5, picbox.Location.Y + 5); + // checkBox.ForeColor = Color.Black; + //} + this.pnlBmpList.Controls.Add(picbox); + this.pnlBmpList.Controls.Add(checkBox); + + // + index++; + this.gboxDefectList.Tag = index; + this.gboxDefectList.Text = $"缺陷图像:{index} 张"; + pnlBmpList.VerticalScroll.Value = pnlBmpList.VerticalScroll.Maximum; + })); + } + } + + + private void chkBuzzer_CheckedChanged(object sender, EventArgs e) + { + this.disableBuzzer = chkBuzzer.Checked; + if (devContainer.state && this.disableBuzzer) + devContainer.io_output(CMDName.蜂鸣器输出, false, true, 0); + } + + private void chkDoorSensor_CheckedChanged(object sender, EventArgs e) + { + this.disableDoorSensor = chkDoorSensor.Checked; + } + + private void tsbtnLight_Click(object sender, EventArgs e) + { + if (devContainer.state) + { + if(tsbtnLight.Text.Trim()== "开灯") + { + if(devContainer.io_output(CMDName.日光灯输出)) + tsbtnLight.Text = " 关灯 "; + } + else + { + if (devContainer.io_output(CMDName.日光灯输出, false, true, 0)) + tsbtnLight.Text = " 开灯 "; + } + } + } + + private void btnMakeTag_Click(object sender, EventArgs e) + { + if(currentPT != CurrentPTEnum.MakeTag) + { + AddTextEvent("打标失败", "非可打标状态!"); + return; + } + btnMakeTags.Enabled = false; + autoMakeTagRuning = true; + Thread threadtest = new System.Threading.Thread(() => + { + try + { + if (!devContainer.state) + { + AddTextEvent("打标", "设备已停机!"); + return; + } + if ((int)this.lblDefectAddTag.Tag < 1) + { + AddTextEvent("打标", "打标队列为空!"); + return; + } + + int tagIndex; + double Xmm, Ymm; + Bitmap currBmp; + string[] tags; + for (int i = 0; i < this.pnlBmpList.Controls.Count; i += 2) + { + CheckBox cb = this.pnlBmpList.Controls[i + 1] as CheckBox; + if (cb.Checked) + { + PictureBox picBox = this.pnlBmpList.Controls[i] as PictureBox; + tags = picBox.Tag.ToString().Split(','); + tagIndex = Convert.ToInt32(tags[0]); + Xmm = Convert.ToDouble(tags[1]); + Ymm = Convert.ToDouble(tags[2]); + currBmp = (Bitmap)picBox.Image; + + //打标 + AddTextEvent("打标", $"第{i / 2 + 1}/{this.pnlBmpList.Controls.Count / 2}张 [索引:{tagIndex}, X:{Xmm}mm, Y:{Ymm}mm]"); + var list = devContainer.libDefect.makeTag(tagIndex, Xmm, Ymm, currBmp.Width, currBmp.Height); + devContainer.devAxis.move_ptp(1, list[0], AxMoveMode.绝对位置); + devContainer.devAxis.move_ptp(2, list[1], AxMoveMode.绝对位置); + while (!devContainer.devAxis.isReady(1) || !devContainer.devAxis.isReady(2)) + { + Application.DoEvents(); + Thread.Sleep(100); + if (!devContainer.state) + throw new Exception("设备停止,打标中止!"); + } + // + if (!devContainer.io_output(CMDName.喷墨输出, false, true, 500)) + throw new Exception("请确认[喷墨输出]指令设置是否正确!"); + + this.Invoke(new System.Action(() => + { + cb.Checked = false; + })); + } + } + + //自动下料 + AddTextEvent("打标完成", $"批量打标完成,进行下料..."); + currentState = CurrentStateEnum.自动流程结束; + gotoDownPT(); + } + catch (Exception ex) + { + AddTextEvent("打标失败", ex.Message, WarningEnum.High); + warning(WarningEnum.Low, true); + } + finally { autoMakeTagRuning=false; } + }); + threadtest.IsBackground = true; + threadtest.Start(); + } + + private void btnInputCode_Click(object sender, EventArgs e) + { + txtProductCode_DoubleClick(null, null); + } + private void txtProductName_DoubleClick(object sender, EventArgs e) + { + txtProductCode_DoubleClick(null, null); + } + private void txtProductCode_DoubleClick(object sender, EventArgs e) + { + //不需要等待扫码才能选择 + //if (currentState != CurrentStateEnum.等待扫码) return; + + FrmInput frm = new FrmInput(productCodeList, "请选择产品料号:"); + if (frm.ShowDialog() != DialogResult.OK && string.IsNullOrWhiteSpace(frm.inputData)) + return; //显示料号 //this.txtProductCode.Text = frm.inputData; var model = svcProduct.GetModelNav(frm.inputData); @@ -3401,218 +3401,218 @@ namespace ProductionControl { this.txtProductCode.Text = model.Code; this.txtProductName.Text = model.Name; - } - /*//屏蔽扫码枪事件 - Task.Factory.StartNew(() => - { - devContainer.devCodeScanner.ScanerEvent?.Invoke(frm.inputData); - }); - */ - - //string code = Interaction.InputBox("请输入产品编码", "输入框", "", -1, -1).Trim(); - //if(code != "") - //{ - // Task.Factory.StartNew(() => - // { - // devContainer.devCodeScanner.ScanerEvent?.Invoke(frm.inputData); - // }); - //} - } - - private void txtProductSN_DoubleClick(object sender, EventArgs e) - { - //if (currentState != CurrentStateEnum.等待扫码 || this.txtProductCode.Text.Trim()=="") return; - - //string sn = Interaction.InputBox("请输入产品SN码", "输入框", "", -1, -1).Trim(); - //if (sn != "") - //{ - // this.txtProductSN.Text = sn; - // string code = this.txtProductCode.Text.Trim(); - // Task.Factory.StartNew(() => - // { - // devContainer.devCodeScanner.ScanerEvent?.Invoke(code); - // }); - //} - } - private void 测试ToolStripMenuItem_Click(object sender, EventArgs e) - { - tsbtnDefectImage.Enabled = tsbtnSizeImage.Enabled=true; - return; - Form1 frm = new Form1(); - frm.Show(); - //tsbtnDefectImage_Click(null, null); - return; - try - { - //string ls = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,182.257722637742,182.257727282667,0,0"; - //List list = new List(ls.Split(',')); - //lstPT = list.Select(q => Convert.ToDouble(q)).ToList(); - //updatePTValue(1,2); - //lstPT.Add(10); - //lstPT.Add(0); - //updatePTValue(1, 2); - //{ - // lstLineWidth.Add(res.Shanxian > 0 ? res.Shanxian : 0); - // updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue); - //} - //return; - - //loadProductCodeList(); - //FrmInput frm = new FrmInput(null, "请选择产品编码:"); - //if (frm.ShowDialog() != DialogResult.OK) - // return; - //var model = svcProduct.GetModelNav(frm.inputData); - //if (model == null) - // throw new Exception("没有此产品!"); - //order.ProductId = model.Id; - //order.BatchId = model.BatchId; - //order.StepId = model.StepId==null? 0:(int)model.StepId; - //frm = new FrmInput(null, "请输入SN:"); - //if (frm.ShowDialog() != DialogResult.OK) - // return; - //order.SN = frm.inputData; - - //frm = new FrmInput(null, "请输入主机台Mark点数据:", "[0,0,0,0,0,0,0,0]"); - //if (frm.ShowDialog() != DialogResult.OK) - // return; - //order.MarkData= frm.inputData; - //order.Tension1 = order.Tension2 = order.Tension3 = order.Tension4 = order.Tension5 = order.Tension5 + 3; - //order.PT1 = order.PT4 = order.PT5 = order.PT6 = order.PT6 + 1.33; - //order.LineWidth2 = order.LineWidth3 = order.LineWidth5 = order.LineWidth6 = +order.LineWidth6 + 1.22; - - //order.HeightValue = order.Height1 = order.Height3 = order.Height4 = 55; - //order.DefectCount = order.DefectCount + 22; - //order.YXCount = order.PPCount = 33; - //order.TimeLen = 1000; - //order.Succeed = true; - //order.ModifyUserCode = order.CreateUserCode = Config.loginUser.Code; - - //if (!svcOrder.Insert(order)) - // AddTextEvent("保存失败", $"保存生产记录失败!"); - //MessageBox.Show("成功!"); - - //--------------- - this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\1.bmp")); - this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\2.bmp")); - this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\3.bmp")); - } - catch(Exception ex) - { - MessageBox.Show(ex.Message); - } - } - - private void toolStripSeparator4_Click(object sender, EventArgs e) - { - - } - - private void chkHttpLog_CheckedChanged(object sender, EventArgs e) - { - if (this.chkHttpLog.Checked) - { - webService.LogEvent = (warning, msg) => - { - AddTextEvent("HTTP服务", msg, warning); - }; - } - else - webService.LogEvent = null; - } - //打开比对失败的图片 - private void lblCompareResult_Click(object sender, EventArgs e) - { - if (lstCompareFailZoomImage.Count < 1) return; - FrmPhotoShow frm = new FrmPhotoShow(lstCompareFailZoomImage); - frm.ShowDialog(); - } - - //过程变量查看 - private void tsbtnSizeTag_Click(object sender, EventArgs e) - { - if (order == null || order.SizeTagDataList == null || order.SizeTagDataList.Count<1) - return; - - FrmShowSizeTag frm = new FrmShowSizeTag(order); - frm.Show(); - } - - //缺陷+比对与图纸查看 - private void tsbtnDefectImage_Click(object sender, EventArgs e) - { - //currProductModel = svcProduct.GetModelNav(53); - //order = svcOrder.GetModelNav("20230814002"); - AddTextEvent("打开窗口", "1"); - if (currProductModel ==null || order == null || order.DefectInfoList == null || order.DefectInfoList.Count < 1) - return; - AddTextEvent("打开窗口", "2"); - //图纸 - try - { - string gbxBmpPath = ""; - var attachmentFile = currProductModel.AttachmentList.FirstOrDefault(x => x.Type == 0); - if (attachmentFile != null) - { - gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}"; - if (!File.Exists(gbxBmpPath + ".bmp")) gbxBmpPath = ""; - } - AddTextEvent("打开窗口", "3"); - if (string.IsNullOrEmpty(gbxBmpPath)) - { - MessageBox.Show("图纸文件不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return; - } - AddTextEvent("打开窗口", "4"); - if (!File.Exists(gbxBmpPath + ".jpg"))//转背景后的图纸文件 - { - AddTextEvent("打开窗口", "5"); - //换背景JPG - Mat mat = Cv2.ImRead(gbxBmpPath + ".bmp"); - Cv2.CvtColor(mat, mat, ColorConversionCodes.RGB2GRAY);//转灰度图 - for (int i = 0; i < mat.Height; i++) - { - for (int j = 0; j < mat.Width; j++) - { - if (mat.At(i, j) == 255)//白色 - mat.Set(i, j, 0); - else - mat.Set(i, j, 255); - } - } - AddTextEvent("打开窗口", "6"); - //灰转彩 - //Cv2.CvtColor(mat, mat, ColorConversionCodes.GRAY2RGB); - //for (int i = 0; i < mat.Height; i++) - //{ - // for (int j = 0; j < mat.Width; j++) - // { - // if (mat.At(i, j) == 255)//白色 - // mat.Set(i, j, 0); //黄色 - // } - //} - OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat).Save(gbxBmpPath + ".jpg", ImageFormat.Jpeg); - } - AddTextEvent("打开窗口", "7"); - // - ToolStripButton btn = sender as ToolStripButton; - AddTextEvent("打开窗口", btn.Tag.ToString()); - FrmShowDefectImage frm = new FrmShowDefectImage(gbxBmpPath + ".jpg", order, string.IsNullOrEmpty(btn.Tag.ToString()) ? 0 : Convert.ToInt32(btn.Tag.ToString())); - frm.Show(); - AddTextEvent("打开窗口", "9"); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - } - } - - private void tsbtnLog_Click(object sender, EventArgs e) - { - if (string.IsNullOrWhiteSpace(Config.LogPath)) return; - string lsPath = (Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\").Replace("\\\\", "\\"); - if(!Directory.Exists(lsPath)) - Directory.CreateDirectory(lsPath); - System.Diagnostics.Process.Start("explorer.exe", lsPath); - } - } -} + } + /*//屏蔽扫码枪事件 + Task.Factory.StartNew(() => + { + devContainer.devCodeScanner.ScanerEvent?.Invoke(frm.inputData); + }); + */ + + //string code = Interaction.InputBox("请输入产品编码", "输入框", "", -1, -1).Trim(); + //if(code != "") + //{ + // Task.Factory.StartNew(() => + // { + // devContainer.devCodeScanner.ScanerEvent?.Invoke(frm.inputData); + // }); + //} + } + + private void txtProductSN_DoubleClick(object sender, EventArgs e) + { + //if (currentState != CurrentStateEnum.等待扫码 || this.txtProductCode.Text.Trim()=="") return; + + //string sn = Interaction.InputBox("请输入产品SN码", "输入框", "", -1, -1).Trim(); + //if (sn != "") + //{ + // this.txtProductSN.Text = sn; + // string code = this.txtProductCode.Text.Trim(); + // Task.Factory.StartNew(() => + // { + // devContainer.devCodeScanner.ScanerEvent?.Invoke(code); + // }); + //} + } + private void 测试ToolStripMenuItem_Click(object sender, EventArgs e) + { + tsbtnDefectImage.Enabled = tsbtnSizeImage.Enabled=true; + return; + Form1 frm = new Form1(); + frm.Show(); + //tsbtnDefectImage_Click(null, null); + return; + try + { + //string ls = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,182.257722637742,182.257727282667,0,0"; + //List list = new List(ls.Split(',')); + //lstPT = list.Select(q => Convert.ToDouble(q)).ToList(); + //updatePTValue(1,2); + //lstPT.Add(10); + //lstPT.Add(0); + //updatePTValue(1, 2); + //{ + // lstLineWidth.Add(res.Shanxian > 0 ? res.Shanxian : 0); + // updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue); + //} + //return; + + //loadProductCodeList(); + //FrmInput frm = new FrmInput(null, "请选择产品编码:"); + //if (frm.ShowDialog() != DialogResult.OK) + // return; + //var model = svcProduct.GetModelNav(frm.inputData); + //if (model == null) + // throw new Exception("没有此产品!"); + //order.ProductId = model.Id; + //order.BatchId = model.BatchId; + //order.StepId = model.StepId==null? 0:(int)model.StepId; + //frm = new FrmInput(null, "请输入SN:"); + //if (frm.ShowDialog() != DialogResult.OK) + // return; + //order.SN = frm.inputData; + + //frm = new FrmInput(null, "请输入主机台Mark点数据:", "[0,0,0,0,0,0,0,0]"); + //if (frm.ShowDialog() != DialogResult.OK) + // return; + //order.MarkData= frm.inputData; + //order.Tension1 = order.Tension2 = order.Tension3 = order.Tension4 = order.Tension5 = order.Tension5 + 3; + //order.PT1 = order.PT4 = order.PT5 = order.PT6 = order.PT6 + 1.33; + //order.LineWidth2 = order.LineWidth3 = order.LineWidth5 = order.LineWidth6 = +order.LineWidth6 + 1.22; + + //order.HeightValue = order.Height1 = order.Height3 = order.Height4 = 55; + //order.DefectCount = order.DefectCount + 22; + //order.YXCount = order.PPCount = 33; + //order.TimeLen = 1000; + //order.Succeed = true; + //order.ModifyUserCode = order.CreateUserCode = Config.loginUser.Code; + + //if (!svcOrder.Insert(order)) + // AddTextEvent("保存失败", $"保存生产记录失败!"); + //MessageBox.Show("成功!"); + + //--------------- + this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\1.bmp")); + this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\2.bmp")); + this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\3.bmp")); + } + catch(Exception ex) + { + MessageBox.Show(ex.Message); + } + } + + private void toolStripSeparator4_Click(object sender, EventArgs e) + { + + } + + private void chkHttpLog_CheckedChanged(object sender, EventArgs e) + { + if (this.chkHttpLog.Checked) + { + webService.LogEvent = (warning, msg) => + { + AddTextEvent("HTTP服务", msg, warning); + }; + } + else + webService.LogEvent = null; + } + //打开比对失败的图片 + private void lblCompareResult_Click(object sender, EventArgs e) + { + if (lstCompareFailZoomImage.Count < 1) return; + FrmPhotoShow frm = new FrmPhotoShow(lstCompareFailZoomImage); + frm.ShowDialog(); + } + + //过程变量查看 + private void tsbtnSizeTag_Click(object sender, EventArgs e) + { + if (order == null || order.SizeTagDataList == null || order.SizeTagDataList.Count<1) + return; + + FrmShowSizeTag frm = new FrmShowSizeTag(order); + frm.Show(); + } + + //缺陷+比对与图纸查看 + private void tsbtnDefectImage_Click(object sender, EventArgs e) + { + //currProductModel = svcProduct.GetModelNav(53); + //order = svcOrder.GetModelNav("20230814002"); + AddTextEvent("打开窗口", "1"); + if (currProductModel ==null || order == null || order.DefectInfoList == null || order.DefectInfoList.Count < 1) + return; + AddTextEvent("打开窗口", "2"); + //图纸 + try + { + string gbxBmpPath = ""; + var attachmentFile = currProductModel.AttachmentList.FirstOrDefault(x => x.Type == 0); + if (attachmentFile != null) + { + gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}"; + if (!File.Exists(gbxBmpPath + ".bmp")) gbxBmpPath = ""; + } + AddTextEvent("打开窗口", "3"); + if (string.IsNullOrEmpty(gbxBmpPath)) + { + MessageBox.Show("图纸文件不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + AddTextEvent("打开窗口", "4"); + if (!File.Exists(gbxBmpPath + ".jpg"))//转背景后的图纸文件 + { + AddTextEvent("打开窗口", "5"); + //换背景JPG + Mat mat = Cv2.ImRead(gbxBmpPath + ".bmp"); + Cv2.CvtColor(mat, mat, ColorConversionCodes.RGB2GRAY);//转灰度图 + for (int i = 0; i < mat.Height; i++) + { + for (int j = 0; j < mat.Width; j++) + { + if (mat.At(i, j) == 255)//白色 + mat.Set(i, j, 0); + else + mat.Set(i, j, 255); + } + } + AddTextEvent("打开窗口", "6"); + //灰转彩 + //Cv2.CvtColor(mat, mat, ColorConversionCodes.GRAY2RGB); + //for (int i = 0; i < mat.Height; i++) + //{ + // for (int j = 0; j < mat.Width; j++) + // { + // if (mat.At(i, j) == 255)//白色 + // mat.Set(i, j, 0); //黄色 + // } + //} + OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat).Save(gbxBmpPath + ".jpg", ImageFormat.Jpeg); + } + AddTextEvent("打开窗口", "7"); + // + ToolStripButton btn = sender as ToolStripButton; + AddTextEvent("打开窗口", btn.Tag.ToString()); + FrmShowDefectImage frm = new FrmShowDefectImage(gbxBmpPath + ".jpg", order, string.IsNullOrEmpty(btn.Tag.ToString()) ? 0 : Convert.ToInt32(btn.Tag.ToString())); + frm.Show(); + AddTextEvent("打开窗口", "9"); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); + } + } + + private void tsbtnLog_Click(object sender, EventArgs e) + { + if (string.IsNullOrWhiteSpace(Config.LogPath)) return; + string lsPath = (Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\").Replace("\\\\", "\\"); + if(!Directory.Exists(lsPath)) + Directory.CreateDirectory(lsPath); + System.Diagnostics.Process.Start("explorer.exe", lsPath); + } + } +} diff --git a/halftoneproject-master/Code/FrmMain.resx b/halftoneproject-master/Code/FrmMain.resx index 92a5777..4613102 100644 --- a/halftoneproject-master/Code/FrmMain.resx +++ b/halftoneproject-master/Code/FrmMain.resx @@ -642,21 +642,21 @@ iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAANSSURBVFhHtVdbS1RRGF1GGF2hwqdIIughKe2hp3rwIRHq - JYgGFcJbOV7KTAJ77Kkg8ldEVA8F/YRSijC7SRBUUEFJmne7mTrTWvbtmTO6nTnHxgWLc87e37e+tS9n - zxmsFK2oLa1EZZV4FvX7rXn1cQ4NZS04c68Z9YN1qJsWda+2NtQdsLDVQRsaaprRNBdHPOljOcrnW9BY - beH5hUYeR5O3cJAyoeWxtPyhGacf+Ar6qFhLi4b7wMHLQKE9ptCOhiKNzFdsGSY6UbvD0lNoB9aphj1m - 4gdw/TeQ/AX0PQG2WPMCKlCxtwmNCZkIQ27IZCtOHbL0BUhT2jOsoVrWnMYUG5PsFBn49A2w2boQQ0lh - B47v6kBVaMYQS82ktKTp9Fmr27rS4NSv+Q7cTqRN9L0GNln3iiENaUlT2qxxR7Wseylkwjn9A7xg8rX/ - oTScnrStTHYEZyIftJGHKy5witbS/ahPzHEImOGGGhJ174txlJY0TT43uG6FEvaJOc4Bjziy9aLufTGO - 0pKmyefGY4rylRz2iTmy6EMLh+59MY7SkqaF50ZIA70WLgO9vhjHyAaIghBLENqAtBhW8C/ag0lgOwOL - uZ47RTreQ44sFgoy4gyMSNPps614Ati2kPwNuMJdOs5NMid+AGZ15TuTWCwUZBQD0gpqi6pJE90y0ONL - ysUoBpYjZ/4lOCUbfwI1vHYaL/D06uIPxpQvyTGKAWlJU9qujmp+ATaYxFJw43z0iTlGMUCtTxYaHrPA - M5+YYxQD1HpuoeHBTXLTJ+YYxQDfgBsWGh7coTGulVdQDGtAGuPACQuNhmxnQVgDnP53FhYN3LlX9d76 - RMWwBrgBB3mN9n+BIz/vpl8/tb6lyGVAOS5Phw6/B8osPDu49tXzlsh3dWIQKJkGLur0ChZg0R5LkYGM - w0yxPGQ6mdcRMDE2CmT/C8dT8YgrpCsTDlsXvgKlFLnLkUxLlEUHrEsGBmRaRdh/i7GpQnzucgNi/+gY - dawrEyyoj8dxBaoAv1xPWlcG3gJFI0AlzR2zJvD+KNsq6GirNWWAJi65meDyDquWdaXRz2ORU/5KI+QG - jFtz3kDNdnKSR3K/allzJt4D+3g+19hj3vGZZwvP5N32SAB/AYFT8UsGgCOBAAAAAElFTkSuQmCC + YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAANRSURBVFhHtVdbS1RRGF1GGF2hwqdIIughKe2hp3rwIRHq + JYgGFcJbOV7KTAJ77Kkg8ldEWA8F/YRSijC7SRBUUEFJmne7mTrTWvbtmTO6nTnHpgWLc87e37e+tS9n + zxmsFq2oLa1EZZV4FvX7rfn/4xwaylpw5m4z6ofqUDcj6l5tbag7YGH/B21oqGlG03wc8aSP5ShfaEFj + tYXnFxp5HE3ewkHKhJbH0vKHZpy+7yvoo2ItLRruAQcvA4X2mEI7Goo0Ml+xFZjoRO0OS0+hHVinGvaY + ie/A9V9A8ifQ/xjYYs2LqEDF3iY0JmQiDLkhk604dcjSFyFNac+yhmpZcxrTbEyyU2Tgk9fAZutCDCWF + HTi+qwNVoRlDLDWT0pKm02etbutKg1O/5htwK5E20f8K2GTdq4Y0pCVNabPGbdWy7uWQCef0N/Ccydf+ + hdJwetK2MtkRnIl80EYerrjAKVpL92M+McdhYJYbaljUvS/GUVrSNPnc4LoVStgn5jgPPOTI1ou698U4 + SkuaJp8bjyjKV3LEJ+bIog8sHLr3xThKS5oWnhshDfRZuAz0+WIcIxsgCkIsQWgD0mJYwd9oD6aA7Qws + 5nruFOl4Dzm6VCjIiDMwKk2nz7biSWDbYvJX4Ap36QQ3ybz4HpjTtQdILBUKMooBaQW1RdWkiW4Z6PUl + 5WIUAyuRM/8CnJKNP4AaXjuNF3h6dfEHY9qX5BjFgLSkKW1XRzU/AxtMYjm4cT74xByjGKDWRwsNjzng + qU/MMYoBaj2z0PDgJrnpE3OMYoBvwA0LDQ/u0BjXyisohjUgjQnghIVGQ7azIKwBTv9bC4sG7tyrem99 + omJYA9yAQ7xG+7/AkZ9306+fWt9S5DKgHJenQ4ffA2UWnh1c++oFS+S7OjkElMwAF3V6BQuwaK+lyEDG + YaZYHjKdzOsImBgfA7L/heOpeMQV0pUJh60LX4BSitzhSGYkyqKD1iUDgzKtIuzvYWyqEJ+73IDYPzZO + HevKBAvq43FCgSrAL9eT1pWBN0DRKFBJc8esCbw/yrYKOtpqTRmgiUtuJri8I6plXWkM8FjklL/UCLkB + 49acN1CznZzikTygWtaciXfAPp7PNfaYd3zi2cIzebc9EsAfcrPxSTnKeRsAAAAASUVORK5CYII= @@ -665,11 +665,11 @@ YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAG9SURBVFhHYxgS4F+GuvqvFGVjKJf24KW9KM+nEJnk3+kq x/7nqf//l632H+iA/1+i5f6/DpC89MJVpOiRhQwnVDl1wbH6wmUPAjT/fwyV+Q90wH90B7wLkPr/wlX0 /0MbgRv3THjVodqoBx6Y8f1/7iRC0AFPbAT/3zfl+nzflCcQqhUveOkm2gtl4gekOOChOf9/kPpHFgIz - gdEmATUCBfzLUlb5Fiu/EeiA/1Ah/IAsB1gK/L/vwPX5pbvo3vfBUu1f4xXSfqcpN/7NUVv3Nlftz7dY + gdEmATUCBfzLUlb5Fiu/EeiA/1Ah/IAsB1gK/L/vwPX5pbvo3vfBUu1f4xXSfqcpN/7NUVv3Jlftz7dY hf80d8AzB+H/rz3F/38Ilv7/LU4BrPdfrhoYjzpg1AGjDhh1wNB3wM9s1ee/UhSv0s0BT92k/l8uDfkP LM89/tdrsUGlGP6HarG9CZAxA7YHJgMd8JMmDrgU7/Z/44o1/+es34NXwxMrfoOH5tz3qO6A9QdO/1+x 8yhBB4DAXWNB/vumvDMJOeBLrDyopoyFasMPSHEADDyyEPR4Ziv8BN0BH5LVvv3NUZ32PUZOEaqUMCDH - ATDwzkdS7l2glB/QwuRfmcrG/wrJaDdS4gCqgFEHjDpg3YFT9WAHrNtTDxUaBcMZMDAAAJbA3z1DE0Zi + ATDwzkdS7l2glB/QwuRfmcrG/wrJaDdS4gCqgFEHjDpg3YFT9WAHrNtTDxUaBcMZMDAAAIoH3zw7A9x2 AAAAAElFTkSuQmCC @@ -677,61 +677,61 @@ iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAALjSURBVFhH7ZbpS1RRHIZvTU0mQgRFEPSHBAUVbVhkm1pp - mWZm6jjjMs64t0JfIooyx9z3ZVxzGTUbTdOEchlnXx0N+tRXIRDezj3Mhekyls7cSYheeL6dw/Ne7uF3 + mWZmOjrjMs64t0JfIooyx9z3ZVxzGTUbTdOEchlnXx0N+tRXIRDezj3Mhekyls7cSYheeL6dw/Ne7uF3 DvPPpGj6AAqn96Pg0z7kT+1B3tRu5E7ugvJjGJQToVBMhCBnfAeyx8QqzxbhQuQr65HLP4hJgW3wbBMm G5VnjYqEK+CPPFO7VZgC/sozhCgg0e79sZZcMR7aVqxlwor1jFg+Ji7hy2XvtwRW4Hdy8uWrrNyzlGFL ZGlF373lspEACvxBDoUmZCWylRF5ltMQ+VdvufQd418Bvnxk+Ynvfz62/alnCytX8uXpw34U4MuHlx9j - eOkRhpYe+jxw0lHRNyJ3+5JLhjZYgJz2VW/54NIDDLrvQ+O+B81iMaFwzdPuS542uIECfPmAuwgDRNi/ + eOkRhpYe+jxw0lHRNyJ3+5KnDW2wADntq97ywaUHGHTfh8Z9D5rFYkLhmqfdl1wyuIECfPmAuwgDRNi/ WIB+Vz4hD32uXPQ5leuWp2rWWYAv71vMQy+R9boU6HXm4K1TTulxZBOy0G3PDJ68xyVHtzObkIluRwa6 - HDJ02aXoZLGlo8MmQbs1jSK4vNMpQ6dDig67hEAk9lS021Kgtt2F2pqMNksyWi13KC3mJIpgcjWRqe0p - aLMRkTUJrdbblBZLIuEWms0JaDLFUxpZjPEByX+5z1tsRGRNRLM1Ac0WIrHEockch0bzDTSYrqPBGIt6 - Qh2LIYbit5yNt7zRehMNFiIyxxJiUG++hjrTVSK7glpjNGoMUajRR6GaUKWPRNVCZGBydnxycm681pqi - iYyIjJdRzWK4RGQXUam/gMqF86gglOsiKAHJubAl+LO90hCBCv05SvnCWbzRnaGUEVTz4VDNhQsj58Le - XvzZXqY7DZXuFErnT6J07gReE0pmj1MElXNhS/Bne8ncMbyaPYqXLDNHKEGRc6GPCd5sfzFzGM+/HKIE - Vc6FPiZ4s/3Z54N/R84lY5LZKchsDyRsiU2Tc2FLbJqcSwp5bG6a/H+CF4b5CTYAGhE50nekAAAAAElF + HDJ02aXoZLGlo8OWhnarhCK4vNMpQ6dDig57GoFI7Klot6VAbbsLtTUZbZZktFruUFrMSRTB5GoiU9tT + 0GYjImsSWq23KS2WRMItNJsT0GSKpzSyGOMDkv9yn7fYiMiaiGZrApotRGKJQ5M5Do3mG2gwXUeDMRb1 + hDoWQwzFbzkbb3mj9SYaLERkjiXEoN58DXWmq0R2BbXGaNQYolCjj0I1oUofiaqFyMDk7Pjk5Nx4rTVF + ExkRGS+jmsVwicguolJ/AZUL51FBKNdFUAKSc2FL8Gd7pSECFfpzlPKFs3ijO0MpI6jmw6GaCxdGzoW9 + vfizvUx3GirdKZTOn0Tp3Am8JpTMHqcIKufCluDP9pK5Y3g1exQvWWaOUIIi50IfE7zZ/mLmMJ5/OUQJ + qpwLfUzwZvuzzwf/jpxLxiSzU5DZHkjYEpsm58KW2DQ5lxTy2Nw0+f8ELwzzE/paGgzH1hR8AAAAAElF TkSuQmCC iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHLSURBVFhH7dY9SAJhGMBxJyEIWpuCIGiNLDOXBhssMmyw - ITAHLTTIqEEiB6ulqSkIguaoISUKItM+SE/OtK64vpTLMg/D8vSwAsF6sngbKjixNDDuP9299z4vv+Hg - TlASRYbY2mtDUoRuix/ZQpaf99BaShfD6IEURAcf4UbPQrD3Fg6UgWOXjBjBJFgZ2l7YVi34AtZNQhYA - IV0cvgIIJQVu2RHYmzzn6w2uWjRWuOxiDLxtpzkBzmYc1hqxlEOCd6FRznyKwDS65C4fwNveLakXsFZi - jlSFKtERnwoPJ2tC2viKXxEAtMTdzwDHgLdTqQs17QwbElPxsUw/O/48ETOlrZTxPhPqY6DoAKKLggt1 - FMKGJDDmDLDjAHemNNDGB+ABPIAH8IDSB0QGH6M3+sTJnwFwxQnsjZ5B9iMiJ1UgRI8EpIoUHiopsVtG - zDibd9NFAaxrPLC85IF5m4NzYFuK19nr3ZcFB9h29mFxw50T8NamyFfhkOJzOQEaJuXvCKrRGHf5AD7C - ZIQ8+25EvgPYpyxg9kqXqEZbc/cTwEeUmq661jOd9+aMNjkJovDwS/7/jb8BFCQewAOsO17LO8DqsKAl - vv+cQPAK+g31RrDqJzoAAAAASUVORK5CYII= + YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHLSURBVFhH7dY9SAJhGMBxpyAIWpuCIGiN7NOlwQaLDB1s + CKxBCw00bJCowWppagoCoTlqyIiCyLSE8uQs64qzD+uyzMPQPE/MQLCeNN6GCk4sDYz7T3fvvc/Lbzi4 + E5REwZF43Z2WFaLb4ke2kxUXfbSKUocxejgBIV0S7jVxuOp/gCOZ73RfTIxirVg52l7Y1k34ItZLQgYA + fnUUvgIIGQVO8QlYW1wXm437dWiscFmbMXB3nuUE2Ntw2GjCErZWXI5GOTuU+mbRJXf5ALJ7d0RuwDoI + M6nwV6EjPhUwsLV+VXTNI/UBWuLuZ4BTwLuoxKWStge0sZnoeHooPvkyFTamLNf6SNo/yEDRAYScgktl + CAJaFpiJNMQnASLGFND6J+ABPIAH8IDSBwR1ydC9Jub9MwAu9cLe2DlkPiISUgFl6JGAVJBlxzKq2Skm + 5uxtjlRRAJsDLlhZdsHCqo1zYFeE11sbnDcFB6w6DmBpy5kTkG1beFhpE+HmnIABJuHpvlKiMe7yAXyE + iQlJ5t0IfgewzxnA/K06VoO25u4ngI8oJV19p2F6HifSKnYahAHDa/7/jb8BFCQewAMsDrfpHWCxmdAS + 339OIHgD1J71QoDsMyIAAAAASUVORK5CYII= iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAURSURBVFhH7VV7TNVlGH7JRjNbtS7L1uZWs7m12tzc2qpV - W6vW5qq15bTW1tZlNqgGQzAs5ICYXAK5CUPuxxBQQA4YCAIhKHfFEFDuCErCRDJIiXHO0/N2Php/0cGO - /eWzffvt9/u+93mf7739ZDlAlmywWyVy3irNc1a5BKtAn/qu33XfHHUvHAdknT3L4whyVgEH7wd+vAfI - 9gCsK5zPbPln2bOlSM8b0/8OR5a8M523agZHXwAqXgOOv8XFZ/nzQOk6wPY0ULQGyHuYAigoUzCTKdNq - ZyhuHY7Mu7aggE5qNgGtAUBnBNAdCZzbCZz2AhreB2pfB6pfAY5tAI6sBXIeBNIZDS5Hhmw2VMsH9sv6 - qYMP3EQVnXTQ8UgxMH4CmKgBLhUAAwlAVyCFfAI0bwFOvQtUvQqUPMs0PQKkCn5LlRvKYyiXh/k0z5Mo - fpHk/nRuA37vAWbHgT+GgakW4EoRMBwP9HzLyHwNtH8ONG1mNBgR23OsD0YiRTCfJPWG0nU4kuUNpJOg - lGQdDPl4ndO5Ym4SmO4CJo8DY9kUwf2+IOA8U3SWaWlkNCpZI4dZGymeQBJTsU82GmrXYI8XK1IpoGwj - 8/0DBfzsvLk6nx0DZs4B1yhgPAcYjaWIPUxJKEVsB85sBereo3gWafZjQCI7I1HyDLVrmI2SCSSy1Y6+ - ydBamIJCOmTYp7u56Pz6KeBqKdOQxXqI434URYQDvSzODh8W50fsEkYh5ykgTqB8hvrfgUhZjRhWcTwF - FL3EkH5F4iSGm0V4tYqhrzbOefvLyXQe41zDFNHPKHSyZppYmBVs19xnnDzkc8TJo8bF0nBEy1pEUUDc - vSRgMdV8APzCmw3so8MDwK90PKY3X+T84oKAMKaMtdD0GQUwfWqvPORTXuNiaSBc1nBR9UpOPBKUk6iJ - ee0KpohoOmPljzDs6nTxGqKA3l1MAQU0fOq0U/sYCiCfY7eLEUCweHYGyzz23A1kcAiVsA7qPmYt+LHI - WA8DnAlDFDKstzZL3/X7hRDnOT2vdmpPHuUz9K5hPlTaEcooJHHEHnqZo5f93fwlw/sdb/k9nfG26nRo - wbnent91X89VsRXVTu2VJ1TaDLVrcATLTlhoGMVWzFrPlnqbt2JYz7DAunnLXm07Ol1Y+q7fdV/P6Xm1 - U3vy2C0SYqhdg2OHPDGzTaYRRBEJT/JHwxFbwSg0eHPYcPx2s9p72Hb9vH0fo3B+t/O77uu5XP4b1I72 - 417yp/IZateBQPkGOyggjL/f/SymQrZVFXPb7MuC5I0HM5h/q/N5gcOojSNZ9/VcCs+rHe3tgRJmKJcH - bJIVdn/JwXaKiHicBcXJZuOEa+bY7aPjUc6CsQo+S/jOtmxlC5ZxAKXznJ6nnT1AypXHUC4f2hH2bVKN - AP7noznVCvhnbGPIB+l0gpNxssP5HOJ7K0d2MQXsZeX7e8DuJ+UOX1lpqG4dSjLvI/UIYkHlfwi06Bzg - v+H6IHBjwvkcqXV+z2P+Q1bD7iOVbnG+AJI95J1og1/aMYTk1SO27CxyW0Zx6PRlpNf2ILKoCUHWKvgm - 2/BFTD7gJfcZU/chJj4x1xUBltjkVGPiXmgE0k70orLrCi5OzWFylk1w7SYa+yeQe7IHUcUt2HW44e8I - GBP3wjvBZnElAluj8y3GxL24EwGFClgqAirAHL098EsttwQHhzuWiMDtu/1i7P2p3bJYQERh4//j+A7c - D5G/AFoWc7tnHzTjAAAAAElFTkSuQmCC + YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAUQSURBVFhH7VV7TNVlGH7JRjNbtS7L1uZWs7m12tzc2qpV + W6vW5qq15bTW1tZlNqgGQzAs5IAYAoHchCH3YwgoIAcMBIEQlLtiCCh3BCVhIhmkxDjn6Xk7H42/6GDH + /vLZvv32+33f+7zP995+shwgSzbYrRI5b5XmOatcglWgT33X77pvjroXjgOyzp7lcQQ5q4CD9wM/3gNk + ewDWFc5ntvyz7NlSpOeN6X+HI0vemc5bNYOjLwAVrwHH3+Lis/x5oHQdYHsaKFoD5D1MARSUKZjJlGm1 + MxS3DkfmXVtQQCc1m4DWAKAzAuiOBM7tBE57AQ3vA7WvA9WvAMc2AEfWAjkPAumMBpcjQzYbquUD+2X9 + 1MEHbqKKTjroeKQYGD8BTNQAlwqAgQSgK5BCPgGatwCn3gWqXgVKnmWaHgFSBb+lyg3lMZTLw3ya50kU + v0hyfzq3Ab/3ALPjwB/DwFQLcKUIGI4Her5lZL4G2j8HmjYzGoyI7TnWByORIphPknpD6TocyfIG0klQ + SrIOhny8zulcMTcJTHcBk8eBsWyK4H5fEHCeKTrLtDQyGpWskcOsjRRPIImp2CcbDbVrsMeLFakUULaR + +f6BAn523lydz44BM+eAaxQwngOMxlJEOFMSShHbgTNbgbr3KJ5Fmv0YkMjOSJQ8Q+0aZqNkAolstaNv + MrQWpqCQDhn26W4uOr9+CrhayjRksR7iuB9FEXuAXhZnhw+L8yN2CaOQ8xQQJ1A+Q/3vQKSsRgyrOJ4C + il5iSL8icRLDzSK8WsXQVxvnvP3lZDqPca5hiuhnFDpZM00szAq2a+4zTh7yOeLkUeNiaTiiZS2iKCDu + XhKwmGo+AH7hzQb20eEB4Fc6HtObL3J+cUFAGFPGWmj6jAKYPrVXHvIpr3GxNLBH1nBR9UpOPBKUk6iJ + ee0KpohoOmPljzDs6nTxGqKA3l1MAQU0fOq0U/sYCiCfY7eLEUCweHYGyzzC7wYyOIRKWAd1H7MW/Fhk + rIcBzoQhChnWW5ul7/r9QojznJ5XO7Unj/IZetcwHyrtCGUUkjhiD73M0cv+bv6S4f2Ot/yeznhbdTq0 + 4Fxvz++6r+eq2Ipqp/bKEypthto1OIJlJyw0jGIrZq1nS73NWzGsZ1hg3bxlr7YdnS4sfdfvuq/n9Lza + qT157BYJMdSuwbFDnpjZJtMIooiEJ/mj4YitYBQavDlsOH67We09bLt+3r6PUTi/2/ld9/VcLv8Nakf7 + cS/5U/kMtetAoHyDHRQQxt/vfhZTIduqirlt9mVB8saDGcy/1fm8wGHUxpGs+3ouhefVjvb2QAkzlMsD + NskKu7/kYDtFRDzOguJks3HCNXPs9tHxKGfBWAWfJXxnW7ayBcs4gNJ5Ts/Tzh4g5cpjKJcP7Qj7NqlG + AP/z0ZxqBfwztjHkg3Q6wck42eF8DvG9lSO7mAL2svL9PWD3k3KHr6w0VLcOJZn3kXoEsaDyPwRadA7w + 33B9ELgx4XyO1Dq/5zH/Iath95FKtzhfAMke8k60wS/tGELy6hFbdha5LaM4dPoy0mt7EFnUhCBrFXyT + bfgiJh/wkvuMqfsQE5+Y64oAS2xyqjFxLzQCaSd6Udl1BRen5jA5yya4dhON/RPIPdmDqOIW7Drc8HcE + jIl74Z1gs7gSga3R+RZj4l7ciYBCBSwVARVgjt4e+KWWW4KDwx1LROD23X4x9v7UblksIKKw8f9xfAfu + h8hfV8RzuqW13GsAAAAASUVORK5CYII= diff --git a/halftoneproject-master/Code/FrmSysSetting.Designer.cs b/halftoneproject-master/Code/FrmSysSetting.Designer.cs index 943bf8d..12233b5 100644 --- a/halftoneproject-master/Code/FrmSysSetting.Designer.cs +++ b/halftoneproject-master/Code/FrmSysSetting.Designer.cs @@ -102,6 +102,8 @@ this.label6 = new System.Windows.Forms.Label(); this.groupBox22 = new System.Windows.Forms.GroupBox(); this.panel22 = new System.Windows.Forms.Panel(); + this.numOffset = new System.Windows.Forms.NumericUpDown(); + this.label7 = new System.Windows.Forms.Label(); this.label61 = new System.Windows.Forms.Label(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.groupBox14 = new System.Windows.Forms.GroupBox(); @@ -235,6 +237,7 @@ this.numHttpPort = new System.Windows.Forms.NumericUpDown(); this.label49 = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); + this.cbOpenFlawDistribution = new System.Windows.Forms.CheckBox(); this.toolStrip1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.panel1.SuspendLayout(); @@ -263,6 +266,7 @@ this.panel23.SuspendLayout(); this.groupBox22.SuspendLayout(); this.panel22.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numOffset)).BeginInit(); this.tabPage1.SuspendLayout(); this.groupBox14.SuspendLayout(); this.panel14.SuspendLayout(); @@ -1210,6 +1214,8 @@ // panel22 // this.panel22.BackColor = System.Drawing.Color.White; + this.panel22.Controls.Add(this.numOffset); + this.panel22.Controls.Add(this.label7); this.panel22.Controls.Add(this.label61); this.panel22.Controls.Add(this.cobTension_PortNum); this.panel22.Dock = System.Windows.Forms.DockStyle.Fill; @@ -1219,10 +1225,44 @@ this.panel22.Size = new System.Drawing.Size(462, 37); this.panel22.TabIndex = 0; // + // numOffset + // + this.numOffset.DecimalPlaces = 2; + this.numOffset.Increment = new decimal(new int[] { + 1, + 0, + 0, + 131072}); + this.numOffset.Location = new System.Drawing.Point(296, 9); + this.numOffset.Margin = new System.Windows.Forms.Padding(2); + this.numOffset.Maximum = new decimal(new int[] { + 10, + 0, + 0, + 0}); + this.numOffset.Minimum = new decimal(new int[] { + 10, + 0, + 0, + -2147483648}); + this.numOffset.Name = "numOffset"; + this.numOffset.Size = new System.Drawing.Size(120, 21); + this.numOffset.TabIndex = 13; + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(234, 13); + this.label7.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(53, 12); + this.label7.TabIndex = 12; + this.label7.Text = "补偿值:"; + // // label61 // this.label61.AutoSize = true; - this.label61.Location = new System.Drawing.Point(5, 12); + this.label61.Location = new System.Drawing.Point(5, 13); this.label61.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label61.Name = "label61"; this.label61.Size = new System.Drawing.Size(41, 12); @@ -2687,6 +2727,7 @@ // // tabPage9 // + this.tabPage9.Controls.Add(this.cbOpenFlawDistribution); this.tabPage9.Controls.Add(this.ckSkipSizeFailed); this.tabPage9.Controls.Add(this.chkSkipSmallAxis); this.tabPage9.Controls.Add(this.chkSkipScannerCC); @@ -2703,7 +2744,7 @@ this.tabPage9.Name = "tabPage9"; this.tabPage9.Size = new System.Drawing.Size(482, 529); this.tabPage9.TabIndex = 8; - this.tabPage9.Text = "传感器过滤"; + this.tabPage9.Text = "功能过滤"; this.tabPage9.UseVisualStyleBackColor = true; // // ckSkipSizeFailed @@ -2923,6 +2964,17 @@ this.label49.TabIndex = 4; this.label49.Text = "本机IP:"; // + // cbOpenFlawDistribution + // + this.cbOpenFlawDistribution.AutoSize = true; + this.cbOpenFlawDistribution.Location = new System.Drawing.Point(19, 304); + this.cbOpenFlawDistribution.Margin = new System.Windows.Forms.Padding(2); + this.cbOpenFlawDistribution.Name = "cbOpenFlawDistribution"; + this.cbOpenFlawDistribution.Size = new System.Drawing.Size(96, 16); + this.cbOpenFlawDistribution.TabIndex = 12; + this.cbOpenFlawDistribution.Text = "启用缺陷分布"; + this.cbOpenFlawDistribution.UseVisualStyleBackColor = true; + // // FrmSysSetting // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); @@ -2980,6 +3032,7 @@ this.groupBox22.ResumeLayout(false); this.panel22.ResumeLayout(false); this.panel22.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numOffset)).EndInit(); this.tabPage1.ResumeLayout(false); this.groupBox14.ResumeLayout(false); this.panel14.ResumeLayout(false); @@ -3271,5 +3324,8 @@ private System.Windows.Forms.Panel panel22; private System.Windows.Forms.Label label61; private System.Windows.Forms.CheckBox ckSkipSizeFailed; + private System.Windows.Forms.NumericUpDown numOffset; + private System.Windows.Forms.Label label7; + private System.Windows.Forms.CheckBox cbOpenFlawDistribution; } } \ No newline at end of file diff --git a/halftoneproject-master/Code/FrmSysSetting.cs b/halftoneproject-master/Code/FrmSysSetting.cs index 4ad0e60..4538049 100644 --- a/halftoneproject-master/Code/FrmSysSetting.cs +++ b/halftoneproject-master/Code/FrmSysSetting.cs @@ -1,465 +1,474 @@ -using Newtonsoft.Json.Linq; -using ProductionControl.Utils; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using System.Windows.Forms.VisualStyles; - -namespace ProductionControl -{ - public partial class FrmSysSetting : Form - { - public FrmSysSetting() - { - InitializeComponent(); - } - private void FrmSetParams_Load(object sender, EventArgs e) - { - initData(); - } - private void initData() - { - string configPath = Application.StartupPath + "\\SysConfig.ini"; - string lsTmp = ""; - - var comNameList = Utils.SSerialPort.getPortNames().ToList(); - comNameList.ForEach(comName => - { - this.cobLight_PortNum.Items.Add(comName); - this.cobTension_PortNum.Items.Add(comName); - this.cobSmallAxis_ComName.Items.Add(comName); - }); - - //Skip - this.chkSkipAxis0.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipAxis0") == "1"; - this.chkSkipAxis1.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipAxis1") == "1"; - this.chkSkipAxis2.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipAxis2") == "1"; - this.chkSkipAxis3.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipAxis3") == "1"; - this.chkSkipTension.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipTension") == "1"; - this.chkSkipHeight.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipHeight") == "1"; - this.chkSkipLight.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipLight") == "1"; - this.chkSkipScannerGL.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipScannerGL") == "1"; - this.chkSkipScannerCC.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipScannerCC") == "1"; - this.chkSkipSmallAxis.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipSmallAxis") == "1"; - - this.ckSkipSizeFailed.Checked = Util.ReadIniValue(configPath, "SKIP", "MarkErrorStop") == "1"; - - //DEV - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_PulseOutMode"); - EnumUtil.BindToEnumName(this.cobAxis0PulseOutMode, typeof(AxisPulseOutMode), lsTmp == "" ? AxisPulseOutMode.O_CW_CCW : (AxisPulseOutMode)Convert.ToInt32(lsTmp)); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_PulseOutMode"); - EnumUtil.BindToEnumName(this.cobAxis1PulseOutMode, typeof(AxisPulseOutMode), lsTmp == "" ? AxisPulseOutMode.O_CW_CCW : (AxisPulseOutMode)Convert.ToInt32(lsTmp)); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_PulseOutMode"); - EnumUtil.BindToEnumName(this.cobAxis2PulseOutMode, typeof(AxisPulseOutMode), lsTmp == "" ? AxisPulseOutMode.O_CW_CCW : (AxisPulseOutMode)Convert.ToInt32(lsTmp)); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_PulseOutMode"); - EnumUtil.BindToEnumName(this.cobAxis3PulseOutMode, typeof(AxisPulseOutMode), lsTmp == "" ? AxisPulseOutMode.O_CW_CCW : (AxisPulseOutMode)Convert.ToInt32(lsTmp)); - - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_HomeMode"); - EnumUtil.BindToEnumName(this.cobAxis0HomeMode, typeof(AxitHomeMode), lsTmp == "" ? AxitHomeMode.MODE11_LmtSearch_Ref : (AxitHomeMode)Convert.ToInt32(lsTmp)); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_HomeMode"); - EnumUtil.BindToEnumName(this.cobAxis1HomeMode, typeof(AxitHomeMode), lsTmp == "" ? AxitHomeMode.MODE11_LmtSearch_Ref : (AxitHomeMode)Convert.ToInt32(lsTmp)); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_HomeMode"); - EnumUtil.BindToEnumName(this.cobAxis2HomeMode, typeof(AxitHomeMode), lsTmp == "" ? AxitHomeMode.MODE11_LmtSearch_Ref : (AxitHomeMode)Convert.ToInt32(lsTmp)); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_HomeMode"); - EnumUtil.BindToEnumName(this.cobAxis3HomeMode, typeof(AxitHomeMode), lsTmp == "" ? AxitHomeMode.MODE11_LmtSearch_Ref : (AxitHomeMode)Convert.ToInt32(lsTmp)); - - var lstLightName = Utils.EnumUtil.GetNamesArr(); - this.cobLight_Name.Items.AddRange(lstLightName); - lsTmp = Util.ReadIniValue(configPath, "DEV", "Light_Name"); - if (string.IsNullOrWhiteSpace(lsTmp)) - this.cobLight_Name.SelectedIndex = 0; - else - this.cobLight_Name.Text = ((LightDevNameEnum)Convert.ToInt32(lsTmp)).ToString(); - this.cobLight_PortNum.Text = "COM" + Util.ReadIniValue(configPath, "DEV", "Light_PortNum"); - this.cobTension_PortNum.Text = "COM" + Util.ReadIniValue(configPath, "DEV", "Tension_PortNum"); - this.cobSmallAxis_ComName.Text = Util.ReadIniValue(configPath, "DEV", "SmallAxis_ComName"); - - this.cobAxis0HomeDir.SelectedIndex = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "Axis0_HomeDir")); - this.cobAxis1HomeDir.SelectedIndex = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "Axis1_HomeDir")); - this.cobAxis2HomeDir.SelectedIndex = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "Axis2_HomeDir")); - this.cobAxis3HomeDir.SelectedIndex = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "Axis3_HomeDir")); - - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeVelLow"); - if (!string.IsNullOrWhiteSpace(lsTmp)) - { - JArray Axis_HomeVelLow = JArray.Parse(lsTmp); - this.numAxis0HomeVelLow.Value = Axis_HomeVelLow.Count > 0 ? (decimal)Axis_HomeVelLow[0] : 0; - this.numAxis1HomeVelLow.Value = Axis_HomeVelLow.Count > 1 ? (decimal)Axis_HomeVelLow[1] : 0; - this.numAxis2HomeVelLow.Value = Axis_HomeVelLow.Count > 2 ? (decimal)Axis_HomeVelLow[2] : 0; - this.numAxis3HomeVelLow.Value = Axis_HomeVelLow.Count > 3 ? (decimal)Axis_HomeVelLow[3] : 0; - } - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeVelHigh"); - if (!string.IsNullOrWhiteSpace(lsTmp)) - { - JArray Axis_HomeVelHigh = JArray.Parse(lsTmp); - this.numAxis0HomeVelHigh.Value = Axis_HomeVelHigh.Count > 0 ? (decimal)Axis_HomeVelHigh[0] : 0; - this.numAxis1HomeVelHigh.Value = Axis_HomeVelHigh.Count > 1 ? (decimal)Axis_HomeVelHigh[1] : 0; - this.numAxis2HomeVelHigh.Value = Axis_HomeVelHigh.Count > 2 ? (decimal)Axis_HomeVelHigh[2] : 0; - this.numAxis3HomeVelHigh.Value = Axis_HomeVelHigh.Count > 3 ? (decimal)Axis_HomeVelHigh[3] : 0; - } - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeAcc"); - if (!string.IsNullOrWhiteSpace(lsTmp)) - { - JArray Axis_HomeAcc = JArray.Parse(lsTmp); - this.numAxis0HomeAcc.Value = Axis_HomeAcc.Count > 0 ? (decimal)Axis_HomeAcc[0] : 0; - this.numAxis1HomeAcc.Value = Axis_HomeAcc.Count > 1 ? (decimal)Axis_HomeAcc[1] : 0; - this.numAxis2HomeAcc.Value = Axis_HomeAcc.Count > 2 ? (decimal)Axis_HomeAcc[2] : 0; - this.numAxis3HomeAcc.Value = Axis_HomeAcc.Count > 3 ? (decimal)Axis_HomeAcc[3] : 0; - } - lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeDec"); - if (!string.IsNullOrWhiteSpace(lsTmp)) - { - JArray Axis_HomeDec = JArray.Parse(lsTmp); - this.numAxis0HomeDec.Value = Axis_HomeDec.Count > 0 ? (decimal)Axis_HomeDec[0] : 0; - this.numAxis1HomeDec.Value = Axis_HomeDec.Count > 1 ? (decimal)Axis_HomeDec[1] : 0; - this.numAxis2HomeDec.Value = Axis_HomeDec.Count > 2 ? (decimal)Axis_HomeDec[2] : 0; - this.numAxis3HomeDec.Value = Axis_HomeDec.Count > 3 ? (decimal)Axis_HomeDec[3] : 0; - } - - this.txtHeightDev_IP.Text = Util.ReadIniValue(configPath, "DEV", "HeightDev_IP"); - this.numHeightDev_Port.Value = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "HeightDev_Port")); - this.numHeightDev_SafeValue.Value = Convert.ToDecimal(Util.ReadIniValue(configPath, "DEV", "HeightDev_SafeValue")); - - lsTmp = Util.ReadIniValue(configPath, "DEV", "HeightDev_BaseList"); - if (!string.IsNullOrWhiteSpace(lsTmp)) - { - JArray HeightDev_BaseList = JArray.Parse(lsTmp); - this.numHeightBase0.Value = HeightDev_BaseList.Count > 0 ? (decimal)HeightDev_BaseList[0] : 0; - this.numHeightBase1.Value = HeightDev_BaseList.Count > 1 ? (decimal)HeightDev_BaseList[1] : 0; - this.numHeightBase2.Value = HeightDev_BaseList.Count > 2 ? (decimal)HeightDev_BaseList[2] : 0; - this.numHeightBase3.Value = HeightDev_BaseList.Count > 3 ? (decimal)HeightDev_BaseList[3] : 0; - this.numHeightBase4.Value = HeightDev_BaseList.Count > 4 ? (decimal)HeightDev_BaseList[4] : 0; - } - - this.txtIO_DevNum.Text = Util.ReadIniValue(configPath, "DEV", "IOCard_DeviceNum"); - this.txtDefect_Path.Text = Util.ReadIniValue(configPath, "DEV", "Defect_SavePath"); - this.txtDefect_Small_Path.Text = Util.ReadIniValue(configPath, "DEV", "Defect_Small_SavePath"); - this.txtDefect_Compress_SavePath.Text = Util.ReadIniValue(configPath, "DEV", "Defect_Compress_SavePath"); - - //int liTmp = -1; - double ldTmp = -1; - lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_SavePath_AutoClear"); - //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); - ldTmp = Convert.ToDouble(lsTmp); - chkDefect_Path_AutoClear.Checked = (ldTmp > -1); - if (ldTmp > -1) numDefect_Path_AutoClear.Value = (decimal)ldTmp; - +using Newtonsoft.Json.Linq; +using ProductionControl.Utils; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; + +namespace ProductionControl +{ + public partial class FrmSysSetting : Form + { + public FrmSysSetting() + { + InitializeComponent(); + } + private void FrmSetParams_Load(object sender, EventArgs e) + { + initData(); + } + private void initData() + { + string configPath = Application.StartupPath + "\\SysConfig.ini"; + string lsTmp = ""; + + var comNameList = Utils.SSerialPort.getPortNames().ToList(); + comNameList.ForEach(comName => + { + this.cobLight_PortNum.Items.Add(comName); + this.cobTension_PortNum.Items.Add(comName); + this.cobSmallAxis_ComName.Items.Add(comName); + }); + + //Skip + this.chkSkipAxis0.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipAxis0") == "1"; + this.chkSkipAxis1.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipAxis1") == "1"; + this.chkSkipAxis2.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipAxis2") == "1"; + this.chkSkipAxis3.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipAxis3") == "1"; + this.chkSkipTension.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipTension") == "1"; + this.chkSkipHeight.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipHeight") == "1"; + this.chkSkipLight.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipLight") == "1"; + this.chkSkipScannerGL.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipScannerGL") == "1"; + this.chkSkipScannerCC.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipScannerCC") == "1"; + this.chkSkipSmallAxis.Checked = Util.ReadIniValue(configPath, "SKIP", "SkipSmallAxis") == "1"; + + this.ckSkipSizeFailed.Checked = Util.ReadIniValue(configPath, "SKIP", "MarkErrorStop") == "1"; + this.cbOpenFlawDistribution.Checked = Util.ReadIniValue(configPath, "SKIP", "OpenFlawDistribution") == "1"; + //DEV + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_PulseOutMode"); + EnumUtil.BindToEnumName(this.cobAxis0PulseOutMode, typeof(AxisPulseOutMode), lsTmp == "" ? AxisPulseOutMode.O_CW_CCW : (AxisPulseOutMode)Convert.ToInt32(lsTmp)); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_PulseOutMode"); + EnumUtil.BindToEnumName(this.cobAxis1PulseOutMode, typeof(AxisPulseOutMode), lsTmp == "" ? AxisPulseOutMode.O_CW_CCW : (AxisPulseOutMode)Convert.ToInt32(lsTmp)); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_PulseOutMode"); + EnumUtil.BindToEnumName(this.cobAxis2PulseOutMode, typeof(AxisPulseOutMode), lsTmp == "" ? AxisPulseOutMode.O_CW_CCW : (AxisPulseOutMode)Convert.ToInt32(lsTmp)); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_PulseOutMode"); + EnumUtil.BindToEnumName(this.cobAxis3PulseOutMode, typeof(AxisPulseOutMode), lsTmp == "" ? AxisPulseOutMode.O_CW_CCW : (AxisPulseOutMode)Convert.ToInt32(lsTmp)); + + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis0_HomeMode"); + EnumUtil.BindToEnumName(this.cobAxis0HomeMode, typeof(AxitHomeMode), lsTmp == "" ? AxitHomeMode.MODE11_LmtSearch_Ref : (AxitHomeMode)Convert.ToInt32(lsTmp)); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis1_HomeMode"); + EnumUtil.BindToEnumName(this.cobAxis1HomeMode, typeof(AxitHomeMode), lsTmp == "" ? AxitHomeMode.MODE11_LmtSearch_Ref : (AxitHomeMode)Convert.ToInt32(lsTmp)); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis2_HomeMode"); + EnumUtil.BindToEnumName(this.cobAxis2HomeMode, typeof(AxitHomeMode), lsTmp == "" ? AxitHomeMode.MODE11_LmtSearch_Ref : (AxitHomeMode)Convert.ToInt32(lsTmp)); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis3_HomeMode"); + EnumUtil.BindToEnumName(this.cobAxis3HomeMode, typeof(AxitHomeMode), lsTmp == "" ? AxitHomeMode.MODE11_LmtSearch_Ref : (AxitHomeMode)Convert.ToInt32(lsTmp)); + + var lstLightName = Utils.EnumUtil.GetNamesArr(); + this.cobLight_Name.Items.AddRange(lstLightName); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Light_Name"); + if (string.IsNullOrWhiteSpace(lsTmp)) + this.cobLight_Name.SelectedIndex = 0; + else + this.cobLight_Name.Text = ((LightDevNameEnum)Convert.ToInt32(lsTmp)).ToString(); + this.cobLight_PortNum.Text = "COM" + Util.ReadIniValue(configPath, "DEV", "Light_PortNum"); + this.cobTension_PortNum.Text = "COM" + Util.ReadIniValue(configPath, "DEV", "Tension_PortNum"); + lsTmp = Util.ReadIniValue(configPath, "DEV", "Tension_Offset"); + if (string.IsNullOrWhiteSpace(lsTmp)) + this.numOffset.Value = 0; + else + this.numOffset.Value = (decimal)double.Parse(lsTmp); + this.cobSmallAxis_ComName.Text = Util.ReadIniValue(configPath, "DEV", "SmallAxis_ComName"); + + this.cobAxis0HomeDir.SelectedIndex = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "Axis0_HomeDir")); + this.cobAxis1HomeDir.SelectedIndex = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "Axis1_HomeDir")); + this.cobAxis2HomeDir.SelectedIndex = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "Axis2_HomeDir")); + this.cobAxis3HomeDir.SelectedIndex = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "Axis3_HomeDir")); + + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeVelLow"); + if (!string.IsNullOrWhiteSpace(lsTmp)) + { + JArray Axis_HomeVelLow = JArray.Parse(lsTmp); + this.numAxis0HomeVelLow.Value = Axis_HomeVelLow.Count > 0 ? (decimal)Axis_HomeVelLow[0] : 0; + this.numAxis1HomeVelLow.Value = Axis_HomeVelLow.Count > 1 ? (decimal)Axis_HomeVelLow[1] : 0; + this.numAxis2HomeVelLow.Value = Axis_HomeVelLow.Count > 2 ? (decimal)Axis_HomeVelLow[2] : 0; + this.numAxis3HomeVelLow.Value = Axis_HomeVelLow.Count > 3 ? (decimal)Axis_HomeVelLow[3] : 0; + } + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeVelHigh"); + if (!string.IsNullOrWhiteSpace(lsTmp)) + { + JArray Axis_HomeVelHigh = JArray.Parse(lsTmp); + this.numAxis0HomeVelHigh.Value = Axis_HomeVelHigh.Count > 0 ? (decimal)Axis_HomeVelHigh[0] : 0; + this.numAxis1HomeVelHigh.Value = Axis_HomeVelHigh.Count > 1 ? (decimal)Axis_HomeVelHigh[1] : 0; + this.numAxis2HomeVelHigh.Value = Axis_HomeVelHigh.Count > 2 ? (decimal)Axis_HomeVelHigh[2] : 0; + this.numAxis3HomeVelHigh.Value = Axis_HomeVelHigh.Count > 3 ? (decimal)Axis_HomeVelHigh[3] : 0; + } + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeAcc"); + if (!string.IsNullOrWhiteSpace(lsTmp)) + { + JArray Axis_HomeAcc = JArray.Parse(lsTmp); + this.numAxis0HomeAcc.Value = Axis_HomeAcc.Count > 0 ? (decimal)Axis_HomeAcc[0] : 0; + this.numAxis1HomeAcc.Value = Axis_HomeAcc.Count > 1 ? (decimal)Axis_HomeAcc[1] : 0; + this.numAxis2HomeAcc.Value = Axis_HomeAcc.Count > 2 ? (decimal)Axis_HomeAcc[2] : 0; + this.numAxis3HomeAcc.Value = Axis_HomeAcc.Count > 3 ? (decimal)Axis_HomeAcc[3] : 0; + } + lsTmp = Util.ReadIniValue(configPath, "DEV", "Axis_HomeDec"); + if (!string.IsNullOrWhiteSpace(lsTmp)) + { + JArray Axis_HomeDec = JArray.Parse(lsTmp); + this.numAxis0HomeDec.Value = Axis_HomeDec.Count > 0 ? (decimal)Axis_HomeDec[0] : 0; + this.numAxis1HomeDec.Value = Axis_HomeDec.Count > 1 ? (decimal)Axis_HomeDec[1] : 0; + this.numAxis2HomeDec.Value = Axis_HomeDec.Count > 2 ? (decimal)Axis_HomeDec[2] : 0; + this.numAxis3HomeDec.Value = Axis_HomeDec.Count > 3 ? (decimal)Axis_HomeDec[3] : 0; + } + + this.txtHeightDev_IP.Text = Util.ReadIniValue(configPath, "DEV", "HeightDev_IP"); + this.numHeightDev_Port.Value = Convert.ToInt32(Util.ReadIniValue(configPath, "DEV", "HeightDev_Port")); + this.numHeightDev_SafeValue.Value = Convert.ToDecimal(Util.ReadIniValue(configPath, "DEV", "HeightDev_SafeValue")); + + lsTmp = Util.ReadIniValue(configPath, "DEV", "HeightDev_BaseList"); + if (!string.IsNullOrWhiteSpace(lsTmp)) + { + JArray HeightDev_BaseList = JArray.Parse(lsTmp); + this.numHeightBase0.Value = HeightDev_BaseList.Count > 0 ? (decimal)HeightDev_BaseList[0] : 0; + this.numHeightBase1.Value = HeightDev_BaseList.Count > 1 ? (decimal)HeightDev_BaseList[1] : 0; + this.numHeightBase2.Value = HeightDev_BaseList.Count > 2 ? (decimal)HeightDev_BaseList[2] : 0; + this.numHeightBase3.Value = HeightDev_BaseList.Count > 3 ? (decimal)HeightDev_BaseList[3] : 0; + this.numHeightBase4.Value = HeightDev_BaseList.Count > 4 ? (decimal)HeightDev_BaseList[4] : 0; + } + + this.txtIO_DevNum.Text = Util.ReadIniValue(configPath, "DEV", "IOCard_DeviceNum"); + this.txtDefect_Path.Text = Util.ReadIniValue(configPath, "DEV", "Defect_SavePath"); + this.txtDefect_Small_Path.Text = Util.ReadIniValue(configPath, "DEV", "Defect_Small_SavePath"); + this.txtDefect_Compress_SavePath.Text = Util.ReadIniValue(configPath, "DEV", "Defect_Compress_SavePath"); + + //int liTmp = -1; + double ldTmp = -1; + lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_SavePath_AutoClear"); + //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); + ldTmp = Convert.ToDouble(lsTmp); + chkDefect_Path_AutoClear.Checked = (ldTmp > -1); + if (ldTmp > -1) numDefect_Path_AutoClear.Value = (decimal)ldTmp; + lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_Compress_SavePath_AutoClear"); //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); - ldTmp = Convert.ToDouble(lsTmp); - chkDefect_Compress_SavePath_AutoClear.Checked = (ldTmp > -1); - if (ldTmp > -1) numDefect_Compress_SavePath_AutoClear.Value = (decimal)ldTmp; - - lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_Small_SavePath_AutoClear"); - //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); + ldTmp = Convert.ToDouble(lsTmp); + chkDefect_Compress_SavePath_AutoClear.Checked = (ldTmp > -1); + if (ldTmp > -1) numDefect_Compress_SavePath_AutoClear.Value = (decimal)ldTmp; + + lsTmp = Util.ReadIniValue(configPath, "DEV", "Defect_Small_SavePath_AutoClear"); + //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); ldTmp = Convert.ToDouble(lsTmp); chkDefect_Small_Path_AutoClear.Checked = (ldTmp > -1); if (ldTmp > -1) numDefect_Small_Path_AutoClear.Value = (decimal)ldTmp; - - - this.chkSaveAllDefectImg.Checked= (Util.ReadIniValue(configPath, "DEV", "SaveAllDefectImg") == "1"); - this.chkMakeTag.Checked= (Util.ReadIniValue(configPath, "DEV", "MakeTag") == "1"); - this.txtSizeEnginePath.Text= Util.ReadIniValue(configPath, "DEV", "SizeEnginePath"); - - this.txtSizeBmp_SavePath.Text = Util.ReadIniValue(configPath, "DEV", "SizeBmp_SavePath"); - this.txtSizeBmp_Compare_SavePath.Text = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath"); - this.txtSizeBmp_Zoom_Image_SavePath.Text = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath"); - - lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_SavePath_AutoClear"); - //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); + + + this.chkSaveAllDefectImg.Checked= (Util.ReadIniValue(configPath, "DEV", "SaveAllDefectImg") == "1"); + this.chkMakeTag.Checked= (Util.ReadIniValue(configPath, "DEV", "MakeTag") == "1"); + this.txtSizeEnginePath.Text= Util.ReadIniValue(configPath, "DEV", "SizeEnginePath"); + + this.txtSizeBmp_SavePath.Text = Util.ReadIniValue(configPath, "DEV", "SizeBmp_SavePath"); + this.txtSizeBmp_Compare_SavePath.Text = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath"); + this.txtSizeBmp_Zoom_Image_SavePath.Text = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath"); + + lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_SavePath_AutoClear"); + //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); ldTmp = Convert.ToDouble(lsTmp); chkSizeBmp_SavePath_AutoClear.Checked = (ldTmp > -1); - if (ldTmp > -1) numSizeBmp_SavePath_AutoClear.Value = (decimal)ldTmp; - - lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath_AutoClear"); - //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); + if (ldTmp > -1) numSizeBmp_SavePath_AutoClear.Value = (decimal)ldTmp; + + lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath_AutoClear"); + //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); ldTmp = Convert.ToDouble(lsTmp); chkSizeBmp_Compare_SavePath_AutoClear.Checked = (ldTmp > -1); - if (ldTmp > -1) numSizeBmp_Compare_SavePath_AutoClear.Value = (decimal)ldTmp; - + if (ldTmp > -1) numSizeBmp_Compare_SavePath_AutoClear.Value = (decimal)ldTmp; + lsTmp = Util.ReadIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath_AutoClear"); //if (Util.IsNumber(lsTmp)) liTmp = Convert.ToInt32(lsTmp); ldTmp = Convert.ToDouble(lsTmp); chkSizeBmp_Zoom_Image_SavePath_AutoClear.Checked = (ldTmp > -1); - if (ldTmp > -1) numSizeBmp_Zoom_Image_SavePath_AutoClear.Value = (decimal)ldTmp; - //DB - this.txtDBCon.Text = Util.ReadIniValue(configPath, "DB", "DBConStr"); - //HTTP - this.txtLocalIp.Text = Util.ReadIniValue(configPath, "HTTP", "LocalIp"); - lsTmp = Util.ReadIniValue(configPath, "HTTP", "LocalHttpPort"); - if (Util.IsNumber(lsTmp))this.numHttpPort.Value = Convert.ToInt32(lsTmp); - //lsTmp = Util.ReadIniValue(configPath, "HTTP", "LocalSocketPort"); - //if (Util.IsNumber(lsTmp)) this.numSocketPort.Value = Convert.ToInt32(lsTmp); - //LOG - this.txtLogPath.Text = Util.ReadIniValue(configPath, "LOG", "LogPath"); - } - - - private void tsbtnSave_Click(object sender, EventArgs e) - { - try - { - string configPath = Application.StartupPath + "\\SysConfig.ini"; - - //DEV - string lsLight_Name = this.cobLight_Name.Text.Trim(); - if (lsLight_Name == "") - throw new Exception("请选择光源提供商!"); - LightDevNameEnum Light_Name = Utils.EnumUtil.Convert2Enum(lsLight_Name); - string Light_PortNum = this.cobLight_PortNum.Text.Trim(); - string Tension_PortNum = this.cobTension_PortNum.Text.Trim(); - string SmallAxis_ComName = this.cobSmallAxis_ComName.Text.Trim(); - if (Light_PortNum == "" || Tension_PortNum == "" || SmallAxis_ComName == "") - throw new Exception("请设置设备COM端口!"); - - string HeightDev_IP = this.txtHeightDev_IP.Text; - int HeightDev_Port = (int)this.numHeightDev_Port.Value; - if(HeightDev_IP=="") - throw new Exception("请设置厚度检测设备IP地址!"); - decimal HeightDev_SafeValue=this.numHeightDev_SafeValue.Value; - - string IOCard_DeviceNum = this.txtIO_DevNum.Text.Trim(); - if (IOCard_DeviceNum == "") - throw new Exception("请设置I/O设备编号 !"); - - string Defect_SavePath = this.txtDefect_Path.Text.Trim(); - if (Defect_SavePath == "") - throw new Exception("请设置缺陷大图保存路径 !"); - string Defect_Compress_SavePath = this.txtDefect_Compress_SavePath.Text.Trim(); - if (Defect_Compress_SavePath == "") - throw new Exception("请设置缺陷压缩大图保存路径 !"); - string Defect_Small_SavePath = this.txtDefect_Small_Path.Text.Trim(); - //if (Defect_Small_SavePath == "") - // throw new Exception("请设置缺陷小图保存路径 !"); - - //DB - string DBConStr = this.txtDBCon.Text.Trim(); - if (DBConStr == "") - throw new Exception("请设置DB连接字符串 !"); - //LOG - string LogPath = this.txtLogPath.Text.Trim(); - if (LogPath == "") - throw new Exception("请设置日志保存路径 !"); - - //最后统一保存 - //Skip - Util.WriteIniValue(configPath, "SKIP", "SkipAxis0", this.chkSkipAxis0.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipAxis1", this.chkSkipAxis1.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipAxis2", this.chkSkipAxis2.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipAxis3", this.chkSkipAxis3.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipTension", this.chkSkipTension.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipHeight", this.chkSkipHeight.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipLight", this.chkSkipLight.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipScannerGL", this.chkSkipScannerGL.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipScannerCC", this.chkSkipScannerCC.Checked ? "1" : "0"); - Util.WriteIniValue(configPath, "SKIP", "SkipSmallAxis", this.chkSkipSmallAxis.Checked ? "1" : "0"); - - Util.WriteIniValue(configPath, "SKIP", "MarkErrorStop", this.ckSkipSizeFailed.Checked ? "1" : "0"); - - //DEV - Utils.Util.WriteIniValue(configPath, "DEV", "Axis0_PulseOutMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis0PulseOutMode)).ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis1_PulseOutMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis1PulseOutMode)).ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis2_PulseOutMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis2PulseOutMode)).ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis3_PulseOutMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis3PulseOutMode)).ToString()); - - Utils.Util.WriteIniValue(configPath, "DEV", "Axis0_HomeMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis0HomeMode)).ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis1_HomeMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis1HomeMode)).ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis2_HomeMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis2HomeMode)).ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis3_HomeMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis3HomeMode)).ToString()); - - Utils.Util.WriteIniValue(configPath, "DEV", "Axis0_HomeDir", this.cobAxis0HomeDir.SelectedIndex.ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis1_HomeDir", this.cobAxis1HomeDir.SelectedIndex.ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis2_HomeDir", this.cobAxis2HomeDir.SelectedIndex.ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "Axis3_HomeDir", this.cobAxis3HomeDir.SelectedIndex.ToString()); - - JArray HeightDev_BaseList = new JArray() - { - numHeightBase0.Value,numHeightBase1.Value,numHeightBase2.Value,numHeightBase3.Value,numHeightBase4.Value - }; - Utils.Util.WriteIniValue(configPath, "DEV", "HeightDev_BaseList", HeightDev_BaseList.ToString().Replace("\r\n", "")); - - - Utils.Util.WriteIniValue(configPath, "DEV", "Light_Name", ""+(int)Light_Name); - Utils.Util.WriteIniValue(configPath, "DEV", "Light_PortNum", Light_PortNum.Substring(3)); - Utils.Util.WriteIniValue(configPath, "DEV", "Tension_PortNum", Tension_PortNum.Substring(3)); - Utils.Util.WriteIniValue(configPath, "DEV", "SmallAxis_ComName", SmallAxis_ComName); - - Utils.Util.WriteIniValue(configPath, "DEV", "HeightDev_IP", HeightDev_IP); - Utils.Util.WriteIniValue(configPath, "DEV", "HeightDev_Port", HeightDev_Port.ToString()); - Utils.Util.WriteIniValue(configPath, "DEV", "HeightDev_SafeValue", HeightDev_SafeValue.ToString()); - JArray Axis_HomeVelLow = new JArray() - { - numAxis0HomeVelLow.Value,numAxis1HomeVelLow.Value,numAxis2HomeVelLow.Value,numAxis3HomeVelLow.Value - }; - Utils.Util.WriteIniValue(configPath, "DEV", "Axis_HomeVelLow", Axis_HomeVelLow.ToString().Replace("\r\n","")); - - JArray Axis_HomeVelHigh = new JArray() - { - numAxis0HomeVelHigh.Value,numAxis1HomeVelHigh.Value,numAxis2HomeVelHigh.Value,numAxis3HomeVelHigh.Value - }; - Utils.Util.WriteIniValue(configPath, "DEV", "Axis_HomeVelHigh", Axis_HomeVelHigh.ToString().Replace("\r\n", "")); - - JArray Axis_HomeAcc = new JArray() - { - numAxis0HomeAcc.Value,numAxis1HomeAcc.Value,numAxis2HomeAcc.Value,numAxis3HomeAcc.Value - }; - Utils.Util.WriteIniValue(configPath, "DEV", "Axis_HomeAcc", Axis_HomeAcc.ToString().Replace("\r\n", "")); - - JArray Axis_HomeDec = new JArray() - { - numAxis0HomeDec.Value,numAxis1HomeDec.Value,numAxis2HomeDec.Value,numAxis3HomeDec.Value - }; - Utils.Util.WriteIniValue(configPath, "DEV", "Axis_HomeDec", Axis_HomeDec.ToString().Replace("\r\n", "")); - - Utils.Util.WriteIniValue(configPath, "DEV", "IOCard_DeviceNum", IOCard_DeviceNum); - - Utils.Util.WriteIniValue(configPath, "DEV", "Defect_SavePath", Defect_SavePath); - Utils.Util.WriteIniValue(configPath, "DEV", "Defect_SavePath_AutoClear", (chkDefect_Path_AutoClear.Checked ? (double)numDefect_Path_AutoClear.Value : -1)+""); - Utils.Util.WriteIniValue(configPath, "DEV", "Defect_Compress_SavePath", Defect_Compress_SavePath); - Utils.Util.WriteIniValue(configPath, "DEV", "Defect_Compress_SavePath_AutoClear", (chkDefect_Compress_SavePath_AutoClear.Checked ? (double)numDefect_Compress_SavePath_AutoClear.Value : -1) + ""); - Utils.Util.WriteIniValue(configPath, "DEV", "Defect_Small_SavePath", Defect_Small_SavePath); - Utils.Util.WriteIniValue(configPath, "DEV", "Defect_Small_SavePath_AutoClear", (chkDefect_Small_Path_AutoClear.Checked ? (double)numDefect_Small_Path_AutoClear.Value : -1) + ""); - - Utils.Util.WriteIniValue(configPath, "DEV", "SaveAllDefectImg", this.chkSaveAllDefectImg.Checked ? "1" : "0"); - Utils.Util.WriteIniValue(configPath, "DEV", "MakeTag", this.chkMakeTag.Checked ? "1" : "0"); - Utils.Util.WriteIniValue(configPath, "DEV", "SizeEnginePath", this.txtSizeEnginePath.Text.Trim()); - Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_SavePath", this.txtSizeBmp_SavePath.Text.Trim()); - Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_SavePath_AutoClear", (chkSizeBmp_SavePath_AutoClear.Checked ? (double)numSizeBmp_SavePath_AutoClear.Value : -1) + ""); - Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath", this.txtSizeBmp_Compare_SavePath.Text.Trim()); - Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath_AutoClear", (chkSizeBmp_Compare_SavePath_AutoClear.Checked ? (double)numSizeBmp_Compare_SavePath_AutoClear.Value : -1) + ""); - Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath", this.txtSizeBmp_Zoom_Image_SavePath.Text.Trim()); - Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath_AutoClear", (chkSizeBmp_Zoom_Image_SavePath_AutoClear.Checked ? (double)numSizeBmp_Zoom_Image_SavePath_AutoClear.Value : -1) + ""); - //DB - Utils.Util.WriteIniValue(configPath, "DB", "DBConStr", DBConStr); - //HTTP - Utils.Util.WriteIniValue(configPath, "HTTP", "LocalIp",this.txtLocalIp.Text.Trim()); - Utils.Util.WriteIniValue(configPath, "HTTP", "LocalHttpPort", this.numHttpPort.Value.ToString()); - //LOG - Utils.Util.WriteIniValue(configPath, "LOG", "LogPath", LogPath); - - // - this.Hide(); - MessageBox.Show("保存成功,生效需重启程序!"); - this.Close(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void tsbtnClose_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void txtDefect_Path_Click(object sender, EventArgs e) - { - string path = FileUtil.selectFolder(Application.StartupPath); - if (!string.IsNullOrWhiteSpace(path)) - this.txtDefect_Path.Text = path; - } - - - private void txtLogPath_Click(object sender, EventArgs e) - { - string path = FileUtil.selectFolder(Application.StartupPath); - if (!string.IsNullOrWhiteSpace(path)) - this.txtLogPath.Text = path; - } - private void txtSizeEnginePath_Click(object sender, EventArgs e) - { - string path = FileUtil.selectFolder(Application.StartupPath); - if (!string.IsNullOrWhiteSpace(path)) - this.txtSizeEnginePath.Text = path; - } - - private void txtSizeBmp_Path_Click(object sender, EventArgs e) - { - string path = FileUtil.selectFolder(Application.StartupPath); - if (!string.IsNullOrWhiteSpace(path)) - this.txtSizeBmp_SavePath.Text = path; - } - private void txtSizeBmp_Compare_SavePath_Click(object sender, EventArgs e) - { - string path = FileUtil.selectFolder(Application.StartupPath); - if (!string.IsNullOrWhiteSpace(path)) - this.txtSizeBmp_Compare_SavePath.Text = path; - } - private void txtSizeBmp_Zoom_Image_SavePath_Click(object sender, EventArgs e) - { - string path = FileUtil.selectFolder(Application.StartupPath); - if (!string.IsNullOrWhiteSpace(path)) - this.txtSizeBmp_Zoom_Image_SavePath.Text = path; - } - private void txtDefect_Small_Path_Click(object sender, EventArgs e) - { - string path = FileUtil.selectFolder(Application.StartupPath); - if (!string.IsNullOrWhiteSpace(path)) - this.txtDefect_Small_Path.Text = path; - } - private void txtDefect_Compress_SavePath_Click(object sender, EventArgs e) - { - string path = FileUtil.selectFolder(Application.StartupPath); - if (!string.IsNullOrWhiteSpace(path)) - this.txtDefect_Compress_SavePath.Text = path; - } - - private void btnClearDefect_Small_Path_Click(object sender, EventArgs e) - { - this.txtDefect_Small_Path.Text = ""; - } - - private void btnClearDefect_Path_Click(object sender, EventArgs e) - { - this.txtDefect_Path.Text = ""; - } - - private void btnClearDefect_Compress_SavePath_Click(object sender, EventArgs e) - { - txtDefect_Compress_SavePath.Text = ""; - } - - private void btnClearSizeBmp_Path_Click(object sender, EventArgs e) - { - txtSizeBmp_SavePath.Text = ""; - } - - private void btnClearSizeBmp_Compare_SavePath_Click(object sender, EventArgs e) - { - txtSizeBmp_Compare_SavePath.Text = ""; - } - private void btnSizeBmp_Zoom_Image_SavePath_Click(object sender, EventArgs e) - { - txtSizeBmp_Zoom_Image_SavePath.Text = ""; - } - private void btnBackDB_Click(object sender, EventArgs e) - { - try - { - string lsPath=Utils.FileUtil.selectFolder(); - if (string.IsNullOrWhiteSpace(lsPath)) - return; - - lsPath += "\\DB" + DateTime.Now.ToString("yyyyMMddHHmm") + ".bak"; - Service.InitDB.BackupDataBase(lsPath); - MessageBox.Show("备份成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void chkMakeTag_CheckedChanged(object sender, EventArgs e) - { - - } - } -} + if (ldTmp > -1) numSizeBmp_Zoom_Image_SavePath_AutoClear.Value = (decimal)ldTmp; + //DB + this.txtDBCon.Text = Util.ReadIniValue(configPath, "DB", "DBConStr"); + //HTTP + this.txtLocalIp.Text = Util.ReadIniValue(configPath, "HTTP", "LocalIp"); + lsTmp = Util.ReadIniValue(configPath, "HTTP", "LocalHttpPort"); + if (Util.IsNumber(lsTmp))this.numHttpPort.Value = Convert.ToInt32(lsTmp); + //lsTmp = Util.ReadIniValue(configPath, "HTTP", "LocalSocketPort"); + //if (Util.IsNumber(lsTmp)) this.numSocketPort.Value = Convert.ToInt32(lsTmp); + //LOG + this.txtLogPath.Text = Util.ReadIniValue(configPath, "LOG", "LogPath"); + } + + + private void tsbtnSave_Click(object sender, EventArgs e) + { + try + { + string configPath = Application.StartupPath + "\\SysConfig.ini"; + + //DEV + string lsLight_Name = this.cobLight_Name.Text.Trim(); + if (lsLight_Name == "") + throw new Exception("请选择光源提供商!"); + LightDevNameEnum Light_Name = Utils.EnumUtil.Convert2Enum(lsLight_Name); + string Light_PortNum = this.cobLight_PortNum.Text.Trim(); + string Tension_PortNum = this.cobTension_PortNum.Text.Trim(); + decimal Tension_Offset = this.numOffset.Value; + string SmallAxis_ComName = this.cobSmallAxis_ComName.Text.Trim(); + if (Light_PortNum == "" || Tension_PortNum == "" || SmallAxis_ComName == "") + throw new Exception("请设置设备COM端口!"); + + string HeightDev_IP = this.txtHeightDev_IP.Text; + int HeightDev_Port = (int)this.numHeightDev_Port.Value; + if(HeightDev_IP=="") + throw new Exception("请设置厚度检测设备IP地址!"); + decimal HeightDev_SafeValue=this.numHeightDev_SafeValue.Value; + + string IOCard_DeviceNum = this.txtIO_DevNum.Text.Trim(); + if (IOCard_DeviceNum == "") + throw new Exception("请设置I/O设备编号 !"); + + string Defect_SavePath = this.txtDefect_Path.Text.Trim(); + if (Defect_SavePath == "") + throw new Exception("请设置缺陷大图保存路径 !"); + string Defect_Compress_SavePath = this.txtDefect_Compress_SavePath.Text.Trim(); + if (Defect_Compress_SavePath == "") + throw new Exception("请设置缺陷压缩大图保存路径 !"); + string Defect_Small_SavePath = this.txtDefect_Small_Path.Text.Trim(); + //if (Defect_Small_SavePath == "") + // throw new Exception("请设置缺陷小图保存路径 !"); + + //DB + string DBConStr = this.txtDBCon.Text.Trim(); + if (DBConStr == "") + throw new Exception("请设置DB连接字符串 !"); + //LOG + string LogPath = this.txtLogPath.Text.Trim(); + if (LogPath == "") + throw new Exception("请设置日志保存路径 !"); + + //最后统一保存 + //Skip + Util.WriteIniValue(configPath, "SKIP", "SkipAxis0", this.chkSkipAxis0.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipAxis1", this.chkSkipAxis1.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipAxis2", this.chkSkipAxis2.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipAxis3", this.chkSkipAxis3.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipTension", this.chkSkipTension.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipHeight", this.chkSkipHeight.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipLight", this.chkSkipLight.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipScannerGL", this.chkSkipScannerGL.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipScannerCC", this.chkSkipScannerCC.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "SkipSmallAxis", this.chkSkipSmallAxis.Checked ? "1" : "0"); + + Util.WriteIniValue(configPath, "SKIP", "MarkErrorStop", this.ckSkipSizeFailed.Checked ? "1" : "0"); + Util.WriteIniValue(configPath, "SKIP", "OpenFlawDistribution", this.cbOpenFlawDistribution.Checked ? "1" : "0"); + //DEV + Utils.Util.WriteIniValue(configPath, "DEV", "Axis0_PulseOutMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis0PulseOutMode)).ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis1_PulseOutMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis1PulseOutMode)).ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis2_PulseOutMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis2PulseOutMode)).ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis3_PulseOutMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis3PulseOutMode)).ToString()); + + Utils.Util.WriteIniValue(configPath, "DEV", "Axis0_HomeMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis0HomeMode)).ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis1_HomeMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis1HomeMode)).ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis2_HomeMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis2HomeMode)).ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis3_HomeMode", ((int)EnumUtil.GetSelectedItemToEnum(this.cobAxis3HomeMode)).ToString()); + + Utils.Util.WriteIniValue(configPath, "DEV", "Axis0_HomeDir", this.cobAxis0HomeDir.SelectedIndex.ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis1_HomeDir", this.cobAxis1HomeDir.SelectedIndex.ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis2_HomeDir", this.cobAxis2HomeDir.SelectedIndex.ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "Axis3_HomeDir", this.cobAxis3HomeDir.SelectedIndex.ToString()); + + JArray HeightDev_BaseList = new JArray() + { + numHeightBase0.Value,numHeightBase1.Value,numHeightBase2.Value,numHeightBase3.Value,numHeightBase4.Value + }; + Utils.Util.WriteIniValue(configPath, "DEV", "HeightDev_BaseList", HeightDev_BaseList.ToString().Replace("\r\n", "")); + + + Utils.Util.WriteIniValue(configPath, "DEV", "Light_Name", ""+(int)Light_Name); + Utils.Util.WriteIniValue(configPath, "DEV", "Light_PortNum", Light_PortNum.Substring(3)); + Utils.Util.WriteIniValue(configPath, "DEV", "Tension_PortNum", Tension_PortNum.Substring(3)); + Utils.Util.WriteIniValue(configPath, "DEV", "Tension_Offset", Tension_Offset.ToString()); + + Utils.Util.WriteIniValue(configPath, "DEV", "SmallAxis_ComName", SmallAxis_ComName); + + Utils.Util.WriteIniValue(configPath, "DEV", "HeightDev_IP", HeightDev_IP); + Utils.Util.WriteIniValue(configPath, "DEV", "HeightDev_Port", HeightDev_Port.ToString()); + Utils.Util.WriteIniValue(configPath, "DEV", "HeightDev_SafeValue", HeightDev_SafeValue.ToString()); + JArray Axis_HomeVelLow = new JArray() + { + numAxis0HomeVelLow.Value,numAxis1HomeVelLow.Value,numAxis2HomeVelLow.Value,numAxis3HomeVelLow.Value + }; + Utils.Util.WriteIniValue(configPath, "DEV", "Axis_HomeVelLow", Axis_HomeVelLow.ToString().Replace("\r\n","")); + + JArray Axis_HomeVelHigh = new JArray() + { + numAxis0HomeVelHigh.Value,numAxis1HomeVelHigh.Value,numAxis2HomeVelHigh.Value,numAxis3HomeVelHigh.Value + }; + Utils.Util.WriteIniValue(configPath, "DEV", "Axis_HomeVelHigh", Axis_HomeVelHigh.ToString().Replace("\r\n", "")); + + JArray Axis_HomeAcc = new JArray() + { + numAxis0HomeAcc.Value,numAxis1HomeAcc.Value,numAxis2HomeAcc.Value,numAxis3HomeAcc.Value + }; + Utils.Util.WriteIniValue(configPath, "DEV", "Axis_HomeAcc", Axis_HomeAcc.ToString().Replace("\r\n", "")); + + JArray Axis_HomeDec = new JArray() + { + numAxis0HomeDec.Value,numAxis1HomeDec.Value,numAxis2HomeDec.Value,numAxis3HomeDec.Value + }; + Utils.Util.WriteIniValue(configPath, "DEV", "Axis_HomeDec", Axis_HomeDec.ToString().Replace("\r\n", "")); + + Utils.Util.WriteIniValue(configPath, "DEV", "IOCard_DeviceNum", IOCard_DeviceNum); + + Utils.Util.WriteIniValue(configPath, "DEV", "Defect_SavePath", Defect_SavePath); + Utils.Util.WriteIniValue(configPath, "DEV", "Defect_SavePath_AutoClear", (chkDefect_Path_AutoClear.Checked ? (double)numDefect_Path_AutoClear.Value : -1)+""); + Utils.Util.WriteIniValue(configPath, "DEV", "Defect_Compress_SavePath", Defect_Compress_SavePath); + Utils.Util.WriteIniValue(configPath, "DEV", "Defect_Compress_SavePath_AutoClear", (chkDefect_Compress_SavePath_AutoClear.Checked ? (double)numDefect_Compress_SavePath_AutoClear.Value : -1) + ""); + Utils.Util.WriteIniValue(configPath, "DEV", "Defect_Small_SavePath", Defect_Small_SavePath); + Utils.Util.WriteIniValue(configPath, "DEV", "Defect_Small_SavePath_AutoClear", (chkDefect_Small_Path_AutoClear.Checked ? (double)numDefect_Small_Path_AutoClear.Value : -1) + ""); + + Utils.Util.WriteIniValue(configPath, "DEV", "SaveAllDefectImg", this.chkSaveAllDefectImg.Checked ? "1" : "0"); + Utils.Util.WriteIniValue(configPath, "DEV", "MakeTag", this.chkMakeTag.Checked ? "1" : "0"); + Utils.Util.WriteIniValue(configPath, "DEV", "SizeEnginePath", this.txtSizeEnginePath.Text.Trim()); + Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_SavePath", this.txtSizeBmp_SavePath.Text.Trim()); + Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_SavePath_AutoClear", (chkSizeBmp_SavePath_AutoClear.Checked ? (double)numSizeBmp_SavePath_AutoClear.Value : -1) + ""); + Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath", this.txtSizeBmp_Compare_SavePath.Text.Trim()); + Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_Compare_SavePath_AutoClear", (chkSizeBmp_Compare_SavePath_AutoClear.Checked ? (double)numSizeBmp_Compare_SavePath_AutoClear.Value : -1) + ""); + Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath", this.txtSizeBmp_Zoom_Image_SavePath.Text.Trim()); + Utils.Util.WriteIniValue(configPath, "DEV", "SizeBmp_Zoom_Image_SavePath_AutoClear", (chkSizeBmp_Zoom_Image_SavePath_AutoClear.Checked ? (double)numSizeBmp_Zoom_Image_SavePath_AutoClear.Value : -1) + ""); + //DB + Utils.Util.WriteIniValue(configPath, "DB", "DBConStr", DBConStr); + //HTTP + Utils.Util.WriteIniValue(configPath, "HTTP", "LocalIp",this.txtLocalIp.Text.Trim()); + Utils.Util.WriteIniValue(configPath, "HTTP", "LocalHttpPort", this.numHttpPort.Value.ToString()); + //LOG + Utils.Util.WriteIniValue(configPath, "LOG", "LogPath", LogPath); + + + // + this.Hide(); + MessageBox.Show("保存成功,生效需重启程序!"); + this.Close(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void tsbtnClose_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void txtDefect_Path_Click(object sender, EventArgs e) + { + string path = FileUtil.selectFolder(Application.StartupPath); + if (!string.IsNullOrWhiteSpace(path)) + this.txtDefect_Path.Text = path; + } + + + private void txtLogPath_Click(object sender, EventArgs e) + { + string path = FileUtil.selectFolder(Application.StartupPath); + if (!string.IsNullOrWhiteSpace(path)) + this.txtLogPath.Text = path; + } + private void txtSizeEnginePath_Click(object sender, EventArgs e) + { + string path = FileUtil.selectFolder(Application.StartupPath); + if (!string.IsNullOrWhiteSpace(path)) + this.txtSizeEnginePath.Text = path; + } + + private void txtSizeBmp_Path_Click(object sender, EventArgs e) + { + string path = FileUtil.selectFolder(Application.StartupPath); + if (!string.IsNullOrWhiteSpace(path)) + this.txtSizeBmp_SavePath.Text = path; + } + private void txtSizeBmp_Compare_SavePath_Click(object sender, EventArgs e) + { + string path = FileUtil.selectFolder(Application.StartupPath); + if (!string.IsNullOrWhiteSpace(path)) + this.txtSizeBmp_Compare_SavePath.Text = path; + } + private void txtSizeBmp_Zoom_Image_SavePath_Click(object sender, EventArgs e) + { + string path = FileUtil.selectFolder(Application.StartupPath); + if (!string.IsNullOrWhiteSpace(path)) + this.txtSizeBmp_Zoom_Image_SavePath.Text = path; + } + private void txtDefect_Small_Path_Click(object sender, EventArgs e) + { + string path = FileUtil.selectFolder(Application.StartupPath); + if (!string.IsNullOrWhiteSpace(path)) + this.txtDefect_Small_Path.Text = path; + } + private void txtDefect_Compress_SavePath_Click(object sender, EventArgs e) + { + string path = FileUtil.selectFolder(Application.StartupPath); + if (!string.IsNullOrWhiteSpace(path)) + this.txtDefect_Compress_SavePath.Text = path; + } + + private void btnClearDefect_Small_Path_Click(object sender, EventArgs e) + { + this.txtDefect_Small_Path.Text = ""; + } + + private void btnClearDefect_Path_Click(object sender, EventArgs e) + { + this.txtDefect_Path.Text = ""; + } + + private void btnClearDefect_Compress_SavePath_Click(object sender, EventArgs e) + { + txtDefect_Compress_SavePath.Text = ""; + } + + private void btnClearSizeBmp_Path_Click(object sender, EventArgs e) + { + txtSizeBmp_SavePath.Text = ""; + } + + private void btnClearSizeBmp_Compare_SavePath_Click(object sender, EventArgs e) + { + txtSizeBmp_Compare_SavePath.Text = ""; + } + private void btnSizeBmp_Zoom_Image_SavePath_Click(object sender, EventArgs e) + { + txtSizeBmp_Zoom_Image_SavePath.Text = ""; + } + private void btnBackDB_Click(object sender, EventArgs e) + { + try + { + string lsPath=Utils.FileUtil.selectFolder(); + if (string.IsNullOrWhiteSpace(lsPath)) + return; + + lsPath += "\\DB" + DateTime.Now.ToString("yyyyMMddHHmm") + ".bak"; + Service.InitDB.BackupDataBase(lsPath); + MessageBox.Show("备份成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void chkMakeTag_CheckedChanged(object sender, EventArgs e) + { + + } + } +} diff --git a/halftoneproject-master/Code/FrmSysSetting.resx b/halftoneproject-master/Code/FrmSysSetting.resx index f4d68e5..0aadc95 100644 --- a/halftoneproject-master/Code/FrmSysSetting.resx +++ b/halftoneproject-master/Code/FrmSysSetting.resx @@ -124,16 +124,16 @@ iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAIeSURBVFhH7ZfLShxBFIaPCJKAQcgLhBh0I7hTSYi6CVEX - Lmchoq1dVd112rgQ3yC7oBslD+CNJBDIC7gTXXoBFy7dSdaRYELI5VRR09Pl1Mx09TQBwR8+eqaqzt// - VJ/umYF7OdQBUTJGTBaGywngyYDx81Cl0gUs3geBf0uB41vjnFMCh+pM2ueVcc8hLkfTQoaX9Al2QMS7 - /shtCPFC+yzgFURRjzlDC0XJyzQAxy0zWkxcvku9hPxsRlsoG0DID2a0mITcrHlpv8DMNFE2AMOPZjS/ - GC7SzkX6NccNK8AMfocweaLnGqqdACsrD6nuj65V4rieelUJ4yOa6dDzTrUTIAwfUd034ka/53It9bKQ - q3reKasHcM+M5lOSdMPU9G9dq2Q1ocUXPe+UHaDJwgbSt61pXoHvM141mu6sHUBt5wsz4yeGg1T7NeNV - wyOAQjXVOXFCD5jT1tA6jmcQBL9MfT2eAcrnbgYIgutCVO+KLF4BlImQU8DY40LEcR/5HFqefjtAjdWu - BCaWp+cl+EldvQwiGfGGxcPkN5l+LVe5m01YJp4BbugSzANf6tcNpY55Ueuj6DkweWx5/v8mlGh5eu+A - kHMgxDNYxF59vI0ad8HfPKV6+pGrH9E5A2R/lNqo7wQ/XA8hjfxkzuaQunWcRWXSLEAQPKBFB/VFJTE7 - +4N2ecKcrYEqlU5aPE794P7bVRSBr3Vf3MsSwD8RV2WjuxFNUgAAAABJRU5ErkJggg== + YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAIfSURBVFhH7ZdPaxNBGMbfUBCFSsEvILa0l4K3KoptL9JE + es6hhLpmZ2Z33q09hH4Db6IXpR+gtUULBb+AN6lHW8GDR2/iWZEo4p93hslmp5kkO5ulEOgDPzaZmffZ + J7PvbhI4l0MViJIlolYYLqvAk3nj56F6/QKw+A0I/FcKHB8Z55wSuNBjMjp3jXsOcbmYFjL8TJ/gBYh4 + zx+5CyF+0j4P8AtE0ZQ5wxBFyZ00AMcdM1pMXD5OvYQ8NKNDlA0g5EszWkxCPu96ab/AzAxQNgDDV2Y0 + vxg2aeci/ZrjMyvAGv6AMLmq5/pqlACt1iWq+6trlTg+Tb06hPE7mqnoeadGCRCGl6nuG9HW77l8knpZ + yC0975TVA7hvRvMpSSahuvpH1ypZTWjxWs87ZQcYsLCP9G1rmlfgdsary8CdtQOo7bxtZvzE8DrVfs14 + dfEIoFBN9ZE4pgfMyXBoHccPEAS/TX0vngHKZzwDBMH3QnTuiixeAZSJkPeAsSuFiONZ8jmyPP12gBpr + VAlMLE/PS/CLunoTRHLTGxbfIL9a+rXcYTybsEw8A7TpEtwHvjGnG0od86LWR9EtYPK95Xn2TSjR8vTe + ASHXQYgZaOK0Pp5GjbvgD69RPf3I1Y/onAGyP0pt1HeCH66HkEYemLM5pG4dZ1GZDAoQBBdp0dveopJo + NH7SLlfN2fqoXp+gxcvUD+6/XUURuKL74lyWAP4DwL5ll9fZEiMAAAAASUVORK5CYII= @@ -257,9 +257,6 @@ 166, 17 - - 166, 17 - 56 diff --git a/halftoneproject-master/Code/Properties/AssemblyInfo.cs b/halftoneproject-master/Code/Properties/AssemblyInfo.cs index 8376f2e..18d250b 100644 --- a/halftoneproject-master/Code/Properties/AssemblyInfo.cs +++ b/halftoneproject-master/Code/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 //通过使用 "*",如下所示: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0.0")] -[assembly: AssemblyFileVersion("1.2.0.0")] +[assembly: AssemblyVersion("1.2.1.0")] +[assembly: AssemblyFileVersion("1.2.1.0")] diff --git a/halftoneproject-master/Models/Order.cs b/halftoneproject-master/Models/Order.cs index 5fa10dc..a06b44d 100644 --- a/halftoneproject-master/Models/Order.cs +++ b/halftoneproject-master/Models/Order.cs @@ -1,222 +1,224 @@ -using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Models -{ - [SugarIndex("index_{table}_sn", nameof(Order.SN), OrderByType.Asc, isUnique: true)] - public class Order : BaseTable - { - /// - /// 产品 - /// - public int ProductId { get; set; } - [Navigate(NavigateType.ManyToOne, nameof(ProductId))] - public Product ProductInfo { get; set; } - - public string SN { get; set; } - public string BatchId { get; set; } - /// - /// 流程 - /// - public int StepId { get; set; } - [Navigate(NavigateType.ManyToOne, nameof(StepId))] - public Step StepInfo { get; set; } - - /// - /// 时长-秒 - /// - public double TimeLen { get; set; } - /// - /// 是否合格 - /// - [SugarColumn(IsNullable = true)] - public bool Qualified { get; set; } = true; - - /// - /// 比对结果 0-未比对 1-通过 2-不通过 - /// - public int CompareResult { get; set; } = 0; - - - //平均值 - public double TensionValue { get; set; } - public double HeightValue { get; set; } - public double LineWidthValue { get; set; } - public double PTValue { get; set; } - - //N次 - #region 张力5次 - public double Tension1 { get; set; } - public double Tension2 { get; set; } - public double Tension3 { get; set; } - public double Tension4 { get; set; } - public double Tension5 { get; set; } - #endregion - #region 厚度5次 - public double Height1 { get; set; } - public double Height2 { get; set; } - public double Height3 { get; set; } - public double Height4 { get; set; } - public double Height5 { get; set; } - #endregion - #region 线宽9次 - public double LineWidth1 { get; set; } - public double LineWidth2 { get; set; } - public double LineWidth3 { get; set; } - public double LineWidth4 { get; set; } - public double LineWidth5 { get; set; } - public double LineWidth6 { get; set; } - public double LineWidth7 { get; set; } - public double LineWidth8 { get; set; } - public double LineWidth9 { get; set; } - #endregion - #region PT6次 - public double PT1 { get; set; } - public double PT2 { get; set; } - public double PT3 { get; set; } - public double PT4 { get; set; } - public double PT5 { get; set; } - public double PT6 { get; set; } - #endregion - /// - /// 缺陷数 - /// - public int DefectCount { get; set; } - - #region 缺陷种类 - public int DKCount { get; set; }//堵孔数量 - public int ZWCount { get; set; }//脏污数量 - public int GSYCCount { get; set; }//钢丝异常数量 - public int XWSCount { get; set; }//纤维丝数量 - public int QKCount { get; set; }//缺口数量 - public int ZKCount { get; set; }//针孔数量 - public int PPCount { get; set; }//泡泡数量 - public int HSCount { get; set; }//划伤数量 - public int YXCount { get; set; }//压线数量 - public int XBCount { get; set; }//斜边数量 new - public int SXCount { get; set; }//栅线数量 new - #endregion - - /// - /// mark点数据:[X1,Y1,X2,Y2,X3,Y3,X4,Y4] - /// - [SugarColumn(IsNullable = true)] - public string MarkData { get; set; } - // - public bool Succeed { get; set; } - /// - /// 失败分类 - /// - public int FailType { get; set; } - /// - /// 失败的工序名称 - /// - [SugarColumn(IsNullable = true)] - public string FailProcessName { get; set; } - [SugarColumn(IsNullable = true, ColumnDataType = "text", Length = 2048)] - public string Note { get; set; } - - /// - /// 0-初始; 5-已检测; 10-出现异常 - /// - public int State { get; set; } - - //---------- - /// - /// 修改次数 - /// - public int HistoryCount { get; set; } = 0; - /// - /// 修改历史记录 - /// - [Navigate(NavigateType.OneToMany, nameof(OrderHistory.Pid))] - public List OrderHistoryList { get; set; } - - /// - /// Defect和Size比对失败的坐标位置 - /// - [Navigate(NavigateType.OneToMany, nameof(DefectInfo.Pid))] - public List DefectInfoList { get; set; } - - //-------IsIgnore = true 不保存 - [SugarColumn(IsIgnore = true)] - //[Navigate(NavigateType.OneToMany, nameof(SizeTagData.Pid))] - public List SizeTagDataList { get; set; } - - //2023-10-30 添加异常列 - /// - /// 异常情况 - /// - public string Abnormalities { get; set; } - /// - /// 修复人员 - /// - public string RepairCode { get; set; } - } - [SugarIndex("index_{table}_pid", nameof(OrderHistory.Pid), OrderByType.Asc, isUnique: false)] - public class OrderHistory : BaseTable - { - public int Pid { get; set; } - public bool Qualified { get; set; }//合格 - - //比对 - public int CompareResult { get; set; } - //平均值 - public double TensionValue { get; set; } - public double HeightValue { get; set; } - public double LineWidthValue { get; set; } - public double PTValue { get; set; } - - //外观 - public int DKCount { get; set; }//堵孔数量 - public int ZWCount { get; set; }//脏污数量 - public int GSYCCount { get; set; }//钢丝异常数量 - public int XWSCount { get; set; }//纤维丝数量 - public int QKCount { get; set; }//缺口数量 - public int ZKCount { get; set; }//针孔数量 - public int PPCount { get; set; }//泡泡数量 - public int HSCount { get; set; }//划伤数量 - public int YXCount { get; set; }//压线数量 - public int XBCount { get; set; }//斜边数量 new - public int SXCount { get; set; }//栅线数量 new - } - - [SugarIndex("index_{table}_pid", nameof(SizeTagData.Pid), OrderByType.Asc, isUnique: false)] - public class SizeTagData : BaseTable - { - public int Pid { get; set; } - public string SizeTag { get; set; } - /// - /// 产生Tag工序索引 - /// - public int CreateStepIndex { get; set; } - /// - /// 消费本数据工序索引和消费值索引:5-0,8-2 - /// - public string ConsumeStepIndex { get; set; } - - /// - /// double[] - /// - public string posePT { get; set; } - } - - [SugarIndex("index_{table}_pid", nameof(DefectInfo.Pid), OrderByType.Asc, isUnique: false)] - public class DefectInfo : BaseTable - { - public int Pid { get; set; } - /// - /// 0-Defect 1-Size - /// - public int Type { get; set; } - public string Code { get;set; } - - public double X { get; set; } - public double Y { get; set; } - public double ZXD { get; set; } - } +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Models +{ + [SugarIndex("index_{table}_sn", nameof(Order.SN), OrderByType.Asc, isUnique: true)] + public class Order : BaseTable + { + /// + /// 产品 + /// + public int ProductId { get; set; } + [Navigate(NavigateType.ManyToOne, nameof(ProductId))] + public Product ProductInfo { get; set; } + + public string SN { get; set; } + public string BatchId { get; set; } + /// + /// 流程 + /// + public int StepId { get; set; } + [Navigate(NavigateType.ManyToOne, nameof(StepId))] + public Step StepInfo { get; set; } + + /// + /// 时长-秒 + /// + public double TimeLen { get; set; } + /// + /// 是否合格 + /// + [SugarColumn(IsNullable = true)] + public bool Qualified { get; set; } = true; + + /// + /// 比对结果 0-未比对 1-通过 2-不通过 + /// + public int CompareResult { get; set; } = 0; + + + //平均值 + public double TensionValue { get; set; } + public double HeightValue { get; set; } + public double LineWidthValue { get; set; } + public double PTValue { get; set; } + + //N次 + #region 张力5次 + public double Tension1 { get; set; } + public double Tension2 { get; set; } + public double Tension3 { get; set; } + public double Tension4 { get; set; } + public double Tension5 { get; set; } + #endregion + #region 厚度5次 + public double Height1 { get; set; } + public double Height2 { get; set; } + public double Height3 { get; set; } + public double Height4 { get; set; } + public double Height5 { get; set; } + #endregion + #region 线宽9次 + public double LineWidth1 { get; set; } + public double LineWidth2 { get; set; } + public double LineWidth3 { get; set; } + public double LineWidth4 { get; set; } + public double LineWidth5 { get; set; } + public double LineWidth6 { get; set; } + public double LineWidth7 { get; set; } + public double LineWidth8 { get; set; } + public double LineWidth9 { get; set; } + #endregion + #region PT6次 + public double PT1 { get; set; } + public double PT2 { get; set; } + public double PT3 { get; set; } + public double PT4 { get; set; } + public double PT5 { get; set; } + public double PT6 { get; set; } + #endregion + /// + /// 缺陷数 + /// + public int DefectCount { get; set; } + + #region 缺陷种类 + public int DKCount { get; set; }//堵孔数量 + public int ZWCount { get; set; }//脏污数量 + public int GSYCCount { get; set; }//钢丝异常数量 + public int XWSCount { get; set; }//纤维丝数量 + public int QKCount { get; set; }//缺口数量 + public int ZKCount { get; set; }//针孔数量 + public int PPCount { get; set; }//泡泡数量 + public int HSCount { get; set; }//划伤数量 + public int YXCount { get; set; }//压线数量 + public int XBCount { get; set; }//斜边数量 new + public int SXCount { get; set; }//栅线数量 new + #endregion + + /// + /// mark点数据:[X1,Y1,X2,Y2,X3,Y3,X4,Y4] + /// + [SugarColumn(IsNullable = true)] + public string MarkData { get; set; } + // + public bool Succeed { get; set; } + /// + /// 失败分类 + /// + public int FailType { get; set; } + /// + /// 失败的工序名称 + /// + [SugarColumn(IsNullable = true)] + public string FailProcessName { get; set; } + [SugarColumn(IsNullable = true, ColumnDataType = "text", Length = 2048)] + public string Note { get; set; } + + /// + /// 0-初始; 5-已检测; 10-出现异常 + /// + public int State { get; set; } + + //---------- + /// + /// 修改次数 + /// + public int HistoryCount { get; set; } = 0; + /// + /// 修改历史记录 + /// + [Navigate(NavigateType.OneToMany, nameof(OrderHistory.Pid))] + public List OrderHistoryList { get; set; } + + /// + /// Defect和Size比对失败的坐标位置 + /// + [Navigate(NavigateType.OneToMany, nameof(DefectInfo.Pid))] + public List DefectInfoList { get; set; } + + //-------IsIgnore = true 不保存 + [SugarColumn(IsIgnore = true)] + //[Navigate(NavigateType.OneToMany, nameof(SizeTagData.Pid))] + public List SizeTagDataList { get; set; } + + //2023-10-30 添加异常列 + /// + /// 异常情况 + /// + [SugarColumn(IsNullable = true)] + public string Abnormalities { get; set; } + /// + /// 修复人员 + /// + [SugarColumn(IsNullable = true)] + public string RepairCode { get; set; } + } + [SugarIndex("index_{table}_pid", nameof(OrderHistory.Pid), OrderByType.Asc, isUnique: false)] + public class OrderHistory : BaseTable + { + public int Pid { get; set; } + public bool Qualified { get; set; }//合格 + + //比对 + public int CompareResult { get; set; } + //平均值 + public double TensionValue { get; set; } + public double HeightValue { get; set; } + public double LineWidthValue { get; set; } + public double PTValue { get; set; } + + //外观 + public int DKCount { get; set; }//堵孔数量 + public int ZWCount { get; set; }//脏污数量 + public int GSYCCount { get; set; }//钢丝异常数量 + public int XWSCount { get; set; }//纤维丝数量 + public int QKCount { get; set; }//缺口数量 + public int ZKCount { get; set; }//针孔数量 + public int PPCount { get; set; }//泡泡数量 + public int HSCount { get; set; }//划伤数量 + public int YXCount { get; set; }//压线数量 + public int XBCount { get; set; }//斜边数量 new + public int SXCount { get; set; }//栅线数量 new + } + + [SugarIndex("index_{table}_pid", nameof(SizeTagData.Pid), OrderByType.Asc, isUnique: false)] + public class SizeTagData : BaseTable + { + public int Pid { get; set; } + public string SizeTag { get; set; } + /// + /// 产生Tag工序索引 + /// + public int CreateStepIndex { get; set; } + /// + /// 消费本数据工序索引和消费值索引:5-0,8-2 + /// + public string ConsumeStepIndex { get; set; } + + /// + /// double[] + /// + public string posePT { get; set; } + } + + [SugarIndex("index_{table}_pid", nameof(DefectInfo.Pid), OrderByType.Asc, isUnique: false)] + public class DefectInfo : BaseTable + { + public int Pid { get; set; } + /// + /// 0-Defect 1-Size + /// + public int Type { get; set; } + public string Code { get;set; } + + public double X { get; set; } + public double Y { get; set; } + public double ZXD { get; set; } + } } \ No newline at end of file diff --git a/halftoneproject-master/Models/Product.cs b/halftoneproject-master/Models/Product.cs index 9954154..de89e7c 100644 --- a/halftoneproject-master/Models/Product.cs +++ b/halftoneproject-master/Models/Product.cs @@ -109,8 +109,10 @@ namespace Models //mark尺寸 public double MarkSize { get; set; } //抓点图像 + [SugarColumn(IsNullable = true)] public string MapPath { get; set; } //抓取点位 + [SugarColumn(IsNullable = true)] public string GetPointList { get; set; } } ///