From 3ae459e2e79e567dfd4a552a3b5b8c1fce495167 Mon Sep 17 00:00:00 2001
From: xcd <834800634@qq.com>
Date: 星期四, 16 七月 2020 17:23:35 +0800
Subject: [PATCH] Merge branch 'master' of http://gitblit.broconcentric.com:8088/r/M071

---
 src/Bro.M071.Process/M071Process.cs | 1004 ++++++++++++++++++++++++++++++++++++++++++++++++++++------
 1 files changed, 898 insertions(+), 106 deletions(-)

diff --git a/src/Bro.M071.Process/M071Process.cs b/src/Bro.M071.Process/M071Process.cs
index 13fde83..7847649 100644
--- a/src/Bro.M071.Process/M071Process.cs
+++ b/src/Bro.M071.Process/M071Process.cs
@@ -2,15 +2,26 @@
 using Bro.Common.Helper;
 using Bro.Common.Interface;
 using Bro.Common.Model;
+using Bro.M071.DBManager;
+using Bro.M071.Model;
+using Bro.M071.Model.Model;
+using Bro.M071.Process.UI;
 using Bro.Process;
 using HalconDotNet;
+using Newtonsoft.Json;
+using OfficeOpenXml;
+using OfficeOpenXml.Style;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
+using System.Drawing;
+using System.Drawing.Imaging;
 using System.IO;
 using System.Linq;
 using System.Text;
+using System.Threading;
 using System.Threading.Tasks;
+using static Bro.Common.Helper.EnumHelper;
 
 namespace Bro.M071.Process
 {
@@ -31,8 +42,10 @@
 
         #region 浜嬩欢
         public event Action OnMeasureStart;
-        public event Action<string> OnBarcodeChanged;
+        public event Action OnClearBarcode;
         public event Action<IShapeElement> OnElementUpdated;
+        public event Action<MachineState> OnMachineStateChanged;
+        public event Action OnFullResetDone;
         #endregion
 
         public override void Open()
@@ -40,10 +53,40 @@
             InitialSetting();
 
             base.Open();
+
+            InitialMotionCardBaseAxisAlarm();
+
+            SwitchBeep(false);
+            SwitchLightGreen(false);
+            SwitchLightRed(false);
+            SwitchLightYellow(false);
+
+            Reset(null, null, null);
+            FullReset(null);
+        }
+
+        private void InitialMotionCardBaseAxisAlarm()
+        {
+            if (outputCtrlCard != null)
+            {
+                outputCtrlCard.OnAxisAlarmRaised -= MotionCard_OnAxisAlarmRaised;
+                outputCtrlCard.OnAxisAlarmRaised += MotionCard_OnAxisAlarmRaised;
+            }
+        }
+
+        private void MotionCard_OnAxisAlarmRaised(int axisIndex, string alarmMsg)
+        {
+            RaisedAlarm(alarmMsg);
+            MachineState = MachineState.Alarm;
         }
 
         private void InitialSetting()
         {
+            //鏁版嵁搴撹縼绉绘鏌�
+            //DatabaseInitialize.Initialize();
+
+            MotionCardSettingCheck();
+
             Config.SnapshotPointCollection.ForEach(u =>
             {
                 u.GetHalconToolPathList().ForEach(path =>
@@ -59,21 +102,21 @@
 
                 var snapshotPoint = Config.SnapshotPointCollection.FirstOrDefault(s => s.Id == u.SnapshotPointId && s.IsEnabled);
                 if (snapshotPoint == null)
-                    throw new ProcessException($"{u.AlignName}鏈缃彲鐢ㄦ媿鐓х偣浣�");
+                    throw new ProcessException($"{u.AliasName}鏈缃彲鐢ㄦ媿鐓х偣浣�");
 
                 if (u.ImageSeq < 1)
-                    throw new ProcessException($"{u.AlignName}鍥剧墖搴忓彿灏忎簬1");
+                    throw new ProcessException($"{u.AliasName}鍥剧墖搴忓彿灏忎簬1");
 
                 var algo = Config.KeyAlgorithemCollection.FirstOrDefault(a => a.Id == u.KeyAlgorithemId);
                 if (algo == null)
-                    throw new ProcessException($"{u.AlignName}鏈缃娴嬬畻娉�");
+                    throw new ProcessException($"{u.AliasName}鏈缃娴嬬畻娉�");
 
                 u.KeyAlgorithemPath = algo.AlgorithemPath;
-                LoadHalconTool(u.KeyAlgorithemPath, u.AlignName);
+                LoadHalconTool(u.KeyAlgorithemPath, u.AliasName);
 
                 var resultSet = Config.KeyResultCollection.FirstOrDefault(r => r.Id == u.KeyResultId);
                 if (resultSet == null)
-                    throw new ProcessException($"{u.AlignName}鏈缃娴嬬粨鏋滈厤缃�");
+                    throw new ProcessException($"{u.AliasName}鏈缃娴嬬粨鏋滈厤缃�");
 
                 u.KeyResultList = new List<string>(resultSet.Results);
             });
@@ -98,7 +141,7 @@
                     if (keyRespone.Count == 0)
                         throw new ProcessException($"{u.GetDisplayText()}瀵瑰簲鐨勫崟閿笉瀛樺湪鎴栦笉鍙敤");
 
-                    if (b.KeyResult == "All")
+                    if (b.KeyResultId == "All")
                     {
                         keyRespone.SelectMany(kr => kr.KeyResultList).ToList().ForEach(r =>
                           {
@@ -107,184 +150,896 @@
                     }
                     else
                     {
-                        b.MeasureValueDict[b.KeyResult] = null;
+                        b.MeasureValueDict[b.KeyResultId] = null;
                     }
                 });
             });
         }
 
