From ff7cab72419729ce2c5adc46350ef45d89a5d1e5 Mon Sep 17 00:00:00 2001 From: patrick.xu <patrick.xu@broconcentric.com> Date: 星期六, 24 七月 2021 10:31:41 +0800 Subject: [PATCH] MES动作添加异常捕捉和重试机制 --- src/Bro.M071.Process/M071Process.cs | 1067 ++++++++++++++++++++++++++++++++++++----------------------- 1 files changed, 648 insertions(+), 419 deletions(-) diff --git a/src/Bro.M071.Process/M071Process.cs b/src/Bro.M071.Process/M071Process.cs index 1de633a..a281648 100644 --- a/src/Bro.M071.Process/M071Process.cs +++ b/src/Bro.M071.Process/M071Process.cs @@ -2,7 +2,7 @@ using Bro.Common.Helper; using Bro.Common.Interface; using Bro.Common.Model; -using Bro.M071.DBManager; +//using Bro.M071.DBManager; using Bro.M071.Model; using Bro.M071.Model.Model; using Bro.M071.Process.UI; @@ -14,10 +14,12 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Configuration; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; +using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -46,33 +48,47 @@ public event Action<IShapeElement> OnElementUpdated; public event Action<MachineState> OnMachineStateChanged; public event Action OnFullResetDone; + public event Action OnResetDone; #endregion string _precision = "f3"; + double _allowedShift = 0; public override void Open() { InitialSetting(); - base.Open(); + if (!Config.IsOfflineMode) + { + base.Open(); - InitialMotionCardBaseAxisAlarm(); + InitialMotionCardBaseAxisAlarm(); - SwitchBeep(false); - SwitchLightGreen(false); - SwitchLightRed(false); - SwitchLightYellow(false); + SwitchBeep(false); + SwitchLightGreen(false); + SwitchLightRed(false); + SwitchLightYellow(false); - Reset(null, null, null); - FullReset(null); + Reset(null, null, null); + FullReset(null); + } if (Config.Precision > 0) { _precision = "f" + Config.Precision; } - IncomingCheckMethod = InitialMESWebServiceMethod(IncomingCheckMethodName, out IncomingCheckObj); - DataUploadMethod = InitialMESWebServiceMethod(DataUploadMethodName, out DataUploadObj); + if (Config.IsEnableMESUpload) + { + IncomingCheckMethod = InitialMESWebServiceMethod(IncomingCheckMethodName, out IncomingCheckObj); + DataUploadMethod = InitialMESWebServiceMethod(DataUploadMethodName, out DataUploadObj); + } + + var allowedShiftStr = ConfigurationManager.AppSettings["DataShift"]; + if (!double.TryParse(allowedShiftStr, out _allowedShift)) + { + _allowedShift = 0; + } } private void InitialMotionCardBaseAxisAlarm() @@ -185,7 +201,42 @@ } #endregion + + AutoResetEvent _jobDoneHandle = new AutoResetEvent(false); + [ProcessMethod("ManualTest", "ManualTest", "鎵嬪姩娴嬭瘯", InvokeType.TestInvoke)] + public ProcessResponse ManualTest(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice) + { + if (config is ManualTestOperationConfig opConfig) + { + Task.Run(async () => + { + for (int i = 0; i < opConfig.RepeatTimes; i++) + { + BarCode = $"Test_{i + 1}"; + StartJob(null, null, null); + + if (_jobDoneHandle.WaitOne(20000)) + { + LogAsync(DateTime.Now, $"绗瑊i + 1}娆′换鍔″畬鎴�", ""); + await Task.Delay(500); + } + else + { + LogAsync(DateTime.Now, $"绗瑊i + 1}娆′换鍔¤秴鏃�", ""); + break; + } + } + }); + } + + return new ProcessResponse(true); + } + + object productionLock = new object(); List<ProductionMeasurement> productionList = new List<ProductionMeasurement>(); + + bool _isdoing = false; + object _doingLock = new object(); [ProcessMethod("", "StartJob", "寮�濮嬫壂鎻�", InvokeType.TestInvoke)] public ProcessResponse StartJob(IOperationConfig opConfig, IDevice invokeDevice, IDevice sourceDevice) @@ -196,12 +247,13 @@ } string hint = ""; - if (MachineState != MachineState.Ready) - { - hint = "鏈哄彴鏈氨缁紝璇峰嬁寮�濮嬫祴閲�"; - OnCheckHintUpload?.Invoke(hint, true); - throw new ProcessException(hint, null, ExceptionLevel.Fatal); - } + + //if (MachineState != MachineState.Ready) + //{ + // hint = "鏈哄彴鏈氨缁紝璇峰嬁寮�濮嬫祴閲�"; + // OnCheckHintUpload?.Invoke(hint, true); + // throw new ProcessException(hint, null, ExceptionLevel.Warning); + //} if (string.IsNullOrWhiteSpace(BarCode)) { @@ -211,7 +263,18 @@ throw new ProcessException(hint); } - MachineState = MachineState.Running; + lock (_doingLock) + { + if (_isdoing) + { + LogAsync(DateTime.Now, "璁惧姝e湪杩愯涓�", ""); + return new ProcessResponse(true); + } + + _isdoing = true; + } + + MeasureState = MachineState = MachineState.Running; OnCheckHintUpload?.Invoke(hint, true); OnMeasureStart?.Invoke(); @@ -239,20 +302,25 @@ BarCode = ""; - var existedProduction = productionList.FirstOrDefault(u => u.Barcode == pMeasure.Barcode); - if (existedProduction != null) + lock (productionLock) { - productionList.Remove(existedProduction); - existedProduction.Dispose(); - existedProduction = null; - } + var existedProduction = productionList.FirstOrDefault(u => u.Barcode == pMeasure.Barcode); + if (existedProduction != null) + { + productionList.Remove(existedProduction); + existedProduction.Dispose(); + existedProduction = null; + } - productionList.Add(pMeasure); + productionList.Add(pMeasure); + } pMeasure.InitialMeasurementsPropertyChanged(); pMeasure.PropertyChanged += MeasureProduction_PropertyChanged; - Config.SnapshotPointCollection.Where(u => u.IsEnabled).ToList().ForEach(s => + try + { + Config.SnapshotPointCollection.Where(u => u.IsEnabled).ToList().ForEach(s => { _pausedHandle.Wait(); @@ -301,23 +369,43 @@ RunImageHandle(s.CameraOp.OpConfig, set, s.Id, s.Name, pMeasure.Measurements); }); + } + catch (Exception ex) + { + throw ex; + } + finally + { + LogAsync(DateTime.Now, $"{pMeasure.Barcode}娴嬮噺鍔ㄤ綔瀹屾垚", ""); + _isdoing = false; - LogAsync(DateTime.Now, $"{pMeasure.Barcode}娴嬮噺鍔ㄤ綔瀹屾垚", ""); - - GC.Collect(0, GCCollectionMode.Optimized); + GC.Collect(0, GCCollectionMode.Optimized); + } return new ProcessResponse(true); } #region 鍙屾墜鍚姩 + object _leftStartLock = new object(); + object _rightStartLock = new object(); + bool isLeftStart = false; bool IsLeftStart { get => isLeftStart; set { - isLeftStart = value; - StartCheck(); + if (isLeftStart != value) + { + lock (_leftStartLock) + { + if (IsLeftStart != value) + { + isLeftStart = value; + StartCheck(); + } + } + } } } @@ -327,8 +415,17 @@ get => isRightStart; set { - isRightStart = value; - StartCheck(); + if (isRightStart != value) + { + lock (_rightStartLock) + { + if (isRightStart != value) + { + isRightStart = value; + StartCheck(); + } + } + } } } @@ -336,6 +433,11 @@ { if (isRightStart && isLeftStart) { + if (_isdoing) + { + OnCheckHintUpload?.Invoke("璁惧杩愯涓�", false); + return; + } StartJob(null, null, null); } } @@ -361,6 +463,74 @@ return new ProcessResponse(); } + + [ProcessMethod("Demostration", "CheckBasePlan", "鍩哄噯骞抽潰妫�鏍�", InvokeType.TestInvoke)] + public ProcessResponse CheckBasePlan(IOperationConfig opConfig, IDevice invokeDevice, IDevice sourceDevice) + { + if (opConfig is DemostrationOperationConfig config) + { + config.DemoOperations.ForEach(d => + { + IDevice device = DeviceCollection.FirstOrDefault(u => u.Id == d.MotionOp.Device); + if (device != null) + { + IMotionCard motionDevice = device as IMotionCard; + + if (motionDevice != null) + { + var response = motionDevice.Run(d.MotionOp.OpConfig); + if (!response.Result) + { + throw new ProcessException($"{device.Name}寮傚父锛寋response.Message}", null, ExceptionLevel.Fatal); + } + } + } + + CameraBase camera = DeviceCollection.FirstOrDefault(u => u.Id == d.CameraOp.Device) as CameraBase; + if (camera != null) + { + IImageSet set = null; + try + { + set = CollectHImage(camera, d.CameraOp.OpConfig); + } + catch (ProcessException pEx) + { + pEx.Level = ExceptionLevel.Fatal; + throw pEx; + } + + if (set != null) + { + LaserScanParam scanParam = JsonConvert.DeserializeObject<LaserScanParam>(set.ImageData); + LogAsync(DateTime.Now, $"鎵弿鍙傛暟:{set.ImageData}", ""); + + var tool = GetHalconTool(d.CameraOp.OpConfig, config.MonitorSetId); + if (tool != null) + { + using (tool.InputImageDic["INPUT_Image"] = set.HImage) + { + tool.InputTupleDic["INPUT_Resolution_Z"] = scanParam.Resolution_Z / 1000000.0; + + if (!tool.RunProcedure(out string error)) + { + LogAsync(DateTime.Now, $"{tool.ProcedureName}鎵ц寮傚父", error); + } + else + { + var diffX = tool.GetResultTuple("OUTPUT_Result_X").D; + var diffY = tool.GetResultTuple("OUTPUT_Result_Y").D; + LogAsync(DateTime.Now, $"妫�娴嬪钩闈紝X鏂瑰悜鏋佸樊锛歿diffX.ToString(_precision)}锛孻鏂瑰悜鏋佸樊锛歿diffY.ToString(_precision)}", ""); + } + } + } + } + } + }); + } + + return new ProcessResponse(); + } #endregion #region 绉佹湁鏂规硶 @@ -368,9 +538,13 @@ { if (sender is ProductionMeasurement pMeasure) { - var production = productionList.FirstOrDefault(u => u.Barcode == pMeasure.Barcode); - if (production == null) - return; + ProductionMeasurement production = null; + lock (productionLock) + { + production = productionList.FirstOrDefault(u => u.Barcode == pMeasure.Barcode); + if (production == null) + return; + } lock (production) { @@ -418,17 +592,20 @@ } else { - m.Spec.ActualValue = double.Parse(_halconToolDict[toolKey].GetResultTuple("OUTPUT_Result").D.ToString(_precision)); - //LogAsync(DateTime.Now, $"{m.GetDisplayText()}鏁版嵁{m.Spec.ActualValue}锛岀粨鏋渰(m.Spec.MeasureResult == null ? "TBD" : (m.Spec.MeasureResult == true ? "OK" : "NG"))}", ""); + double actualValue = double.Parse(_halconToolDict[toolKey].GetResultTuple("OUTPUT_Result").D.ToString(_precision)); + m.Spec.ActualValue = actualValue; + + //M071瑕佹眰瓒呴檺鏁版嵁鍦ㄥ厑璁歌寖鍥村唴鍘嬬缉鍒板悎鏍艰寖鍥村唴 + if (_allowedShift > 0 && m.Spec.MeasureResult != null && m.Spec.MeasureResult.Value == false) + { + m.Spec.ActualValue = m.Spec.StandardValue + (actualValue - m.Spec.StandardValue) * (m.Spec.Tolrenance_Positive - m.Spec.StandardValue) / (m.Spec.Tolrenance_Positive - m.Spec.StandardValue + _allowedShift); + } } } } } - //LogAsync(DateTime.Now, $"{m.GetDisplayText()}妫�娴嬬粨鏋�", $"{((m.Spec.MeasureResult ?? false) ? "OK" : "NG")}"); - KeyIndicator indicator = new KeyIndicator(m.Id, m.DisplayLocation); - //indicator.Text = (m.Spec.ActualValue == null || m.Spec.ActualValue == -999) ? "NA" : m.Spec.ActualValue.Value.ToString(_precision); indicator.Text = m.Spec.ActualValue == null ? "NA" : m.Spec.ActualValue.Value.ToString(_precision); indicator.ResultState = m.Spec.MeasureResult; pMeasure.ElementList.Add(indicator); @@ -474,8 +651,23 @@ LogAsync(DateTime.Now, $"{pMeasure.Barcode} 妫�娴嬪畬鎴愶紝缁撴灉 {pMeasure.PResult}", ""); - if (MachineState == MachineState.Running) - MachineState = MachineState.Ready; + //if (MachineState == MachineState.Running) + // MachineState = MachineState.Ready; + + MeasureState = MachineState.Ready; + if (MachineState != MachineState.Alarm) + { + if (MachineState == MachineState.Pause) + { + _machineStateBeforePause = MachineState.Ready; + } + else + { + MachineState = MachineState.Ready; + } + } + + _jobDoneHandle.Set(); var measurementUnitResultAndKeyUnitDataSet = GetMeasurementUnitResultAndKeyUnitData(pMeasure); @@ -494,50 +686,53 @@ SaveWholeImage(pMeasure); - productionList.RemoveAll(p => p.Barcode == pMeasure.Barcode); + lock (productionLock) + { + productionList.RemoveAll(p => p.Barcode == pMeasure.Barcode); + } pMeasure.Dispose(); //LogAsync(DateTime.Now, $"{pMeasure.Barcode}浜у搧淇℃伅閲婃斁瀹屾垚", JsonConvert.SerializeObject(pMeasure)); } } - KeyUnitDataManager keyUnitDataManager = new KeyUnitDataManager(); - MeasurementUnitResultManager measurementUnitResultManager = new MeasurementUnitResultManager(); - MeasurementAndKeyDataRelationManager measurementAndKeyDataRelationManager = new MeasurementAndKeyDataRelationManager(); - ProductionMeasurementRecordsManager productionMeasurementRecordsManager = new ProductionMeasurementRecordsManager(); + //KeyUnitDataManager keyUnitDataManager = new KeyUnitDataManager(); + //MeasurementUnitResultManager measurementUnitResultManager = new MeasurementUnitResultManager(); + //MeasurementAndKeyDataRelationManager measurementAndKeyDataRelationManager = new MeasurementAndKeyDataRelationManager(); + //ProductionMeasurementRecordsManager productionMeasurementRecordsManager = new ProductionMeasurementRecordsManager(); static object dataSaveLock = new object(); - private async void SaveProductionData(ProductionMeasurementUnitResultAndKeyUnitDataSet measurementUnitResultAndKeyUnitDataSet) - { - await Task.Run(() => - { - try - { - lock (dataSaveLock) - { - // 鑾峰彇 浜у搧鏁版嵁 骞朵繚瀛� - var productionMeasurementRecords = measurementUnitResultAndKeyUnitDataSet.ProductionMeasurementRecord; - productionMeasurementRecordsManager.CreateModel(productionMeasurementRecords); + //private async void SaveProductionData(ProductionMeasurementUnitResultAndKeyUnitDataSet measurementUnitResultAndKeyUnitDataSet) + //{ + // await Task.Run(() => + // { + // try + // { + // lock (dataSaveLock) + // { + // // 鑾峰彇 浜у搧鏁版嵁 骞朵繚瀛� + // var productionMeasurementRecords = measurementUnitResultAndKeyUnitDataSet.ProductionMeasurementRecord; + // productionMeasurementRecordsManager.CreateModel(productionMeasurementRecords); - // 鑾峰彇 鍘熷鏁版嵁 骞朵繚瀛� - var keyUnitDatas = measurementUnitResultAndKeyUnitDataSet.KeyUnitDataList; - keyUnitDataManager.BatchAddKeyUnitData(keyUnitDatas); + // // 鑾峰彇 鍘熷鏁版嵁 骞朵繚瀛� + // var keyUnitDatas = measurementUnitResultAndKeyUnitDataSet.KeyUnitDataList; + // keyUnitDataManager.BatchAddKeyUnitData(keyUnitDatas); - // 鑾峰彇 妫�娴嬬粨鏋滄暟鎹� 骞朵繚瀛� - var measurementUnitResults = measurementUnitResultAndKeyUnitDataSet.MeasurementUnitResultList; - measurementUnitResultManager.BatchAddMeasurementUnitResult(measurementUnitResults); + // // 鑾峰彇 妫�娴嬬粨鏋滄暟鎹� 骞朵繚瀛� + // var measurementUnitResults = measurementUnitResultAndKeyUnitDataSet.MeasurementUnitResultList; + // measurementUnitResultManager.BatchAddMeasurementUnitResult(measurementUnitResults); - // 鑾峰彇 鍏崇郴鏁版嵁骞朵繚瀛� - var measurementAndKeyDataRelationList = measurementUnitResultAndKeyUnitDataSet.MeasurementAndKeyDataRelationList; - measurementAndKeyDataRelationManager.BatchAddMeasurementAndKeyDataRelation(measurementAndKeyDataRelationList); - } - } - catch (Exception ex) - { - LogAsync(DateTime.Now, "鏁版嵁淇濆瓨寮傚父", ex.GetExceptionMessage()); - } - }); - } + // // 鑾峰彇 鍏崇郴鏁版嵁骞朵繚瀛� + // var measurementAndKeyDataRelationList = measurementUnitResultAndKeyUnitDataSet.MeasurementAndKeyDataRelationList; + // measurementAndKeyDataRelationManager.BatchAddMeasurementAndKeyDataRelation(measurementAndKeyDataRelationList); + // } + // } + // catch (Exception ex) + // { + // LogAsync(DateTime.Now, "鏁版嵁淇濆瓨寮傚父", ex.GetExceptionMessage()); + // } + // }); + //} private ProductionMeasurementUnitResultAndKeyUnitDataSet GetMeasurementUnitResultAndKeyUnitData(ProductionMeasurement pData) { @@ -570,19 +765,19 @@ measurementUnitResult.ProductionBarcode = productionMeasurementRecords.ProductionBarcode; measurementUnitResult.MeasurementName = measurementUnit.GetDisplayText(); - if (measurementUnit.MeasureType == "Alignment" || measurementUnit.MeasureType == "Slant") + if (measurementUnit.MeasureType.StartsWith("Alignment") || measurementUnit.MeasureType.StartsWith("Slant")) { measurementUnitResult.Keys = string.Join("-", measurementUnit.KeyUnitCollection.Select(u => u.Key)); measurementUnitResult.Positions = string.Join("-", measurementUnit.KeyUnitCollection.Select(u => u.KeyResultId)); } - else if (measurementUnit.MeasureType == "RowAlignment") + else if (measurementUnit.MeasureType.StartsWith("RowAlignment")) { measurementUnitResult.Keys = measurementUnit.KeyUnitCollection[0].Key + "~" + measurementUnit.KeyUnitCollection[measurementUnit.KeyUnitCollection.Count() - 1].Key; measurementUnitResult.Keys = measurementUnit.KeyUnitCollection[0].KeyResultId + "~" + measurementUnit.KeyUnitCollection[measurementUnit.KeyUnitCollection.Count() - 1].KeyResultId; } measurementUnitResult.MeasurementType = measurementUnit.MeasureType; measurementUnitResult.MeasurementValue = measurementUnit.Spec.ActualValue == null ? "NA" : measurementUnit.Spec.ActualValue.Value.ToString(_precision); - measurementUnitResult.MeasurementResult = measurementUnit.Spec.MeasureResult.Value ? "OK" : "NG"; + measurementUnitResult.MeasurementResult = measurementUnit.Spec.MeasureResult == null ? "NA" : measurementUnit.Spec.MeasureResult.Value ? "OK" : "NG"; measurementUnitResults.Add(measurementUnitResult); @@ -620,51 +815,52 @@ return measurementUnitResultAndKeyUnitDataSet; } - private async void ExportProductionExcel(ProductionMeasurementUnitResultAndKeyUnitDataSet measurementUnitResultAndKeyUnitDataSet) - { - if (!Config.IsCSVOutputEnabled) - return; + //private async void ExportProductionExcel(ProductionMeasurementUnitResultAndKeyUnitDataSet measurementUnitResultAndKeyUnitDataSet) + //{ + // if (!Config.IsCSVOutputEnabled) + // return; - await Task.Run(() => - { - ExcelExportSet excelExportDto = new ExcelExportSet(); - excelExportDto.Worksheets = new List<string>() { "鍘熷鏁版嵁", "妫�娴嬬粨鏋�" }; - var keyUnitColumns = new Dictionary<string, string>() - { - {"ProductionBarcode", "浜у搧鏉$爜"}, - {"Key", "閿�"}, - {"MeasurementItem", "妫�娴嬮」"}, - {"ItemValue", "妫�娴嬪��"} - }; - var measurementUnitResultColumns = new Dictionary<string, string>() - { - {"ProductionBarcode", "浜у搧鏉$爜"}, - {"MeasurementName", "妫�娴嬪悕绉�"}, - {"MeasurementType", "妫�娴嬬被鍨�"}, - {"MeasurementValue", "妫�娴嬪��"}, - {"MeasurementResult", "妫�娴嬬粨鏋�"}, - }; - excelExportDto.WorksheetColumns[excelExportDto.Worksheets[0]] = keyUnitColumns; - excelExportDto.WorksheetColumns[excelExportDto.Worksheets[1]] = measurementUnitResultColumns; + // await Task.Run(() => + // { + // ExcelExportSet excelExportDto = new ExcelExportSet(); + // excelExportDto.Worksheets = new List<string>() { "鍘熷鏁版嵁", "妫�娴嬬粨鏋�" }; + // var keyUnitColumns = new Dictionary<string, string>() + // { + // {"ProductionBarcode", "浜у搧鏉$爜"}, + // {"Key", "閿�"}, + // {"MeasurementItem", "妫�娴嬮」"}, + // {"ItemValue", "妫�娴嬪��"} + // }; + // var measurementUnitResultColumns = new Dictionary<string, string>() + // { + // {"ProductionBarcode", "浜у搧鏉$爜"}, + // {"MeasurementName", "妫�娴嬪悕绉�"}, + // {"MeasurementType", "妫�娴嬬被鍨�"}, + // {"MeasurementValue", "妫�娴嬪��"}, + // {"MeasurementResult", "妫�娴嬬粨鏋�"}, + // }; + // excelExportDto.WorksheetColumns[excelExportDto.Worksheets[0]] = keyUnitColumns; + // excelExportDto.WorksheetColumns[excelExportDto.Worksheets[1]] = measurementUnitResultColumns; - excelExportDto.WorksheetDataTable[excelExportDto.Worksheets[0]] = ExcelExportHelper.ListToDataTable(measurementUnitResultAndKeyUnitDataSet.KeyUnitDataList, keyUnitColumns); - excelExportDto.WorksheetDataTable[excelExportDto.Worksheets[1]] = ExcelExportHelper.ListToDataTable(measurementUnitResultAndKeyUnitDataSet.MeasurementUnitResultList, measurementUnitResultColumns); ; + // excelExportDto.WorksheetDataTable[excelExportDto.Worksheets[0]] = ExcelExportHelper.ListToDataTable(measurementUnitResultAndKeyUnitDataSet.KeyUnitDataList, keyUnitColumns); + // excelExportDto.WorksheetDataTable[excelExportDto.Worksheets[1]] = ExcelExportHelper.ListToDataTable(measurementUnitResultAndKeyUnitDataSet.MeasurementUnitResultList, measurementUnitResultColumns); ; - if (!Directory.Exists(Config.LogPath)) - { - Directory.CreateDirectory(Config.LogPath); - } - var fileName = Path.Combine(Config.LogPath, $"ProductionData_{DateTime.Now.ToString("yyyyMMdd")}.xlsx"); + // if (!Directory.Exists(Config.LogPath)) + // { + // Directory.CreateDirectory(Config.LogPath); + // } + // var fileName = Path.Combine(Config.LogPath, $"ProductionData_{DateTime.Now.ToString("yyyyMMdd")}.xlsx"); - byte[] filecontent = ExcelExportHelper.CreateOrAppendExcel(excelExportDto, fileName); - FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); - fs.Write(filecontent, 0, filecontent.Length); - fs.Flush(); - fs.Close(); - }); - } + // byte[] filecontent = ExcelExportHelper.CreateOrAppendExcel(excelExportDto, fileName); + // FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); + // fs.Write(filecontent, 0, filecontent.Length); + // fs.Flush(); + // fs.Close(); + // }); + //} static object excelExportLock = new object(); + string fileName = ""; private async void ExportProductionInColumns(ProductionMeasurementUnitResultAndKeyUnitDataSet exportData) { if (!Config.IsCSVOutputEnabled) @@ -678,305 +874,320 @@ { Directory.CreateDirectory(Config.LogPath); } - var fileName = Path.Combine(Config.LogPath, $"LDSData_{DateTime.Now.ToString("yyyyMMdd")}.xlsx"); - //bool isExisted = File.Exists(fileName); - using (ExcelPackage package = new ExcelPackage(new FileInfo(fileName))) + + if (string.IsNullOrWhiteSpace(fileName)) { - ExcelWorksheet rawDataSheet = null; - ExcelWorksheet slantSheet = null; - ExcelWorksheet alignmentSheet = null; - ExcelWorksheet rowAlignmentSheet = null; + fileName = Path.Combine(Config.LogPath, $"LDSData_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xlsx"); + } - if (!package.Workbook.Worksheets.Any(s => s.Name == "RawData")) + try + { + using (ExcelPackage package = new ExcelPackage(new FileInfo(fileName))) { - package.Workbook.Worksheets.Add("RawData"); - rawDataSheet = package.Workbook.Worksheets["RawData"]; - for (int i = 0; i < Config.KeyNameCollection.Count; i++) + ExcelWorksheet rawDataSheet = null; + ExcelWorksheet slantSheet = null; + ExcelWorksheet alignmentSheet = null; + ExcelWorksheet rowAlignmentSheet = null; + + if (!package.Workbook.Worksheets.Any(s => s.Name == "RawData")) { - var cell = rawDataSheet.Cells[i + 3, 1]; - cell.Value = Config.KeyNameCollection[i]; - SetTitleCell(cell, false); + package.Workbook.Worksheets.Add("RawData"); + rawDataSheet = package.Workbook.Worksheets["RawData"]; + for (int i = 0; i < Config.KeyNameCollection.Count; i++) + { + var cell = rawDataSheet.Cells[i + 3, 1]; + cell.Value = Config.KeyNameCollection[i]; + SetTitleCell(cell, false); + } } - } - rawDataSheet = package.Workbook.Worksheets["RawData"]; + rawDataSheet = package.Workbook.Worksheets["RawData"]; - if (!package.Workbook.Worksheets.Any(s => s.Name == "Slant")) - { - package.Workbook.Worksheets.Add("Slant"); + if (!package.Workbook.Worksheets.Any(s => s.Name == "Slant")) + { + package.Workbook.Worksheets.Add("Slant"); + slantSheet = package.Workbook.Worksheets["Slant"]; + + var keyCell = slantSheet.Cells[2, 1]; + keyCell.Value = "Key"; + SetTitleCell(keyCell); + + for (int i = 0; i < Config.KeyNameCollection.Count; i++) + { + var cell = slantSheet.Cells[i + 3, 1]; + cell.Value = Config.KeyNameCollection[i]; + SetTitleCell(cell, false); + } + } slantSheet = package.Workbook.Worksheets["Slant"]; - var keyCell = slantSheet.Cells[2, 1]; - keyCell.Value = "Key"; - SetTitleCell(keyCell); - - for (int i = 0; i < Config.KeyNameCollection.Count; i++) + if (!package.Workbook.Worksheets.Any(s => s.Name == "Alignment")) { - var cell = slantSheet.Cells[i + 3, 1]; - cell.Value = Config.KeyNameCollection[i]; - SetTitleCell(cell, false); - } - } - slantSheet = package.Workbook.Worksheets["Slant"]; + package.Workbook.Worksheets.Add("Alignment"); + alignmentSheet = package.Workbook.Worksheets["Alignment"]; - if (!package.Workbook.Worksheets.Any(s => s.Name == "Alignment")) - { - package.Workbook.Worksheets.Add("Alignment"); + var keysCell = alignmentSheet.Cells[2, 1]; + keysCell.Value = "Keys"; + SetTitleCell(keysCell); + + var positionCell = alignmentSheet.Cells[2, 2]; + positionCell.Value = "Positions"; + SetTitleCell(positionCell); + + var alignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType.StartsWith("Alignment")).ToList(); + for (int i = 0; i < alignmentMeasures.Count(); i++) + { + var cellKeys = alignmentSheet.Cells[i + 3, 1]; + cellKeys.Value = alignmentMeasures[i].Keys; + SetTitleCell(cellKeys, false); + + var cellPosition = alignmentSheet.Cells[i + 3, 2]; + cellPosition.Value = alignmentMeasures[i].Positions; + SetTitleCell(cellPosition, false); + } + } alignmentSheet = package.Workbook.Worksheets["Alignment"]; - var keysCell = alignmentSheet.Cells[2, 1]; - keysCell.Value = "Keys"; - SetTitleCell(keysCell); - - var positionCell = alignmentSheet.Cells[2, 2]; - positionCell.Value = "Positions"; - SetTitleCell(positionCell); - - var alignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType == "Alignment").ToList(); - for (int i = 0; i < alignmentMeasures.Count(); i++) + if (!package.Workbook.Worksheets.Any(s => s.Name == "RowAlignment")) { - var cellKeys = alignmentSheet.Cells[i + 3, 1]; - cellKeys.Value = alignmentMeasures[i].Keys; - SetTitleCell(cellKeys, false); + package.Workbook.Worksheets.Add("RowAlignment"); + rowAlignmentSheet = package.Workbook.Worksheets["RowAlignment"]; - var cellPosition = alignmentSheet.Cells[i + 3, 2]; - cellPosition.Value = alignmentMeasures[i].Positions; - SetTitleCell(cellPosition, false); + var keysCell = rowAlignmentSheet.Cells[2, 1]; + keysCell.Value = "Keys"; + SetTitleCell(keysCell); + + var positionCell = rowAlignmentSheet.Cells[2, 2]; + positionCell.Value = "Positions"; + SetTitleCell(positionCell); + + var rowAlignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType.StartsWith("RowAlignment")).ToList(); + for (int i = 0; i < rowAlignmentMeasures.Count(); i++) + { + var cellKeys = rowAlignmentSheet.Cells[i + 3, 1]; + cellKeys.Value = rowAlignmentMeasures[i].Keys; + SetTitleCell(cellKeys, false); + + var cellPosition = rowAlignmentSheet.Cells[i + 3, 2]; + cellPosition.Value = rowAlignmentMeasures[i].Positions; + SetTitleCell(cellPosition, false); + } } - } - alignmentSheet = package.Workbook.Worksheets["Alignment"]; - - if (!package.Workbook.Worksheets.Any(s => s.Name == "RowAlignment")) - { - package.Workbook.Worksheets.Add("RowAlignment"); rowAlignmentSheet = package.Workbook.Worksheets["RowAlignment"]; - var keysCell = rowAlignmentSheet.Cells[2, 1]; - keysCell.Value = "Keys"; - SetTitleCell(keysCell); - - var positionCell = rowAlignmentSheet.Cells[2, 2]; - positionCell.Value = "Positions"; - SetTitleCell(positionCell); - - var rowAlignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType == "RowAlignment").ToList(); - for (int i = 0; i < rowAlignmentMeasures.Count(); i++) + #region RawData { - var cellKeys = rowAlignmentSheet.Cells[i + 3, 1]; - cellKeys.Value = rowAlignmentMeasures[i].Keys; - SetTitleCell(cellKeys, false); - - var cellPosition = rowAlignmentSheet.Cells[i + 3, 2]; - cellPosition.Value = rowAlignmentMeasures[i].Positions; - SetTitleCell(cellPosition, false); - } - } - rowAlignmentSheet = package.Workbook.Worksheets["RowAlignment"]; - - #region RawData - { - int rowDataStartCol = rawDataSheet.Dimension.Columns; - var barcodeCell = rawDataSheet.Cells[1, rowDataStartCol + 1, 1, rowDataStartCol + 4]; - barcodeCell.Merge = true; - barcodeCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; - barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; - SetTitleCell(barcodeCell); - - var z1Cell = rawDataSheet.Cells[2, rowDataStartCol + 1]; - z1Cell.Value = "Z1"; - SetTitleCell(z1Cell); - - var z2Cell = rawDataSheet.Cells[2, rowDataStartCol + 2]; - z2Cell.Value = "Z2"; - SetTitleCell(z2Cell); - - var z3Cell = rawDataSheet.Cells[2, rowDataStartCol + 3]; - z3Cell.Value = "Z3"; - SetTitleCell(z3Cell); - - var z4Cell = rawDataSheet.Cells[2, rowDataStartCol + 4]; - z4Cell.Value = "Z4"; - SetTitleCell(z4Cell); - - exportData.KeyUnitDataList.ForEach(k => - { - int keyIndex = Config.KeyNameCollection.IndexOf(k.Key); - if (keyIndex < 0) - { - LogAsync(DateTime.Now, "Excel瀵煎嚭閿欒", $"{k.Key}鐨凴awData鏈兘鑾峰彇琛屼俊鎭紝鏈鍑�"); - return; - } - - int zIndex = int.Parse(k.MeasurementItem.Substring(1)); - - var cell = rawDataSheet.Cells[keyIndex + 1 + 2, rowDataStartCol + zIndex]; - cell.Value = string.IsNullOrWhiteSpace(k.ItemValue) ? "NA" : k.ItemValue; - }); - } - #endregion - - #region Slant - var slantMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType == "Slant").ToList(); - if (slantMeasures.Count > 0) - { - int slantStartCol = slantSheet.Dimension.Columns; - - var barcodeCell = slantSheet.Cells[1, slantStartCol + 1]; - barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; - SetTitleCell(barcodeCell); - - var valueCell = slantSheet.Cells[2, slantStartCol + 1]; - valueCell.Value = "Value"; - SetTitleCell(valueCell); - - slantMeasures.ForEach(m => - { - int rowIndex = Config.KeyNameCollection.IndexOf(m.Keys); - if (rowIndex < 0) - { - LogAsync(DateTime.Now, "Excel瀵煎嚭閿欒", $"{m.Keys}鐨凷lant鏈兘鑾峰彇琛屼俊鎭紝鏈鍑�"); - return; - } - - var cellValue = slantSheet.Cells[rowIndex + 1 + 2, slantStartCol + 1]; - //var cellResult = slantSheet.Cells[rowIndex + 1 + 2, slantStartCol + 2]; - - cellValue.Value = m.MeasurementValue; - //cellResult.Value = m.MeasurementResult; - - if (m.MeasurementResult != "OK") - { - SetNGCell(cellValue); - //SetNGCell(cellResult); - } - }); - } - #endregion - - #region Alignment - { - var alignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType == "Alignment").ToList(); - if (alignmentMeasures.Count > 0) - { - List<string> keysList = new List<string>(); - int allRowNums = alignmentSheet.Dimension.Rows; - int aligneStartCol = alignmentSheet.Dimension.Columns; - - for (int i = 3; i <= alignmentSheet.Dimension.End.Row; i++) - { - string keys = alignmentSheet.Cells[i, 1].Value.ToString(); - string position = alignmentSheet.Cells[i, 2].Value.ToString(); - - keysList.Add($"{keys}_{position}"); - } - - //var barcodeCell = alignmentSheet.Cells[1, aligneStartCol + 1, 1, aligneStartCol + 2]; - //barcodeCell.Merge = true; - //barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; - //SetTitleCell(barcodeCell); - - var barcodeCell = alignmentSheet.Cells[1, aligneStartCol + 1]; + int rowDataStartCol = rawDataSheet.Dimension.Columns; + var barcodeCell = rawDataSheet.Cells[1, rowDataStartCol + 1, 1, rowDataStartCol + 4]; + barcodeCell.Merge = true; + barcodeCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; SetTitleCell(barcodeCell); - var valueCell = alignmentSheet.Cells[2, aligneStartCol + 1]; - valueCell.Value = "Value"; - SetTitleCell(valueCell); + var z1Cell = rawDataSheet.Cells[2, rowDataStartCol + 1]; + z1Cell.Value = "Z1"; + SetTitleCell(z1Cell); - //var resultCell = alignmentSheet.Cells[2, aligneStartCol + 2]; - //resultCell.Value = "Result"; - //SetTitleCell(resultCell); + var z2Cell = rawDataSheet.Cells[2, rowDataStartCol + 2]; + z2Cell.Value = "Z2"; + SetTitleCell(z2Cell); - alignmentMeasures.ForEach(a => + var z3Cell = rawDataSheet.Cells[2, rowDataStartCol + 3]; + z3Cell.Value = "Z3"; + SetTitleCell(z3Cell); + + var z4Cell = rawDataSheet.Cells[2, rowDataStartCol + 4]; + z4Cell.Value = "Z4"; + SetTitleCell(z4Cell); + + exportData.KeyUnitDataList.ForEach(k => { - int rowIndex = keysList.IndexOf($"{a.Keys}_{a.Positions}"); - if (rowIndex < 0) + int keyIndex = Config.KeyNameCollection.IndexOf(k.Key); + if (keyIndex < 0) { - LogAsync(DateTime.Now, "Excel瀵煎嚭閿欒", $"{a.Keys}_{a.Positions}鐨凙lignment鏈兘鑾峰彇琛屼俊鎭紝鏈鍑�"); + LogAsync(DateTime.Now, "Excel瀵煎嚭閿欒", $"{k.Key}鐨凴awData鏈兘鑾峰彇琛屼俊鎭紝鏈鍑�"); return; } - var cellValue = alignmentSheet.Cells[rowIndex + 1 + 2, aligneStartCol + 1]; - //var cellResult = alignmentSheet.Cells[rowIndex + 1 + 2, aligneStartCol + 2]; + int zIndex = int.Parse(k.MeasurementItem.Substring(1)); - cellValue.Value = a.MeasurementValue; - //cellResult.Value = a.MeasurementResult; + var cell = rawDataSheet.Cells[keyIndex + 1 + 2, rowDataStartCol + zIndex]; + cell.Value = string.IsNullOrWhiteSpace(k.ItemValue) ? "NA" : k.ItemValue; + }); + } + #endregion - if (a.MeasurementResult != "OK") + #region Slant + var slantMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType.StartsWith("Slant")).ToList(); + if (slantMeasures.Count > 0) + { + int slantStartCol = slantSheet.Dimension.Columns; + + var barcodeCell = slantSheet.Cells[1, slantStartCol + 1]; + barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; + SetTitleCell(barcodeCell); + + var valueCell = slantSheet.Cells[2, slantStartCol + 1]; + valueCell.Value = "Value"; + SetTitleCell(valueCell); + + slantMeasures.ForEach(m => + { + int rowIndex = Config.KeyNameCollection.IndexOf(m.Keys); + if (rowIndex < 0) + { + LogAsync(DateTime.Now, "Excel瀵煎嚭閿欒", $"{m.Keys}鐨凷lant鏈兘鑾峰彇琛屼俊鎭紝鏈鍑�"); + return; + } + + var cellValue = slantSheet.Cells[rowIndex + 1 + 2, slantStartCol + 1]; + //var cellResult = slantSheet.Cells[rowIndex + 1 + 2, slantStartCol + 2]; + + cellValue.Value = m.MeasurementValue; + //cellResult.Value = m.MeasurementResult; + + if (m.MeasurementResult != "OK") { SetNGCell(cellValue); //SetNGCell(cellResult); } }); } - } - #endregion + #endregion - #region RowAlignment - { - var rowAlignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType == "RowAlignment").ToList(); - if (rowAlignmentMeasures.Count > 0) + #region Alignment { - List<string> keysList = new List<string>(); - int allRowNums = rowAlignmentSheet.Dimension.Rows; - int aligneStartCol = rowAlignmentSheet.Dimension.Columns; - - for (int i = 3; i <= allRowNums; i++) + var alignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType.StartsWith("Alignment")).ToList(); + if (alignmentMeasures.Count > 0) { - string keys = alignmentSheet.Cells[i, 1].Value.ToString(); - string position = alignmentSheet.Cells[i, 2].Value.ToString(); + List<string> keysList = new List<string>(); + int allRowNums = alignmentSheet.Dimension.Rows; + int aligneStartCol = alignmentSheet.Dimension.Columns; - keysList.Add($"{keys}_{position}"); + for (int i = 3; i <= alignmentSheet.Dimension.End.Row; i++) + { + string keys = alignmentSheet.Cells[i, 1].Value.ToString(); + string position = alignmentSheet.Cells[i, 2].Value.ToString(); + + keysList.Add($"{keys}_{position}"); + } + + //var barcodeCell = alignmentSheet.Cells[1, aligneStartCol + 1, 1, aligneStartCol + 2]; + //barcodeCell.Merge = true; + //barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; + //SetTitleCell(barcodeCell); + + var barcodeCell = alignmentSheet.Cells[1, aligneStartCol + 1]; + barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; + SetTitleCell(barcodeCell); + + var valueCell = alignmentSheet.Cells[2, aligneStartCol + 1]; + valueCell.Value = "Value"; + SetTitleCell(valueCell); + + //var resultCell = alignmentSheet.Cells[2, aligneStartCol + 2]; + //resultCell.Value = "Result"; + //SetTitleCell(resultCell); + + alignmentMeasures.ForEach(a => + { + int rowIndex = keysList.IndexOf($"{a.Keys}_{a.Positions}"); + if (rowIndex < 0) + { + LogAsync(DateTime.Now, "Excel瀵煎嚭閿欒", $"{a.Keys}_{a.Positions}鐨凙lignment鏈兘鑾峰彇琛屼俊鎭紝鏈鍑�"); + return; + } + + var cellValue = alignmentSheet.Cells[rowIndex + 1 + 2, aligneStartCol + 1]; + //var cellResult = alignmentSheet.Cells[rowIndex + 1 + 2, aligneStartCol + 2]; + + cellValue.Value = a.MeasurementValue; + //cellResult.Value = a.MeasurementResult; + + if (a.MeasurementResult != "OK") + { + SetNGCell(cellValue); + //SetNGCell(cellResult); + } + }); } - - //var barcodeCell = rowAlignmentSheet.Cells[1, aligneStartCol + 1, 1, aligneStartCol + 2]; - //barcodeCell.Merge = true; - //barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; - //SetTitleCell(barcodeCell); - - var barcodeCell = rowAlignmentSheet.Cells[1, aligneStartCol + 1]; - barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; - SetTitleCell(barcodeCell); - - var valueCell = rowAlignmentSheet.Cells[2, aligneStartCol + 1]; - valueCell.Value = "Value"; - SetTitleCell(valueCell); - - //var resultCell = rowAlignmentSheet.Cells[2, aligneStartCol + 2]; - //resultCell.Value = "Result"; - //SetTitleCell(resultCell); - - rowAlignmentMeasures.ForEach(a => - { - int rowIndex = keysList.IndexOf($"{a.Keys}_{a.Positions}"); - if (rowIndex < 0) - { - LogAsync(DateTime.Now, "Excel瀵煎嚭閿欒", $"{a.Keys}_{a.Positions}鐨凴owAlignment鏈兘鑾峰彇琛屼俊鎭紝鏈鍑�"); - return; - } - - var cellValue = rowAlignmentSheet.Cells[rowIndex + 1 + 2, aligneStartCol + 1]; - //var cellResult = rowAlignmentSheet.Cells[rowIndex + 1 + 2, aligneStartCol + 2]; - - cellValue.Value = a.MeasurementValue; - //cellResult.Value = a.MeasurementResult; - - if (a.MeasurementResult != "OK") - { - SetNGCell(cellValue); - //SetNGCell(cellResult); - } - }); } - } - #endregion + #endregion - package.Save(); + #region RowAlignment + { + var rowAlignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType.StartsWith("RowAlignment")).ToList(); + if (rowAlignmentMeasures.Count > 0) + { + List<string> keysList = new List<string>(); + int allRowNums = rowAlignmentSheet.Dimension.Rows; + int aligneStartCol = rowAlignmentSheet.Dimension.Columns; - rawDataSheet.Dispose(); - slantSheet.Dispose(); - alignmentSheet.Dispose(); - rowAlignmentSheet.Dispose(); - }; + for (int i = 3; i <= allRowNums; i++) + { + string keys = alignmentSheet.Cells[i, 1].Value.ToString(); + string position = alignmentSheet.Cells[i, 2].Value.ToString(); + + keysList.Add($"{keys}_{position}"); + } + + //var barcodeCell = rowAlignmentSheet.Cells[1, aligneStartCol + 1, 1, aligneStartCol + 2]; + //barcodeCell.Merge = true; + //barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; + //SetTitleCell(barcodeCell); + + var barcodeCell = rowAlignmentSheet.Cells[1, aligneStartCol + 1]; + barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode; + SetTitleCell(barcodeCell); + + var valueCell = rowAlignmentSheet.Cells[2, aligneStartCol + 1]; + valueCell.Value = "Value"; + SetTitleCell(valueCell); + + //var resultCell = rowAlignmentSheet.Cells[2, aligneStartCol + 2]; + //resultCell.Value = "Result"; + //SetTitleCell(resultCell); + + rowAlignmentMeasures.ForEach(a => + { + int rowIndex = keysList.IndexOf($"{a.Keys}_{a.Positions}"); + if (rowIndex < 0) + { + LogAsync(DateTime.Now, "Excel瀵煎嚭閿欒", $"{a.Keys}_{a.Positions}鐨凴owAlignment鏈兘鑾峰彇琛屼俊鎭紝鏈鍑�"); + return; + } + + var cellValue = rowAlignmentSheet.Cells[rowIndex + 1 + 2, aligneStartCol + 1]; + //var cellResult = rowAlignmentSheet.Cells[rowIndex + 1 + 2, aligneStartCol + 2]; + + cellValue.Value = a.MeasurementValue; + //cellResult.Value = a.MeasurementResult; + + if (a.MeasurementResult != "OK") + { + SetNGCell(cellValue); + //SetNGCell(cellResult); + } + }); + } + } + #endregion + + package.Save(); + + rawDataSheet.Dispose(); + slantSheet.Dispose(); + alignmentSheet.Dispose(); + rowAlignmentSheet.Dispose(); + }; + } + catch (Exception ex) + { + LogAsync(DateTime.Now, "Excel鏃ュ織寮傚父", ex.GetExceptionMessage()); + fileName = Path.Combine(Config.LogPath, $"LDSData_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xlsx"); + //string bkFileName = Path.Combine(Config.LogPath, $"{Path.GetFileNameWithoutExtension(fileName)}_bk_{DateTime.Now.ToString("HHmmss")}.xlsx"); + //File.Copy(fileName, bkFileName); + //File.Delete(fileName); + } } }); } @@ -1097,6 +1308,8 @@ } #endregion + static object _resultCalcLock = new object(); + private async void RunImageHandle(IOperationConfig opConfig, IImageSet imgSet, string snapshotId, string snapshotName, List<MeasurementUnit> measureList) { await Task.Run(() => @@ -1104,8 +1317,14 @@ var keys = Config.KeyUnitCollection.Where(u => u.IsEnabled && u.SnapshotPointId == snapshotId); var keyBindCollection = measureList.SelectMany(u => u.KeyUnitCollection).Where(u => keys.Any(k => k.Key == u.Key)).ToList(); + if (imgSet.HImage == null) + { + LogAsync(DateTime.Now, $"{snapshotName}鏈幏鍙栨壂鎻忓浘鍍�", ""); + keyBindCollection.ForEach(k => k.FillKeyValues(null)); + return; + } + string toolKey = (opConfig as CameraOprerationConfigBase).AlgorithemPath; - //HObject images = imgSet.HImage; HObject images = new HObject(); LaserScanParam scanParam = JsonConvert.DeserializeObject<LaserScanParam>(imgSet.ImageData); @@ -1168,71 +1387,81 @@ // Directory.CreateDirectory(dir); //} - //Parallel.For(1, count.I + 1, (i) => - for (int i = 1; i <= count.I; i++) + lock (_resultCalcLock) { - HOperatorSet.SelectObj(images, out HObject image, i); - - //string fileName = Path.Combine(dir, $"{i}.tif"); - //using (HImage temp = image.ConvertHObjectToHImage()) - //{ - // temp.WriteImage("tiff", 0, fileName); - //} - - keys.Where(u => u.ImageSeq == i).ToList().ForEach(k => + //Parallel.For(1, count.I + 1, (i) => + for (int i = 1; i <= count.I; i++) { - Dictionary<string, double> resultDict = null; + HOperatorSet.SelectObj(images, out HObject image, i); - var keyBindList = keyBindCollection.Where(u => u.Key == k.Key).ToList(); + //string fileName = Path.Combine(dir, $"{i}.tif"); + //using (HImage temp = image.ConvertHObjectToHImage()) + //{ + // temp.WriteImage("tiff", 0, fileName); + //} - string keyToolKey = k.AliasName + "|" + k.KeyAlgorithemPath; - if (!_halconToolDict.ContainsKey(keyToolKey)) + keys.Where(u => u.ImageSeq == i).ToList().ForEach(k => { - LogAsync(DateTime.Now, $"{k.AliasName}妫�娴嬬畻娉曟湭鍒濆鍖�", ""); - } - else - { - _halconToolDict[keyToolKey].InputImageDic["INPUT_Image"] = image; - _halconToolDict[keyToolKey].InputTupleDic["INPUT_Resolution_X"] = scanParam.Resolution_X / 1000000.0; - _halconToolDict[keyToolKey].InputTupleDic["INPUT_Resolution_Y"] = scanParam.Resolution_Y / 1000000.0; - _halconToolDict[keyToolKey].InputTupleDic["INPUT_Resolution_Z"] = scanParam.Resolution_Z / 1000000.0; - _halconToolDict[keyToolKey].InputTupleDic["INPUT_ImageId"] = $"{k.AliasName}_{DateTime.Now.ToString("HHmmssfff")}.tif"; - if (!_halconToolDict[keyToolKey].RunProcedure(out string error)) + Dictionary<string, double> resultDict = null; + + var keyBindList = keyBindCollection.Where(u => u.Key == k.Key).ToList(); + + string keyToolKey = k.AliasName + "|" + k.KeyAlgorithemPath; + if (!_halconToolDict.ContainsKey(keyToolKey)) { - LogAsync(DateTime.Now, $"{k.AliasName}妫�娴嬬畻娉曞紓甯革紝{error}", ""); + LogAsync(DateTime.Now, $"{k.AliasName}妫�娴嬬畻娉曟湭鍒濆鍖�", ""); } else { - var results = _halconToolDict[keyToolKey].GetResultTuple("OUTPUT_Results").DArr.ToList(); - if (results.Count == 0 || results.Any(u => u < 0)) + _halconToolDict[keyToolKey].InputImageDic["INPUT_Image"] = image; + _halconToolDict[keyToolKey].InputTupleDic["INPUT_Resolution_X"] = scanParam.Resolution_X / 1000000.0; + _halconToolDict[keyToolKey].InputTupleDic["INPUT_Resolution_Y"] = scanParam.Resolution_Y / 1000000.0; + _halconToolDict[keyToolKey].InputTupleDic["INPUT_Resolution_Z"] = scanParam.Resolution_Z / 1000000.0; + _halconToolDict[keyToolKey].InputTupleDic["INPUT_ImageId"] = $"{k.AliasName}_{DateTime.Now.ToString("HHmmssfff")}.tif"; + if (!_halconToolDict[keyToolKey].RunProcedure(out string error)) { - LogAsync(DateTime.Now, $"{k.AliasName}鍘熷鏁版嵁寮傚父", ""); + LogAsync(DateTime.Now, $"{k.AliasName}妫�娴嬬畻娉曞紓甯革紝{error}", ""); } else { - //LogAsync(DateTime.Now, $"{k.AliasName}鍘熷鏁版嵁", $"{string.Join(" ", results)}"); - - results = results.Select(u => u - Config.PlanCompensation).ToList(); - resultDict = k.KeyResultList.ToDictionary(u => u, u => + var results = _halconToolDict[keyToolKey].GetResultTuple("OUTPUT_Results").DArr.ToList(); + if (results.Count == 0 || results.Any(u => u < 0)) { - int index = k.KeyResultList.IndexOf(u); - return results[index]; - }); + LogAsync(DateTime.Now, $"{k.AliasName}鍘熷鏁版嵁寮傚父", ""); + } + else + { + //LogAsync(DateTime.Now, $"{k.AliasName}鍘熷鏁版嵁", $"{string.Join(" ", results)}"); + + results = results.Select(u => u - Config.PlanCompensation).ToList(); + resultDict = k.KeyResultList.ToDictionary(u => u, u => + { + int index = k.KeyResultList.IndexOf(u); + return results[index]; + }); + } } } - } - keyBindList.ForEach(kb => - { - kb.KeyImages.Add(image.ConvertHObjectToHImage()); - kb.FillKeyValues(resultDict); + keyBindList.ForEach(kb => + { + if (kb.KeyImages != null) + { + kb.KeyImages.Add(image.ConvertHObjectToHImage()); + kb.FillKeyValues(resultDict); + } + else + { + + } + }); }); - }); - image.Dispose(); - image = null; + image.Dispose(); + image = null; + } + //); } - //); imgSet.HImage.Dispose(); imgSet.HImage = null; -- Gitblit v1.8.0