From eafdcc5ad6a55d3dfdec6c4787c3f3a9f32efc7f Mon Sep 17 00:00:00 2001
From: xcd <834800634@qq.com>
Date: 星期二, 29 九月 2020 13:27:50 +0800
Subject: [PATCH] 1. M071B机台配置 2. GTS板卡添加回原点捕获模式和输入信号模式 3. CameraBase使用Dictionary类型做图片缓存 4. M071流程显式Copy,原来是为了避免内存泄漏,但目前来看不是这方面原因 5. Gocator驱动添加GoDataSet之类KObject资源显式回收,怀疑其中也有非托管对象资源,测试确实起到内存回收作用

---
 src/Bro.M071.Process/M071Process.cs |  314 +++++++++++++++++++++++++++++----------------------
 1 files changed, 177 insertions(+), 137 deletions(-)

diff --git a/src/Bro.M071.Process/M071Process.cs b/src/Bro.M071.Process/M071Process.cs
index 7847649..a382503 100644
--- a/src/Bro.M071.Process/M071Process.cs
+++ b/src/Bro.M071.Process/M071Process.cs
@@ -48,6 +48,9 @@
         public event Action OnFullResetDone;
         #endregion
 
+        string _precision = "f3";
+
+
         public override void Open()
         {
             InitialSetting();
@@ -63,6 +66,11 @@
 
             Reset(null, null, null);
             FullReset(null);
+
+            if (Config.Precision > 0)
+            {
+                _precision = "f" + Config.Precision;
+            }
         }
 
         private void InitialMotionCardBaseAxisAlarm()
@@ -199,10 +207,18 @@
             MachineState = MachineState.Running;
             OnMeasureStart?.Invoke();
 
-            var measurements = Config.MeasurementUnitCollection.Where(u => u.IsEnabled).ToList().DeepSerializeClone();
-            measurements.ForEach(m =>
+            //var measurements = Config.MeasurementUnitCollection.Where(u => u.IsEnabled).ToList().DeepSerializeClone();
+            //measurements.ForEach(m =>
+            //{
+            //    m.InitialKeyUnitMeasureChanged();
+            //});
+
+            List<MeasurementUnit> measurements = new List<MeasurementUnit>();
+            Config.MeasurementUnitCollection.Where(u => u.IsEnabled).ToList().ForEach(u =>
             {
+                var m = u.Copy();
                 m.InitialKeyUnitMeasureChanged();
+                measurements.Add(m);
             });
 
             var pMeasure = new ProductionMeasurement()
@@ -211,6 +227,8 @@
                 Measurements = measurements,
                 StartTime = DateTime.Now,
             };
+
+            BarCode = "";
 
             var existedProduction = productionList.FirstOrDefault(u => u.Barcode == pMeasure.Barcode);
             if (existedProduction != null)
@@ -275,8 +293,9 @@
                       RunImageHandle(s.CameraOp.OpConfig, set, s.Id, s.Name, pMeasure.Measurements);
                   });
 
-            BarCode = "";
             LogAsync(DateTime.Now, $"{pMeasure.Barcode}娴嬮噺鍔ㄤ綔瀹屾垚", "");
+            
+            GC.Collect(0, GCCollectionMode.Optimized);
 
             return new ProcessResponse(true);
         }
@@ -367,17 +386,28 @@
                                     }
                                     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))
+                                        //var array = m.KeyUnitCollection.SelectMany(u => u.MeasureValueDict.Values.ToList().ConvertAll(v => v ?? -999)).ToArray();
+                                        var array = m.KeyUnitCollection.SelectMany(u => u.MeasureValueDict.Values.Select(v => v ?? -999)).ToArray();
+
+                                        if (array == null || array.Length == 0)
                                         {
-                                            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 = 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"))}", "");
+
+                                            _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(_precision));
+                                                //LogAsync(DateTime.Now, $"{m.GetDisplayText()}鏁版嵁{m.Spec.ActualValue}锛岀粨鏋渰(m.Spec.MeasureResult == null ? "TBD" : (m.Spec.MeasureResult == true ? "OK" : "NG"))}", "");
+                                            }
                                         }
                                     }
                                 }