-        #region InitialHalconTool
-        //protected override void InitialHalconTool()
-        //{
-        //    base.InitialHalconTool();
-
-        //    Config.SnapshotPointCollection.ForEach(u =>
-        //    {
-        //        u.GetHalconToolPathList().ForEach(path =>
-        //        {
-        //            if (!string.IsNullOrWhiteSpace(path))
-        //            {
-        //                string directoryPath = Path.GetDirectoryName(path);
-        //                string fileName = Path.GetFileNameWithoutExtension(path);
-
-        //                HDevEngineTool tool = new HDevEngineTool(directoryPath);
-        //                tool.LoadProcedure(fileName);
-
-        //                //浣跨敤鈥渱鈥濅綔涓洪棿闅旂
-        //                _halconToolDict[u.Id + "|" + path] = tool;
-        //            }
-        //        });
-        //    });
-        //}
-        #endregion
-
-        //Dictionary<string, ProductionMeasurement> MeasureDict = new Dictionary<string, ProductionMeasurement>();
-
-        private string barCode = "";
-        public string BarCode
+        #region 娴佺▼涓姏鍑哄紓甯�
+        public override void ExceptionRaisedInMonitor(Exception ex)
         {
-            get => barCode;
-            set
+            if (ex is ProcessException pEx)
             {
-                if (barCode != value)
+                if (pEx.Level >= ExceptionLevel.Fatal)
                 {
-                    barCode = value;
-                    OnBarcodeChanged?.Invoke(value);
+                    RaisedAlarm(pEx.Message);
+                    MachineState = MachineState.Alarm;
                 }
             }
+            else
+            {
+                RaisedAlarm(ex.Message);
+                MachineState = MachineState.Alarm;
+            }
         }
