From c0b8009ef36746c7a14606267662570e8c59c2c6 Mon Sep 17 00:00:00 2001
From: xcd <834800634@qq.com>
Date: 星期四, 09 七月 2020 19:12:37 +0800
Subject: [PATCH] 部分模型修改

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

diff --git a/src/Bro.M071.Process/M071Process.cs b/src/Bro.M071.Process/M071Process.cs
index 2667c4f..1d8c532 100644
--- a/src/Bro.M071.Process/M071Process.cs
+++ b/src/Bro.M071.Process/M071Process.cs
@@ -2,8 +2,10 @@
 using Bro.Common.Helper;
 using Bro.Common.Interface;
 using Bro.Common.Model;
+using Bro.M071.Model;
 using Bro.Process;
 using HalconDotNet;
+using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
@@ -13,6 +15,7 @@
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
+using static Bro.Common.Helper.EnumHelper;
 
 namespace Bro.M071.Process
 {
@@ -33,8 +36,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()
@@ -42,10 +47,23 @@
             InitialSetting();
 
             base.Open();
+
+            SwitchBeep(false);
+            SwitchLightGreen(false);
+            SwitchLightRed(false);
+            SwitchLightYellow(false);
+
+            Reset(null, null, null);
+            FullReset(null);
         }
 
         private void InitialSetting()
         {
+            ////鏁版嵁搴撹縼绉绘鏌�
+            //DatabaseInitialize.Initialize();
+
+            MotionCardSettingCheck();
+
             Config.SnapshotPointCollection.ForEach(u =>
             {
                 u.GetHalconToolPathList().ForEach(path =>
@@ -61,21 +79,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);
             });
@@ -100,7 +118,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 =>
                           {
@@ -109,59 +127,48 @@
                     }
                     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
-
-        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 (MachineState != MachineState.Ready)
+                throw new ProcessException("鏈哄彴鏈氨缁紝璇峰嬁寮�濮嬫祴閲�", null, ExceptionLevel.Fatal);
+
             if (string.IsNullOrWhiteSpace(BarCode))
             {
+                OnClearBarcode?.Invoke();
                 throw new ProcessException("鏈緭鍏ヤ骇鍝佹潯鐮侊紝璇峰嬁寮�濮嬫祴閲�");
             }
 
+            MachineState = MachineState.Running;
             OnMeasureStart?.BeginInvoke(null, null);
 
             var measurements = Config.MeasurementUnitCollection.Where(u => u.IsEnabled).ToList().DeepSerializeClone();
@@ -174,7 +181,18 @@
             {
                 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;
@@ -183,73 +201,103 @@
                   {
                       _pauseHandle.WaitHandle.WaitOne();
 
-                      IDevice device = DeviceCollection.FirstOrDefault(u => u.Id == s.MotionDevice);
+                      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;
 
-                      //IImageSet 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;
+                      }
 
-                      HImage hImage = CollectHImage(camera, s.CameraOp.OpConfig, out string imgSetId);
-                      if (string.IsNullOrWhiteSpace(imgSetId))
+                      if (set == null)
                       {
                           return;
                       }
 
-                      RunImageHandle(camera, s.CameraOp.OpConfig, hImage, s.Id, s.Name, pMeasure.Measurements);
+                      RunImageHandle(camera, s.CameraOp.OpConfig, set, s.Id, s.Name, pMeasure.Measurements);
                   });
 
             BarCode = "";
+            LogAsync(DateTime.Now, $"{pMeasure.Barcode}娴嬮噺鍔ㄤ綔瀹屾垚", "");
+
             return new ProcessResponse(true);
         }
 
-        /// <summary>
-        /// 鏆傚仠鏍囧織  
-        /// WaitHandle 鏆傚仠鍙ユ焺  榛樿涓洪潪闃诲 鍙墽琛�
-        /// WaitResult 鏆傚仠鏍囧織 true 姝e父鎵ц  false 鏆傚仠涓�
-        /// </summary>
-        ManualWaitConfirm _pauseHandle = new ManualWaitConfirm()
+        #region 鍙屾墜鍚姩
+        bool isLeftStart = false;
+        bool IsLeftStart
         {
-            WaitHandle = new ManualResetEvent(true),
-            WaitResult = true,
-        };
-
-        [ProcessMethod("", "PauseJob", "鏆傚仠娴佺▼", InvokeType.TestInvoke)]
-        public ProcessResponse PauseJob(IOperationConfig opConfig, IDevice invokeDevice, IDevice sourceDevice)
-        {
-            if (_pauseHandle.WaitResult)
+            get => isLeftStart;
+            set
             {
-                #region 鏉垮崱鏆傚仠鍔ㄤ綔
-                #endregion
-
-                _pauseHandle.WaitHandle.Reset();
+                isLeftStart = value;
+                StartCheck();
             }
-            else
-            {
-                #region 鏉垮崱鎭㈠鍔ㄤ綔
-                #endregion
-
-                _pauseHandle.WaitHandle.Set();
-            }
-
-            _pauseHandle.WaitResult = !_pauseHandle.WaitResult;
-            return new ProcessResponse(_pauseHandle.WaitResult);
         }
+
+        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)
@@ -294,8 +342,12 @@
                                     }
                                 }
 