@@ -385,7 +415,7 @@
                                 //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.Text = (m.Spec.ActualValue == null || m.Spec.ActualValue == -999) ? "NA" : m.Spec.ActualValue.Value.ToString(_precision);
                                 indicator.ResultState = m.Spec.MeasureResult;
                                 pMeasure.ElementList.Add(indicator);
                                 //杈撳嚭鍥惧舰鍩哄厓鍒扮晫闈� 
@@ -433,6 +463,7 @@
 
                 productionList.RemoveAll(p => p.Barcode == pMeasure.Barcode);
                 pMeasure.Dispose();
+                //LogAsync(DateTime.Now, $"{pMeasure.Barcode}浜у搧淇℃伅閲婃斁瀹屾垚", JsonConvert.SerializeObject(pMeasure));
             }
         }
 
@@ -517,7 +548,7 @@
                         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.MeasurementValue = measurementUnit.Spec.ActualValue == null ? "NA" : measurementUnit.Spec.ActualValue.Value.ToString(_precision);
                     measurementUnitResult.MeasurementResult = measurementUnit.Spec.MeasureResult.Value ? "OK" : "NG";
 
                     measurementUnitResults.Add(measurementUnitResult);
@@ -533,7 +564,7 @@
                                 keyUnitData.ProductionBarcode = productionMeasurementRecords.ProductionBarcode;
                                 keyUnitData.Key = keyUnit.Key;
                                 keyUnitData.MeasurementItem = keyValue.Key;
-                                keyUnitData.ItemValue = keyValue.Value == null ? "NA" : keyValue.Value.Value.ToString("f2");
+                                keyUnitData.ItemValue = keyValue.Value == null ? "NA" : keyValue.Value.Value.ToString(_precision);
                                 keyUnitDatas.Add(keyUnitData);
 
                                 MeasurementAndKeyDataRelation measurementAndKeyDataRelation = new MeasurementAndKeyDataRelation();
@@ -710,8 +741,6 @@
 
                         #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;
@@ -757,12 +786,7 @@
                         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);
@@ -770,10 +794,6 @@
                             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 =>
                             {
@@ -918,6 +938,11 @@
                         #endregion
 
                         package.Save();
+
+                        rawDataSheet.Dispose();
+                        slantSheet.Dispose();
+                        alignmentSheet.Dispose();
+                        rowAlignmentSheet.Dispose();
                     };
                 }
             });