+        #endregion
+
+        public string BarCode { get; set; }
+
+        List<ProductionMeasurement> productionList = new List<ProductionMeasurement>();
 
         [ProcessMethod("", "StartJob", "寮�濮嬫壂鎻�", InvokeType.TestInvoke)]
         public ProcessResponse StartJob(IOperationConfig opConfig, IDevice invokeDevice, IDevice sourceDevice)
         {
+            if (!IsAllowedWork)
+            {
+                throw new ProcessException(SafetyMsg, null, ExceptionLevel.Fatal);
+            }
+
+            if (MachineState != MachineState.Ready)
+                throw new ProcessException("鏈哄彴鏈氨缁紝璇峰嬁寮�濮嬫祴閲�", null, ExceptionLevel.Fatal);
+
             if (string.IsNullOrWhiteSpace(BarCode))
             {
+                OnClearBarcode?.Invoke();
                 throw new ProcessException("鏈緭鍏ヤ骇鍝佹潯鐮侊紝璇峰嬁寮�濮嬫祴閲�");
             }
 
-            OnMeasureStart?.BeginInvoke(null, null);
+            MachineState = MachineState.Running;
+            OnMeasureStart?.Invoke();
 
             var measurements = Config.MeasurementUnitCollection.Where(u => u.IsEnabled).ToList().DeepSerializeClone();
             measurements.ForEach(m =>
             {
                 m.InitialKeyUnitMeasureChanged();
-                //m.KeyUnitCollection.ForEach(k => k.InitialMeasureValueDictPropertyChanged());
             });
-
-            //MeasureDict[BarCode] = new ProductionMeasurement()
-            //{
-            //    Barcode = BarCode,
-            //    Measurements = measurements,
-            //};
-
-            //MeasureDict[BarCode].InitialMeasurementsPropertyChanged();
-            //MeasureDict[BarCode].PropertyChanged += MeasureProduction_PropertyChanged;
 
             var pMeasure = new ProductionMeasurement()
             {
                 Barcode = BarCode,
                 Measurements = measurements,
+                StartTime = DateTime.Now,
             };
+
+            var existedProduction = productionList.FirstOrDefault(u => u.Barcode == pMeasure.Barcode);
+            if (existedProduction != null)
+            {
+                productionList.Remove(existedProduction);
+                existedProduction.Dispose();
+                existedProduction = null;
+            }
+
+            productionList.Add(pMeasure);
 
             pMeasure.InitialMeasurementsPropertyChanged();
             pMeasure.PropertyChanged += MeasureProduction_PropertyChanged;
 
             Config.SnapshotPointCollection.Where(u => u.IsEnabled).ToList().ForEach(s =>
                   {
-                      IDevice device = DeviceCollection.FirstOrDefault(u => u.Id == s.MotionDevice);
+                      _pausedHandle.Wait();
+
+                      if (MachineState == MachineState.Ready)
+                          return;
+
+                      if (MachineState != MachineState.Running && MachineState != MachineState.Pause)
+                      {
+                          throw new ProcessException("鏈哄彴鐘舵�佷笉鍦ㄨ繍琛屼腑锛岄��鍑烘娴�");
+                      }
+
+                      IDevice device = DeviceCollection.FirstOrDefault(u => u.Id == s.MotionOp.Device);
                       if (device == null)
                           throw new ProcessException($"{s.Name}鎷嶇収鐐逛綅鏈缃繍鍔ㄨ澶�");
 
-                      IMotion motionDevice = device as IMotion;
+                      IMotionCard motionDevice = device as IMotionCard;
 
                       if (motionDevice == null)
                           throw new ProcessException($"{s.Name}鎷嶇収鐐逛綅璁剧疆{device.Name}涓嶆槸杩愬姩璁惧");
 
-                      if (!motionDevice.MoveToPoint(null))
+                      var response = motionDevice.Run(s.MotionOp.OpConfig);
+                      if (!response.Result)
                       {
-                          throw new ProcessException("杩愬姩涓", null, ExceptionLevel.Info);
+                          throw new ProcessException($"{device.Name}寮傚父锛寋response.Message}", null, ExceptionLevel.Fatal);
                       }
 
                       CameraBase camera = DeviceCollection.FirstOrDefault(u => u.Id == s.CameraOp.Device) as CameraBase;
                       if (camera == null)
                           return;
 
-                      ImageSet imgSet = camera.Snapshot(s.CameraOp.OpConfig);
-                      if (imgSet == null)
-                          return;
+                      IImageSet set = null;
+                      try
+                      {
+                          set = CollectHImage(camera, s.CameraOp.OpConfig);
+                      }
+                      catch (ProcessException pEx)
+                      {
+                          pEx.Level = ExceptionLevel.Fatal;
+                          throw pEx;
+                      }
 
-                      RunImageHandle(camera, s.CameraOp.OpConfig, imgSet, s.Id, s.Name, pMeasure.Measurements);
+                      if (set == null)
+                      {
+                          return;
+                      }
+
+                      RunImageHandle(s.CameraOp.OpConfig, set, s.Id, s.Name, pMeasure.Measurements);
                   });
 
             BarCode = "";
+            LogAsync(DateTime.Now, $"{pMeasure.Barcode}娴嬮噺鍔ㄤ綔瀹屾垚", "");
+
             return new ProcessResponse(true);
         }
 