-                                //杈撳嚭鍥惧舰鍩哄厓鍒扮晫闈� todo
-                                OnElementUpdated?.BeginInvoke(null, null, null);
+                                LogAsync(DateTime.Now, $"{m.GetDisplayText()}妫�娴嬬粨鏋�", $"{((m.Spec.MeasureResult ?? false) ? "OK" : "NG")}");
+
+                                IShapeElement indicator = null;
+                                pMeasure.ElementList.Add(indicator);
+                                //杈撳嚭鍥惧舰鍩哄厓鍒扮晫闈� 
+                                OnElementUpdated?.BeginInvoke(indicator, null, null);
 
                                 SaveKeyImages(pMeasure.Barcode, m);
 
@@ -308,18 +360,28 @@
                     {
                         return;
                     }
-
-
-
-                    //MES杈撳嚭 todo
-
-                    //Excel鎶ヨ〃杈撳嚭 todo
-
-                    //鏁版嵁搴撲繚瀛� todo
-
-                    SaveWholeImage(pMeasure);
-                    pMeasure.Dispose();
                 }
+
+                pMeasure.EndTime = DateTime.Now;
+                bool pResult = pMeasure.Measurements.All(u => u.Spec.MeasureResult == true);
+                OnUpdateResult?.Invoke(DateTime.Now, pResult ? 1 : 0);
+                OnUpdateCT?.Invoke((float)(pMeasure.EndTime.Value - pMeasure.StartTime.Value).TotalSeconds);
+
+                LogAsync(DateTime.Now, $"{pMeasure.Barcode} 妫�娴嬪畬鎴愶紝缁撴灉 {(pResult ? "OK" : "NG")}", "");
+
+                if (MachineState == MachineState.Running)
+                    MachineState = MachineState.Ready;
+
+                //MES杈撳嚭 todo
+
+                //Excel鎶ヨ〃杈撳嚭 todo
+
+                //鏁版嵁搴撲繚瀛� todo
+
+                SaveWholeImage(pMeasure);
+
+                productionList.RemoveAll(p => p.Barcode == pMeasure.Barcode);
+                pMeasure.Dispose();
             }
         }
 
@@ -355,7 +417,7 @@
             }
         }
 
-        private void SaveKeyImages(string barCode, MeasurementUint measureUnit)
+        private void SaveKeyImages(string barCode, MeasurementUnit measureUnit)
         {
             string measureName = measureUnit.GetDisplayText();
             if (Config.ImageSaveOption.IsSaveOriginImage)
@@ -386,7 +448,7 @@
             }
         }
 
-        private async void SaveKeyImages(MeasurementUint measureUnit, string measureName, string dir)
+        private async void SaveKeyImages(MeasurementUnit measureUnit, string measureName, string dir)
         {
             await Task.Run(() =>
             {
@@ -406,7 +468,7 @@
         }
         #endregion
 
-        private async void RunImageHandle(CameraBase camera, IOperationConfig opConfig, HImage hImage, string snapshotId, string snapshotName, List<MeasurementUint> measureList)
+        private async void RunImageHandle(CameraBase camera, IOperationConfig opConfig, IImageSet imgSet, string snapshotId, string snapshotName, List<MeasurementUnit> measureList)
         {
             await Task.Run(() =>
              {
@@ -414,7 +476,8 @@
                  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 = hImage;
+                 HObject images = imgSet.HImage;
+                 LaserScanParam scanParam = JsonConvert.DeserializeObject<LaserScanParam>(imgSet.ImageData);
 
                  if (!string.IsNullOrWhiteSpace(toolKey))
                  {
@@ -426,7 +489,7 @@
                          return;
                      }
 
-                     _halconToolDict[toolKey].InputImageDic["INPUT_Image"] = hImage;
+                     _halconToolDict[toolKey].InputImageDic["INPUT_Image"] = imgSet.HImage;
                      if (!_halconToolDict[toolKey].RunProcedure(out string error))
                      {
                          LogAsync(DateTime.Now, $"{snapshotName}鍙栧浘绠楁硶寮傚父锛寋error}", "");
@@ -449,7 +512,7 @@
                  var excludeKeys = keys.Where(u => u.ImageSeq > count).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);
@@ -466,24 +529,26 @@
 
                              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;
+                                 _halconToolDict[keyToolKey].InputTupleDic["INPUT_Resolution_Z"] = scanParam.Resolution_Z;
                                  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();
                                      if (results.Count == 0 || results.Any(u => u < 0))
                                      {
-                                         LogAsync(DateTime.Now, $"{k.AlignName}妫�娴嬬粨鏋滃紓甯�", "");
+                                         LogAsync(DateTime.Now, $"{k.AliasName}妫�娴嬬粨鏋滃紓甯�", "");
                                      }
                                      else
                                      {
@@ -506,11 +571,11 @@
                      image.Dispose();
                  });
 
-                 if (count.I != 1)
-                 {
-                     hImage?.Dispose();
-                     hImage = null;
-                 }
+                 //if (count.I != 1)
+                 //{
+                 //    hImage?.Dispose();
+                 //    hImage = null;
+                 //}
              });
         }
         #endregion

--
Gitblit v1.8.0