@@ -1042,138 +1067,153 @@
         private async void RunImageHandle(IOperationConfig opConfig, IImageSet imgSet, string snapshotId, string snapshotName, List<MeasurementUnit> measureList)
         {
             await Task.Run(() =>
-             {
-                 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();
+            {
+                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();
 
-                 string toolKey = (opConfig as CameraOprerationConfigBase).AlgorithemPath;
-                 //HObject images = imgSet.HImage;
+                string toolKey = (opConfig as CameraOprerationConfigBase).AlgorithemPath;
+                //HObject images = imgSet.HImage;
 
-                 HObject images = new HObject();
-                 LaserScanParam scanParam = JsonConvert.DeserializeObject<LaserScanParam>(imgSet.ImageData);
-                 LogAsync(DateTime.Now, $"鎵弿鍙傛暟:{imgSet.ImageData}", "");
+                HObject images = new HObject();
+                LaserScanParam scanParam = JsonConvert.DeserializeObject<LaserScanParam>(imgSet.ImageData);
+                LogAsync(DateTime.Now, $"鎵弿鍙傛暟:{imgSet.ImageData}", "");
 
-                 if (!string.IsNullOrWhiteSpace(toolKey))
-                 {
-                     toolKey = snapshotId + "|" + toolKey;
-                     if (!_halconToolDict.ContainsKey(toolKey))
-                     {
-                         LogAsync(DateTime.Now, $"{snapshotName}鏈垵濮嬪寲鍙栧浘绠楁硶閰嶇疆", "");
-                         keyBindCollection.ForEach(k => k.FillKeyValues(null));
-                         return;
-                     }
+                if (!string.IsNullOrWhiteSpace(toolKey))
+                {
+                    toolKey = snapshotId + "|" + toolKey;
+                    if (!_halconToolDict.ContainsKey(toolKey))
+                    {
+                        LogAsync(DateTime.Now, $"{snapshotName}鏈垵濮嬪寲鍙栧浘绠楁硶閰嶇疆", "");
+                        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);
+                    //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))
-                     {
-                         LogAsync(DateTime.Now, $"{snapshotName}鍙栧浘绠楁硶寮傚父锛寋error}", "");
-                         keyBindCollection.ForEach(k => k.FillKeyValues(null));
-                         return;
-                     }
+                    if (imgSet.HImage == null)
+                    {
+                        LogAsync(DateTime.Now, $"{snapshotName}鍥剧墖涓虹┖瀵硅薄", "");
+                        keyBindCollection.ForEach(k => k.FillKeyValues(null));
+                        return;
+                    }
 
-                     images = _halconToolDict[toolKey].GetResultObject("OUTPUT_Images");
-                 }
+                    _halconToolDict[toolKey].InputImageDic["INPUT_Image"] = imgSet.HImage;
+                    if (!_halconToolDict[toolKey].RunProcedure(out string error))
+                    {
+                        LogAsync(DateTime.Now, $"{snapshotName}鍙栧浘绠楁硶寮傚父锛寋error}", "");
+                        keyBindCollection.ForEach(k => k.FillKeyValues(null));
+                        return;
+                    }
 
-                 HOperatorSet.CountObj(images, out HTuple count);
-                 LogAsync(DateTime.Now, $"{snapshotName}鍒囧浘{count.I}寮�", "");
+                    images = _halconToolDict[toolKey].GetResultObject("OUTPUT_Images");
+                }
 
-                 if (count == 0)
-                 {
-                     LogAsync(DateTime.Now, $"{snapshotName}鍙栧浘绠楁硶鏈緭鍑哄浘鍍�", "");
-                     keyBindCollection.ForEach(k => k.FillKeyValues(null));
-                     return;
-                 }
+                HOperatorSet.CountObj(images, out HTuple count);
+                LogAsync(DateTime.Now, $"{snapshotName}鍒囧浘{count.I}寮�", "");
 
-                 var excludeKeys = keys.Where(u => u.ImageSeq > count.I).ToList();
-                 if (excludeKeys.Count > 0)
-                 {
-                     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);
-                          });
-                 }
+                if (count == 0)
+                {
+                    LogAsync(DateTime.Now, $"{snapshotName}鍙栧浘绠楁硶鏈緭鍑哄浘鍍�", "");
+                    keyBindCollection.ForEach(k => k.FillKeyValues(null));
+                    return;
+                }
 
-                 //string dir = Path.Combine(Config.ImageSaveFolder, "Clips", $"{DateTime.Now.ToString("yyyyMMdd")}", $"{snapshotName}_{DateTime.Now.ToString("HHmmss")}");
-                 //if (!Directory.Exists(dir))
-                 //{
-                 //    Directory.CreateDirectory(dir);
-                 //}
+                var excludeKeys = keys.Where(u => u.ImageSeq > count.I).ToList();
+                if (excludeKeys.Count > 0)
+                {
+                    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 + 1, (i) =>
-                 for (int i = 1; i <= count.I; i++)
-                 {
-                     HOperatorSet.SelectObj(images, out HObject image, i);
+                //string dir = Path.Combine(Config.ImageSaveFolder, "Clips", $"{DateTime.Now.ToString("yyyyMMdd")}", $"{snapshotName}_{DateTime.Now.ToString("HHmmss")}");
+                //if (!Directory.Exists(dir))
+                //{
+                //    Directory.CreateDirectory(dir);
+                //}
 
-                     //string fileName = Path.Combine(dir, $"{i}.tif");
-                     //using (HImage temp = image.ConvertHObjectToHImage())
-                     //{
-                     //    temp.WriteImage("tiff", 0, fileName);
-                     //}
+                //Parallel.For(1, count.I + 1, (i) =>
+                for (int i = 1; i <= count.I; i++)
+                {
+                    HOperatorSet.SelectObj(images, out HObject image, i);
 
-                     keys.Where(u => u.ImageSeq == i).ToList().ForEach(k =>
-                         {
-                             Dictionary<string, double> resultDict = null;
+                    //string fileName = Path.Combine(dir, $"{i}.tif");
+                    //using (HImage temp = image.ConvertHObjectToHImage())
+                    //{
+                    //    temp.WriteImage("tiff", 0, fileName);
+                    //}
 
-                             var keyBindList = keyBindCollection.Where(u => u.Key == k.Key).ToList();
+                    keys.Where(u => u.ImageSeq == i).ToList().ForEach(k =>
+                    {
+                        Dictionary<string, double> resultDict = null;
 
-                             string keyToolKey = k.AliasName + "|" + k.KeyAlgorithemPath;
-                             if (!_halconToolDict.ContainsKey(keyToolKey))
-                             {
-                                 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.AliasName}妫�娴嬬畻娉曞紓甯革紝{error}", "");
-                                 }
-                                 else
-                                 {
-                                     var results = _halconToolDict[keyToolKey].GetResultTuple("OUTPUT_Results").DArr.ToList();
-                                     if (results.Count == 0 || results.Any(u => u < 0))
-                                     {
-                                         LogAsync(DateTime.Now, $"{k.AliasName}鍘熷鏁版嵁寮傚父", "");
-                                     }
-                                     else
-                                     {
-                                         //LogAsync(DateTime.Now, $"{k.AliasName}鍘熷鏁版嵁", $"{string.Join(" ", results)}");
+                        var keyBindList = keyBindCollection.Where(u => u.Key == k.Key).ToList();
 
-                                         results = results.Select(u => u - Config.PlanCompensation).ToList();
-                                         resultDict = k.KeyResultList.ToDictionary(u => u, u =>
-                                              {
-                                                  int index = k.KeyResultList.IndexOf(u);
-                                                  return results[index];
-                                              });
-                                     }
-                                 }
-                             }
+                        string keyToolKey = k.AliasName + "|" + k.KeyAlgorithemPath;
+                        if (!_halconToolDict.ContainsKey(keyToolKey))
+                        {
+                            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))
+                            {
+                                LogAsync(DateTime.Now, $"{k.AliasName}妫�娴嬬畻娉曞紓甯革紝{error}", "");
+                            }
+                            else
+                            {
+                                var results = _halconToolDict[keyToolKey].GetResultTuple("OUTPUT_Results").DArr.ToList();
+                                if (results.Count == 0 || results.Any(u => u < 0))
+                                {
+                                    LogAsync(DateTime.Now, $"{k.AliasName}鍘熷鏁版嵁寮傚父", "");
+                                }
+                                else
+                                {
+                                    //LogAsync(DateTime.Now, $"{k.AliasName}鍘熷鏁版嵁", $"{string.Join(" ", results)}");
 
-                             keyBindList.ForEach(kb =>
-                             {
-                                 kb.KeyImages.Add(image.ConvertHObjectToHImage());
-                                 kb.FillKeyValues(resultDict);
-                             });
-                         });
+                                    results = results.Select(u => u - Config.PlanCompensation).ToList();
+                                    resultDict = k.KeyResultList.ToDictionary(u => u, u =>
+                                    {
+                                        int index = k.KeyResultList.IndexOf(u);
+                                        return results[index];
+                                    });
+                                }
+                            }
+                        }
 
-                     image.Dispose();
-                 }
-                 //);
+                        keyBindList.ForEach(kb =>
+                        {
+                            kb.KeyImages.Add(image.ConvertHObjectToHImage());
+                            kb.FillKeyValues(resultDict);
+                        });
+                    });
 
-                 images.Dispose();
-                 //if (count.I != 1)
-                 //{
-                 //    hImage?.Dispose();
-                 //    hImage = null;
-                 //}
-             });
+                    image.Dispose();
+                    image = null;
+                }
+                //);
+
+                imgSet.HImage.Dispose();
+                imgSet.HImage = null;
+                imgSet.Dispose();
+
+                images.Dispose();
+                images = null;
+
+                //if (count.I != 1)
+                //{
+                //    hImage?.Dispose();
+                //    hImage = null;
+                //}
+            });
         }
         #endregion
     }

--
Gitblit v1.8.0