+        #region 鍙屾墜鍚姩
+        bool isLeftStart = false;
+        bool IsLeftStart
+        {
+            get => isLeftStart;
+            set
+            {
+                isLeftStart = value;
+                StartCheck();
+            }
+        }
+
+        bool isRightStart = false;
+        bool IsRightStart
+        {
+            get => isRightStart;
+            set
+            {
+                isRightStart = value;
+                StartCheck();
+            }
+        }
+
+        private void StartCheck()
+        {
+            if (isRightStart && isLeftStart)
+            {
+                StartJob(null, null, null);
+            }
+        }
+
+        [ProcessMethod("", "Start_Left", "宸︽墜鍚姩", InvokeType.TestInvoke)]
+        public ProcessResponse Start_Left(IOperationConfig opConfig, IDevice invokeDevice, IDevice sourceDevice)
+        {
+            if (opConfig.InputPara != null && opConfig.InputPara.Count > 0)
+            {
+                IsLeftStart = opConfig.InputPara[0] == 1;
+            }
+
+            return new ProcessResponse();
+        }
+
+        [ProcessMethod("", "Start_Right", "鍙虫墜鍚姩", InvokeType.TestInvoke)]
+        public ProcessResponse Start_Right(IOperationConfig opConfig, IDevice invokeDevice, IDevice sourceDevice)
+        {
+            if (opConfig.InputPara != null && opConfig.InputPara.Count > 0)
+            {
+                IsRightStart = opConfig.InputPara[0] == 1;
+            }
+
+            return new ProcessResponse();
+        }
+        #endregion
+
+        #region 绉佹湁鏂规硶
         private void MeasureProduction_PropertyChanged(object sender, PropertyChangedEventArgs e)
         {
             if (sender is ProductionMeasurement pMeasure)
             {
-                //妫�鏌ユ槸鍚﹀叏閮ㄥ畬鎴�
-                pMeasure.Measurements.ForEach(m =>
+                var production = productionList.FirstOrDefault(u => u.Barcode == pMeasure.Barcode);
+                if (production == null)
+                    return;
+
+                lock (production)
                 {
-                    if (m.KeyUnitCollection.All(k => k.IsDone != null))
+                    //妫�鏌ユ槸鍚﹀叏閮ㄥ畬鎴�
+                    pMeasure.Measurements?.ForEach(m =>
                     {
-                        if (!m.IsUpdated)
+                        if (m.KeyUnitCollection.All(k => k.IsDone != null))
                         {
-                            if (m.KeyUnitCollection.Any(k => k.IsDone == false))
+                            if (!m.IsUpdated)
                             {
-                                m.Spec.ActualValue = -999;
-                            }
-                            else
-                            {
-                                string toolKey = m.Id + "|" + m.Spec.AlgorithemPath;
-                                if (!_halconToolDict.ContainsKey(toolKey))
+                                if (m.KeyUnitCollection.Any(k => k.IsDone == false))
                                 {
-                                    LogAsync(DateTime.Now, $"{m.GetDisplayText()}{m.Spec.Code}绠楁硶鏈垵濮嬪寲", "");
                                     m.Spec.ActualValue = -999;
                                 }
                                 else
                                 {
-                                    var array = m.KeyUnitCollection.SelectMany(u => u.MeasureValueDict.Values.ToList().ConvertAll(v => v ?? -999)).ToArray();
-                                    _halconToolDict[toolKey].InputTupleDic["INPUT_Params"] = new HTuple(array);
-                                    if (!_halconToolDict[toolKey].RunProcedure(out string error))
+                                    string toolKey = m.Id + "|" + m.Spec.AlgorithemPath;
+                                    if (!_halconToolDict.ContainsKey(toolKey))
                                     {
-                                        LogAsync(DateTime.Now, $"{m.GetDisplayText()}{m.Spec.Code}绠楁硶寮傚父,{error}", "");
+                                        LogAsync(DateTime.Now, $"{m.GetDisplayText()}{m.Spec.Code}绠楁硶鏈垵濮嬪寲", "");
                                         m.Spec.ActualValue = -999;
                                     }
                                     else
                                     {
-                                        m.Spec.ActualValue = _halconToolDict[toolKey].GetResultTuple("OUTPUT_Result").D;
-                                        LogAsync(DateTime.Now, $"{m.GetDisplayText()}鏁版嵁{m.Spec.ActualValue}锛岀粨鏋渰(m.Spec.MeasureResult == null ? "TBD" : (m.Spec.MeasureResult == true ? "OK" : "NG"))}", "");
+                                        var array = m.KeyUnitCollection.SelectMany(u => u.MeasureValueDict.Values.ToList().ConvertAll(v => v ?? -999)).ToArray();
+                                        _halconToolDict[toolKey].InputTupleDic["INPUT_Params"] = new HTuple(array);
+                                        if (!_halconToolDict[toolKey].RunProcedure(out string error))
+                                        {
+                                            LogAsync(DateTime.Now, $"{m.GetDisplayText()}{m.Spec.Code}绠楁硶寮傚父,{error}", "");
+                                            m.Spec.ActualValue = -999;
+                                        }
+                                        else
+                                        {
+                                            m.Spec.ActualValue = double.Parse(_halconToolDict[toolKey].GetResultTuple("OUTPUT_Result").D.ToString("f2"));
+                                            //LogAsync(DateTime.Now, $"{m.GetDisplayText()}鏁版嵁{m.Spec.ActualValue}锛岀粨鏋渰(m.Spec.MeasureResult == null ? "TBD" : (m.Spec.MeasureResult == true ? "OK" : "NG"))}", "");
+                                        }
                                     }
                                 }
+
+                                //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("f2");
+                                indicator.ResultState = m.Spec.MeasureResult;
+                                pMeasure.ElementList.Add(indicator);
+                                //杈撳嚭鍥惧舰鍩哄厓鍒扮晫闈� 
+                                OnElementUpdated?.Invoke(indicator);
+
+                                SaveKeyImages(pMeasure.Barcode, m);
+
+                                m.IsUpdated = true;
                             }
-
-                            //杈撳嚭鍥惧舰鍩哄厓鍒扮晫闈� todo
-                            OnElementUpdated?.BeginInvoke(null, null, null);
-
-                            m.IsUpdated = true;
                         }
-                    }
-                });
+                    });
 
-                if (!pMeasure.Measurements.All(m => m.IsUpdated))
-                {
-                    return;
+                    if (!pMeasure.Measurements.All(m => m.IsUpdated))
+                    {
+                        return;
+                    }
                 }
 
+                pMeasure.EndTime = DateTime.Now;
+                bool pResult = pMeasure.Measurements.All(u => u.Spec.MeasureResult == true);
+                pMeasure.PResult = pResult ? "OK" : "NG";
+                OnUpdateResult?.Invoke(DateTime.Now, pResult ? 1 : 0);
+                OnUpdateCT?.Invoke((float)(pMeasure.EndTime.Value - pMeasure.StartTime.Value).TotalSeconds);
+
+                LogAsync(DateTime.Now, $"{pMeasure.Barcode} 妫�娴嬪畬鎴愶紝缁撴灉 {pMeasure.PResult}", "");
+
+                if (MachineState == MachineState.Running)
+                    MachineState = MachineState.Ready;
+
+                var measurementUnitResultAndKeyUnitDataSet = GetMeasurementUnitResultAndKeyUnitData(pMeasure);
+
                 //MES杈撳嚭 todo
+                if (Config.IsEnableMESUpload)
+                {
+                }
 
-                //Excel鎶ヨ〃杈撳嚭 todo
+                //Excel鎶ヨ〃杈撳嚭 锛堝崟涓骇鍝佺殑excel瀵煎嚭锛�
+                //ExportProductionExcel(measurementUnitResultAndKeyUnitDataSet);
 
-                //鏁版嵁搴撲繚瀛� todo
+                ExportProductionInColumns(measurementUnitResultAndKeyUnitDataSet);
+                ////鏁版嵁搴撲繚瀛� 
+                //SaveProductionData(measurementUnitResultAndKeyUnitDataSet);
 
-                //MeasureDict.Remove(pMeasure.Barcode);
+                SaveWholeImage(pMeasure);
+
+                productionList.RemoveAll(p => p.Barcode == pMeasure.Barcode);
                 pMeasure.Dispose();
             }
         }
 
-        private async void RunImageHandle(CameraBase camera, IOperationConfig opConfig, ImageSet imgSet, string snapshotId, string snapshotName, List<MeasurementUint> measureList)
+        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);
+
+                        // 鑾峰彇 鍘熷鏁版嵁 骞朵繚瀛�
+                        var keyUnitDatas = measurementUnitResultAndKeyUnitDataSet.KeyUnitDataList;
+                        keyUnitDataManager.BatchAddKeyUnitData(keyUnitDatas);
+
+                        // 鑾峰彇 妫�娴嬬粨鏋滄暟鎹� 骞朵繚瀛�
+                        var measurementUnitResults = measurementUnitResultAndKeyUnitDataSet.MeasurementUnitResultList;
+                        measurementUnitResultManager.BatchAddMeasurementUnitResult(measurementUnitResults);
+
+                        // 鑾峰彇 鍏崇郴鏁版嵁骞朵繚瀛�
+                        var measurementAndKeyDataRelationList = measurementUnitResultAndKeyUnitDataSet.MeasurementAndKeyDataRelationList;
+                        measurementAndKeyDataRelationManager.BatchAddMeasurementAndKeyDataRelation(measurementAndKeyDataRelationList);
+                    }
+                }
+                catch (Exception ex)
+                {
+                    LogAsync(DateTime.Now, "鏁版嵁淇濆瓨寮傚父", ex.GetExceptionMessage());
+                }
+            });
+        }
+
+        private ProductionMeasurementUnitResultAndKeyUnitDataSet GetMeasurementUnitResultAndKeyUnitData(ProductionMeasurement pData)
+        {
+            ProductionMeasurementUnitResultAndKeyUnitDataSet measurementUnitResultAndKeyUnitDataSet = new ProductionMeasurementUnitResultAndKeyUnitDataSet();
+
+            try
+            {
+
+                //浜у搧鏁版嵁 
+                ProductionMeasurementRecords productionMeasurementRecords = new ProductionMeasurementRecords();
+                //鍏崇郴鏁版嵁
+                List<MeasurementAndKeyDataRelation> measurementAndKeyDataRelationList = new List<MeasurementAndKeyDataRelation>();
+                //鍘熷鏁版嵁
+                List<KeyUnitData> keyUnitDatas = new List<KeyUnitData>();
+                // 鍗曚釜浜у搧鐨勬祴閲忔眹鎬�
+                List<MeasurementUnitResult> measurementUnitResults = new List<MeasurementUnitResult>();
+
+                productionMeasurementRecords.ProductionBarcode = pData.Barcode;
+                productionMeasurementRecords.ProductionCode = ProductionCode;
+                productionMeasurementRecords.ProductionResult = pData.PResult;
+                productionMeasurementRecords.OperationStartTime = pData.StartTime.GetValueOrDefault();
+                productionMeasurementRecords.OperationEndTime = pData.EndTime.GetValueOrDefault();
+
+                measurementUnitResultAndKeyUnitDataSet.ProductionMeasurementRecord = productionMeasurementRecords;
+
+                foreach (var measurementUnit in pData.Measurements)//鑾峰彇鍒板崟涓祴閲忛」缁撴灉
+                {
+                    MeasurementUnitResult measurementUnitResult = new MeasurementUnitResult();
+                    measurementUnitResult.ProductionMeasurementRecordsId = productionMeasurementRecords.ID;
+                    measurementUnitResult.ProductionBarcode = productionMeasurementRecords.ProductionBarcode;
+                    measurementUnitResult.MeasurementName = measurementUnit.GetDisplayText();
+
+                    if (measurementUnit.MeasureType == "Alignment" || measurementUnit.MeasureType == "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")
+                    {
+                        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("f2");
+                    measurementUnitResult.MeasurementResult = measurementUnit.Spec.MeasureResult.Value ? "OK" : "NG";
+
+                    measurementUnitResults.Add(measurementUnitResult);
+
+                    foreach (var keyUnit in measurementUnit.KeyUnitCollection)//鑾峰彇鍗曚釜閿殑娴嬮噺缁撴灉
+                    {
+                        foreach (var keyValue in keyUnit.MeasureValueDict)//鑾峰彇鍗曚釜閿殑鍗曚釜娴嬮噺item 缁撴灉
+                        {
+                            bool isExist = keyUnitDatas.Any(u => u.Key == keyUnit.Key && u.MeasurementItem == keyValue.Key);
+                            if (!isExist)//宸插瓨鍦� 涓嶉噸澶嶆坊鍔犲師濮嬫暟鎹�
+                            {
+                                KeyUnitData keyUnitData = new KeyUnitData();
+                                keyUnitData.ProductionBarcode = productionMeasurementRecords.ProductionBarcode;
+                                keyUnitData.Key = keyUnit.Key;
+                                keyUnitData.MeasurementItem = keyValue.Key;
+                                keyUnitData.ItemValue = keyValue.Value == null ? "NA" : keyValue.Value.Value.ToString("f2");
+                                keyUnitDatas.Add(keyUnitData);
+
+                                MeasurementAndKeyDataRelation measurementAndKeyDataRelation = new MeasurementAndKeyDataRelation();
+                                measurementAndKeyDataRelation.MeasurementUnitResultId = measurementUnitResult.ID;
+                                measurementAndKeyDataRelation.KeyUnitDataId = keyUnitData.ID;
+                                measurementAndKeyDataRelationList.Add(measurementAndKeyDataRelation);
+                            }
+                        }
+                    }
+                }
+                measurementUnitResultAndKeyUnitDataSet.ProductionMeasurementRecord = productionMeasurementRecords;
+                measurementUnitResultAndKeyUnitDataSet.MeasurementAndKeyDataRelationList = measurementAndKeyDataRelationList;
+                measurementUnitResultAndKeyUnitDataSet.KeyUnitDataList = keyUnitDatas;
+                measurementUnitResultAndKeyUnitDataSet.MeasurementUnitResultList = measurementUnitResults;
+            }
+            catch (Exception ex)
+            {
+                LogAsync(DateTime.Now, "鏁版嵁鑾峰彇寮傚父", ex.GetExceptionMessage());
+            }
+            return measurementUnitResultAndKeyUnitDataSet;
+        }
+
+        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;
+
+                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");
+
+                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();
+        private async void ExportProductionInColumns(ProductionMeasurementUnitResultAndKeyUnitDataSet exportData)
+        {
+            if (!Config.IsCSVOutputEnabled)
+                return;
+
+            await Task.Run(() =>
+            {
+                lock (excelExportLock)
+                {
+                    if (!Directory.Exists(Config.LogPath))
+                    {
+                        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)))
+                    {
+                        ExcelWorksheet rawDataSheet = null;
+                        ExcelWorksheet slantSheet = null;
+                        ExcelWorksheet alignmentSheet = null;
+                        ExcelWorksheet rowAlignmentSheet = null;
+
+                        if (!package.Workbook.Worksheets.Any(s => s.Name == "RawData"))
+                        {
+                            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"];
+
+                        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"];
+
+                        if (!package.Workbook.Worksheets.Any(s => s.Name == "Alignment"))
+                        {
+                            package.Workbook.Worksheets.Add("Alignment");
+                            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++)
+                            {
+                                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"];
+
+                        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++)
+                            {
+                                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
+                        {
+                            //rawDataSheet = package.Workbook.Worksheets["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, 1, slantStartCol + 2];
+                            //barcodeCell.Merge = true;
+                            //barcodeCell.Value = exportData.ProductionMeasurementRecord.ProductionBarcode;
+                            //SetTitleCell(barcodeCell);
+
+                            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);
+
+                            //var resultCell = slantSheet.Cells[2, slantStartCol + 2];
+                            //resultCell.Value = "Result";
+                            //SetTitleCell(resultCell);
+
+                            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];
+                                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);
+                                    }
+                                });
+                            }
+                        }
+                        #endregion
+
+                        #region RowAlignment
+                        {
+                            var rowAlignmentMeasures = exportData.MeasurementUnitResultList.Where(u => u.MeasurementType == "RowAlignment").ToList();
+                            if (rowAlignmentMeasures.Count > 0)
+                            {
+                                List<string> keysList = new List<string>();
+                                int allRowNums = rowAlignmentSheet.Dimension.Rows;
+                                int aligneStartCol = rowAlignmentSheet.Dimension.Columns;
+
+                                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();
+                    };
+                }
+            });
+        }
+
+        private void SetNGCell(ExcelRange cell)
+        {
+            cell.Style.Font.Color.SetColor(Color.Red);
+            cell.Style.Font.Bold = true;
+            //cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
+            //cell.Style.Fill.BackgroundColor.SetColor(Color.Red);
+        }
+
+        private void SetTitleCell(ExcelRange cell, bool isCenterAlign = true)
+        {
+            cell.Style.Font.Color.SetColor(Color.White);
+            cell.Style.Font.Bold = true;
+            cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
+            cell.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(31, 73, 125));
+            cell.AutoFitColumns();
+            if (isCenterAlign)
+            {
+                cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
+            }
+            else
+            {
+                cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
+            }
+        }
+
+        #region 鍥惧儚淇濆瓨
+        private void SaveWholeImage(ProductionMeasurement pMeasure)
+        {
+            try
+            {
+                Bitmap backImage = (Bitmap)Bitmap.FromFile(Config.BackgroundImagePath);
+
+                Bitmap map = new Bitmap(backImage.Width, backImage.Height);
+                using (Graphics g = Graphics.FromImage(map))
+                {
+                    g.DrawImage(backImage, new PointF(0, 0));
+
+                    pMeasure.ElementList.ForEach(e =>
+                    {
+                        e.Draw(g);
+                    });
+                }
+
+                string dir = Path.Combine(Config.ImageSaveFolder, "TopView", DateTime.Now.ToString("yyyyMMdd"));
+                if (!Directory.Exists(dir))
+                {
+                    Directory.CreateDirectory(dir);
+                }
+
+                map.Save(Path.Combine(dir, $"{pMeasure.Barcode}_{pMeasure.PResult}_{DateTime.Now.ToString("HHmmss")}.png"), ImageFormat.Png);
+            }
+            catch (Exception ex)
+            {
+                LogAsync(DateTime.Now, "鏁翠綋鍥剧墖淇濆瓨寮傚父", ex.GetExceptionMessage());
+            }
+        }
+
+        private void SaveKeyImages(string barCode, MeasurementUnit measureUnit)
+        {
+            string measureName = measureUnit.GetDisplayText();
+            if (Config.ImageSaveOption.IsSaveOriginImage)
+            {
+                measureUnit.KeyUnitCollection.ForEach(u => u.ImageSaveStatus++);
+
+                string dir = Path.Combine(Config.ImageSaveFolder, "Origin", DateTime.Now.ToString("yyyyMMdd"), barCode, measureUnit.MeasureType);
+                if (!Directory.Exists(dir))
+                {
+                    Directory.CreateDirectory(dir);
+                }
+
+                SaveKeyImages(measureUnit, measureName, dir);
+            }
+
+            string result = (measureUnit.Spec.MeasureResult ?? false) ? "OK" : "NG";
+            if (Config.ImageSaveOption.AddtionalSaveType.ToUpper().Contains(result))
+            {
+                measureUnit.KeyUnitCollection.ForEach(u => u.ImageSaveStatus++);
+
+                string dir = Path.Combine(Config.ImageSaveFolder, result, DateTime.Now.ToString("yyyyMMdd"), barCode, measureUnit.MeasureType);
+                if (!Directory.Exists(dir))
+                {
+                    Directory.CreateDirectory(dir);
+                }
+
+                SaveKeyImages(measureUnit, measureName, dir);
+            }
+        }
+
+        private async void SaveKeyImages(MeasurementUnit measureUnit, string measureName, string dir)
+        {
+            await Task.Run(() =>
+            {
+                measureUnit.KeyUnitCollection.ForEach(u =>
+                {
+                    int i = 0;
+                    u.KeyImages?.ForEach(image =>
+                    {
+                        string fileName = "";
+                        try
+                        {
+                            fileName = Path.Combine(dir, $"{measureName}_{u.Key}{(i == 0 ? "" : $"-{i}")}_{DateTime.Now.ToString("HHmmss")}.tiff");
+                            image.WriteImage("tiff", 0, fileName);
+                        }
+                        catch (Exception)
+                        {
+                            LogAsync(DateTime.Now, "鍒囧浘淇濆瓨澶辫触", fileName);
+                        }
+                        i++;
+                    });
+
+                    u.ImageSaveStatus--;
+                });
+            });
+        }
+        #endregion
+
+        private async void RunImageHandle(IOperationConfig opConfig, IImageSet imgSet, string snapshotId, string snapshotName, List<MeasurementUnit> measureList)
         {
             await Task.Run(() =>
              {
@@ -292,7 +1047,11 @@
                  var keyBindCollection = measureList.SelectMany(u => u.KeyUnitCollection).Where(u => keys.Any(k => k.Key == u.Key)).ToList();
 
                  string toolKey = (opConfig as CameraOprerationConfigBase).AlgorithemPath;
-                 HObject images = imgSet.HImage;
+                 //HObject images = imgSet.HImage;
+
+                 HObject images = new HObject();
+                 LaserScanParam scanParam = JsonConvert.DeserializeObject<LaserScanParam>(imgSet.ImageData);
+                 LogAsync(DateTime.Now, $"鎵弿鍙傛暟:{imgSet.ImageData}", "");
 
                  if (!string.IsNullOrWhiteSpace(toolKey))
                  {
@@ -303,6 +1062,9 @@
                          keyBindCollection.ForEach(k => k.FillKeyValues(null));
                          return;
                      }
+
+                     //string fileName = Path.Combine(Config.ImageSaveFolder, "BeforeRun", $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.tif");
+                     //imgSet.HImage.WriteImage("tiff", 0, fileName);
 
                      _halconToolDict[toolKey].InputImageDic["INPUT_Image"] = imgSet.HImage;
                      if (!_halconToolDict[toolKey].RunProcedure(out string error))
@@ -316,6 +1078,7 @@
                  }
 
                  HOperatorSet.CountObj(images, out HTuple count);
+                 LogAsync(DateTime.Now, $"{snapshotName}鍒囧浘{count.I}寮�", "");
 
                  if (count == 0)
                  {
@@ -324,19 +1087,32 @@
                      return;
                  }
 
-                 var excludeKeys = keys.Where(u => u.ImageSeq > count).ToList();
+                 var excludeKeys = keys.Where(u => u.ImageSeq > count.I).ToList();
                  if (excludeKeys.Count > 0)
                  {
-                     LogAsync(DateTime.Now, $"{string.Join(" ", excludeKeys.Select(u => u.AlignName))}鏈湪鍥剧墖鑾峰彇搴忓垪涓�", "");
+                     LogAsync(DateTime.Now, $"{string.Join(" ", excludeKeys.Select(u => u.AliasName))}鏈湪鍥剧墖鑾峰彇搴忓垪涓�", "");
                      keyBindCollection.Where(k => excludeKeys.Any(u => u.Key == k.Key)).ToList().ForEach(k =>
                           {
                               k.FillKeyValues(null);
                           });
                  }
 
-                 Parallel.For(1, count.I, (i) =>
+                 //string dir = Path.Combine(Config.ImageSaveFolder, "Clips", $"{DateTime.Now.ToString("yyyyMMdd")}", $"{snapshotName}_{DateTime.Now.ToString("HHmmss")}");
+                 //if (!Directory.Exists(dir))
+                 //{
+                 //    Directory.CreateDirectory(dir);
+                 //}
+
+                 //Parallel.For(1, count.I + 1, (i) =>
+                 for (int i = 1; i <= count.I; i++)
                  {
                      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 =>
                          {
@@ -344,27 +1120,33 @@
 
                              var keyBindList = keyBindCollection.Where(u => u.Key == k.Key).ToList();
 
-                             string keyToolKey = k.AlignName + "|" + k.KeyAlgorithemPath;
+                             string keyToolKey = k.AliasName + "|" + k.KeyAlgorithemPath;
                              if (!_halconToolDict.ContainsKey(keyToolKey))
                              {
-                                 LogAsync(DateTime.Now, $"{k.AlignName}妫�娴嬬畻娉曟湭鍒濆鍖�", "");
+                                 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_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.AlignName}妫�娴嬬畻娉曞紓甯革紝{error}", "");
+                                     LogAsync(DateTime.Now, $"{k.AliasName}妫�娴嬬畻娉曞紓甯革紝{error}", "");
                                  }
                                  else
                                  {
-                                     var results = _halconToolDict[keyToolKey].GetResultTuple("OUTPUT_Results").HTupleToDouble();
+                                     var results = _halconToolDict[keyToolKey].GetResultTuple("OUTPUT_Results").DArr.ToList();
                                      if (results.Count == 0 || results.Any(u => u < 0))
                                      {
-                                         LogAsync(DateTime.Now, $"{k.AlignName}妫�娴嬬粨鏋滃紓甯�", "");
+                                         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);
@@ -374,15 +1156,25 @@
                                  }
                              }
 
-                             keyBindList.ForEach(kb => kb.FillKeyValues(resultDict));
+                             keyBindList.ForEach(kb =>
+                             {
+                                 kb.KeyImages.Add(image.ConvertHObjectToHImage());
+                                 kb.FillKeyValues(resultDict);
+                             });
                          });
 
                      image.Dispose();
-                 });
+                 }
+                 //);
 
-                 if (count.I != 1)
-                     imgSet.HImage.Dispose();
+                 images.Dispose();
+                 //if (count.I != 1)
+                 //{
+                 //    hImage?.Dispose();
+                 //    hImage = null;
+                 //}
              });
         }
+        #endregion
     }
 }

--
Gitblit v1.8.0