From 6a4463810e276b62356d77c88509fa6fa7af65cf Mon Sep 17 00:00:00 2001
From: kingno <30263@KINGNO>
Date: 星期三, 23 七月 2025 15:46:33 +0800
Subject: [PATCH] mes数据逻辑上传完善,缺陷代码完善,添加S4工位的S2结果上传Plc的通信日志mes优化

---
 src/Bro.M141.Process/M141Process.cs |  631 ++++++++++++++++++++++++++++++++++++++++++++++++++-------
 1 files changed, 553 insertions(+), 78 deletions(-)

diff --git a/src/Bro.M141.Process/M141Process.cs b/src/Bro.M141.Process/M141Process.cs
index 91e0e62..7d7fa09 100644
--- a/src/Bro.M141.Process/M141Process.cs
+++ b/src/Bro.M141.Process/M141Process.cs
@@ -17,12 +17,17 @@
 using ScottPlot.Drawing.Colormaps;
 using Sunny.UI;
 using Sunny.UI.Win32;
+using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Drawing.Imaging;
 using System.IO;
 using System.Linq;
+using System.Text;
 using Windows.ApplicationModel.Appointments;
+using ZXing;
+using static Bro.Common.Helper.EnumHelper;
+using static Bro.Process.ProcessControl;
 using static Org.BouncyCastle.Math.EC.ECCurve;
 
 namespace Bro.M141.Process
@@ -34,28 +39,41 @@
 
         public M141Process(string productCode) : base(productCode) { }
         #endregion
+
         TaskFactory _taskFactory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning);
+
         public event Action<string, P_PRODUCT_DETAIL, string> OnSinglePostionDetectResultUpdate;
+
         protected M141Config M141Config => Config as M141Config;
 
         public static object _productListLock = new object();
         public List<ProductModel> ProductList = new List<ProductModel>();
         MachineLearningBase ML = null;
-        TcpListenerWrap TcpListener = null;
         Spec _errorSpec = null;
 
-        TcpListenerWrap _realTimeServer = null;
+        //volatile int _productIndex = 0;
 
-        volatile int _productIndex = 0;
+        public M141Process_Mysql mysqlhelper = new M141Process_Mysql();
 
-        int _backgroundImageWidth = 2448;
+        public event Action RerefreshBasketcodeUI;
 
-        M141Process_Mysql mysqlhelper = new M141Process_Mysql();
+        public void RerefreshBasketcode()
+        {
+            RerefreshBasketcodeUI?.Invoke();
+        }
+
+
 
         public override void InitialProcessMethods()
         {
             base.InitialProcessMethods();
 
+            if (ThHeartPlc == null)
+            {
+                ThHeartPlc = new Thread(Heartplc);
+                ThHeartPlc.IsBackground = true;
+                ThHeartPlc.Start();
+            }
         }
 
         public override void ProcessRunStateChanged()
@@ -72,11 +90,19 @@
         }
 
         public PLCBase Plc1;
-        Thread ThHeartPlc;
+        bool devicestate = false;
+        PLCBase Plc2;
+        public Thread ThHeartPlc;
+
+        public RabbitMQHelper mqtt;
+
+
+
         public override void Open()
         {
             base.Open();
 
+            devicestate = true;
             ML = DeviceCollection.FirstOrDefault(u => u is MachineLearningBase) as MachineLearningBase;
             if (ML == null)
             {
@@ -97,43 +123,132 @@
             _positionCheckTimeDict.Clear();
             _positionSpecHeads.Clear();
 
+            mysqlhelper.IniDBIP(M141Config.IPforall);
+            RerefreshBasketcode();
 
-            if (ThHeartPlc == null)
+
+            if (M141Config.ISupMES)
             {
-                ThHeartPlc = new Thread(Heartplc);
-                ThHeartPlc.IsBackground = true;
-                ThHeartPlc.Start();
+                mqtt = new RabbitMQHelper(M141Config.zIP, M141Config.zport, M141Config.zuser, M141Config.zpassword);
+                mqtt.Connect(M141Config.MESchannel);
             }
+
+
         }
 
 
         public override void Close()
         {
+            devicestate = false;
             base.Close();
-            try
-            {
-                if (ThHeartPlc != null)
-                {
-                    ThHeartPlc.Abort();
-                }
 
-            }
-            catch
-            {
-
-            }
-            ThHeartPlc = null;
         }
+
 
         public void Heartplc()
         {
-            while (true)
+            Thread.Sleep(1000);
+
+            //Open();
+
+            string _statisticFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Statistic.json");
+            if (File.Exists(_statisticFilePath))
             {
                 try
                 {
-                    if (Plc1 != null)
+                    string dataStr = "";
+                    using (StreamReader reader = new StreamReader(_statisticFilePath, System.Text.Encoding.UTF8))
                     {
-                        Plc1.WriteSingleAddress(1505, 0, out _);
+                        dataStr = reader.ReadToEnd();
+                    }
+
+                    lock (StatisticRecordsFull)
+                    {
+                        var temRecords = JsonConvert.DeserializeObject<StatisticRecords_Full>(dataStr);
+                        if (StatisticRecordsFull != null && temRecords != null)
+                        {
+                            StatisticRecordsFull.CurRecord = temRecords.CurRecord;
+                            StatisticRecordsFull.HistoryRecord = temRecords.HistoryRecord;
+                        }
+                    }
+                }
+                catch (Exception ex)
+                {
+                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"浜у搧缁熻淇℃伅鍙嶅簭鍒楀寲寮傚父");
+                    StatisticRecordsFull = new StatisticRecords_Full();
+                }
+            }
+
+            int numsum = 0;
+            //List<int> Statelist = new List<int>();
+
+
+            Dictionary<string, List<int>> StateDIC = new Dictionary<string, List<int>>();
+            int numplc = 0;
+            while (true)
+            {
+                numplc++;
+                numsum++;
+
+
+                if (!devicestate)
+                {
+                    Thread.Sleep(1000);
+                    continue;
+                }
+                try
+                {
+                    if (M141Config.WorkShiftList != null && M141Config.WorkShiftList.Count > 0 && numsum >= 0)
+                    {
+                        for (int i = 0; i < M141Config.WorkShiftList.Count; i++)
+                        {
+                            if (M141Config.WorkShiftList[i].IsClearProductSummary)
+                            {
+                                double timeshap = (DateTime.Now - M141Config.WorkShiftList[i].ShiftTime_Start).TotalMinutes % 1440;
+
+                                if (timeshap > 0 && timeshap < 1)
+                                {
+                                    StatisticRecordsFull.CurRecord.ProductSummary.RecordsList.Clear();
+                                    StatisticRecordsFull.CurRecord.DefectSummary.RecordsList.Clear();
+                                    numsum = -62;
+                                }
+                            }
+                        }
+                    }
+
+                    lock (StatisticRecordsFull)
+                    {
+                        if (numsum > 20)
+                        {
+                            numsum = 0;
+                            using (FileStream fileStream = new FileStream(_statisticFilePath, FileMode.OpenOrCreate, FileAccess.Write))
+                            {
+                                fileStream.Seek(0L, SeekOrigin.Begin);
+                                string s = JsonConvert.SerializeObject(StatisticRecordsFull);
+                                byte[] bytes = Encoding.UTF8.GetBytes(s);
+                                fileStream.Write(bytes, 0, bytes.Length);
+                                fileStream.SetLength(bytes.Length);
+                                fileStream.Flush();
+                                fileStream.Close();
+                            }
+                        }
+                    }
+                }
+                catch (Exception ex)
+                {
+
+                }
+
+
+                try
+                {
+                    if (numplc > 3)
+                    {
+                        numplc = 0;
+                        if (Plc1 != null)
+                        {
+                            Plc1.WriteSingleAddress(M141Config.heartadd, 0, out _);
+                        }
                     }
                 }
                 catch
@@ -141,10 +256,114 @@
 
                 }
 
-                Thread.Sleep(3000);
+
+                try
+                {
+                    string csvhead = "鏃堕棿";
+                    string csvdata = DateTime.Now.ToString("yyyyMMddHHmmss") + "T";
+
+                    if (Plc1 != null)
+                    {
+                        foreach (var item1 in M141Config.PLCAlarm)
+                        {
+                            try
+                            {
+                                if (!item1.isused)
+                                {
+                                    continue;
+                                }
+
+                                var alrams = item1.AlarmDetails;
+                                var plcdev = DeviceCollection.FirstOrDefault(u => u.Id == item1.plcname) as PLCBase;
+
+                                if (!StateDIC.ContainsKey(plcdev.Name))
+                                {
+                                    StateDIC[plcdev.Name] = new List<int>();
+                                }
+
+                                foreach (var item in alrams.GroupBy(u => u.address))
+                                {
+                                    int add = item.Key;
+                                    var readres = plcdev.Read(add, 1, out _)[0];
+
+                                    var Allbin = Convert.ToString(readres, 2).PadLeft(16, '0').Select(c => c - '0').ToArray();
+
+                                    Allbin = Allbin.Reverse().ToArray();
+
+                                    foreach (var item2 in item)
+                                    {
+                                        item2.value = Allbin[item2.address2];
+                                    }
+                                }
+                                List<int> list = new List<int>();
+                                foreach (var item in alrams)
+                                {
+                                    csvhead += $",{item.alarmname}";
+                                    csvdata += $",{(item.value == 1 ? "1" : "")}";
+                                    list.Add(item.value);
+                                }
+
+                                if (!StateDIC[plcdev.Name].SequenceEqual(list))
+                                {
+                                    StateDIC[plcdev.Name].Clear();
+                                    StateDIC[plcdev.Name].AddRange(list);
+
+                                    CSVRecordAsync($"PLCstate_{plcdev.Name}.csv", csvdata, csvhead);
+
+                                    var showdata = alrams.Where(u => u.value == 1).Select(u => u.alarmname).ToList();
+
+                                    if (showdata == null)
+                                    {
+                                        showdata = new List<string>();
+                                    }
+
+                                    if (showdata.Count > 0)
+                                    {
+                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"{plcdev.Name}鎶ヨ 涓暟:{showdata.Count}  {string.Join(',', showdata)}");
+                                    }
+                                    else
+                                    {
+                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{plcdev.Name}鎶ヨ 涓暟:0");
+                                    }
+                                }
+                            }
+                            catch
+                            {
+
+                            }
+                        }
+                    }
+
+                }
+                catch
+                {
+
+                }
+
+
+
+                try
+                {
+                    if (Plc1 != null)
+                    {
+                        DateTime dt = DateTime.Now;
+                        Plc1.WriteSingleAddress(10, dt.Year, out _);
+                        Plc1.WriteSingleAddress(11, dt.Month, out _);
+                        Plc1.WriteSingleAddress(12, dt.Day, out _);
+                        Plc1.WriteSingleAddress(13, dt.Hour, out _);
+                        Plc1.WriteSingleAddress(14, dt.Minute, out _);
+                        Plc1.WriteSingleAddress(15, dt.Second, out _);
+                        Plc1.WriteSingleAddress(16, (int)dt.DayOfWeek, out _);
+                    }
+                }
+                catch
+                {
+
+                }
+
+                Thread.Sleep(1000);
             }
         }
-
 
         /// <summary>
         /// 缃戠粶棰勭儹
@@ -152,7 +371,6 @@
         /// <exception cref="NotImplementedException"></exception>
         private void NetWarmUp()
         {
-
             string warmUpImageFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WarmUp");
             if (!Directory.Exists(warmUpImageFolder))
             {
@@ -244,8 +462,6 @@
         Dictionary<string, List<string>> _positionSpecHeads = new Dictionary<string, List<string>>();
 
 
-
-
         volatile int uploadId = 0;
 
 
@@ -294,9 +510,8 @@
                     p.PID = p.PID + "_" + sequence.Split('_')[sequence.Split('_').Length - 1];
 
                     p.Initial(M141Config.StationCode, M141Config.WorkPositionCollection.Where(u => u.IsEnabled).Select(u => u.PositionName).ToList());
-                    //LogAsync(DateTime.Now, EnumHelper.LogLevel.Warning, $"鏈兘浠庢暟鎹簱鑾峰彇浜у搧瀵硅薄锛屼娇鐢ㄤ复鏃舵柊寤轰骇鍝佸璞�");
+                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Warning, $"鏈兘浠庢暟鎹簱鑾峰彇浜у搧瀵硅薄锛屼娇鐢ㄤ复鏃舵柊寤轰骇鍝佸璞�   {sequence}");
                 }
-
                 NewProductIntoList(p, false);
             }
 
@@ -324,33 +539,63 @@
                         throw new Exception($"浜у搧{string.Join(",", pidList)}妫�娴媨measureBind.GetDisplayText()}鏈兘鑾峰彇鍥剧墖瀵硅薄");
                     }
 
+                    RunCustomizedMethod(products, triggerText, triggerSource, imgSet, measureBind.CustomizedMonitorId, resultList);
+                    RunCustomizedMethod(products, triggerText, triggerSource, imgSet, measureBind.CustomizedCombineMethodId, resultList);
+
                     //妫�娴嬮『搴� ML->鑷畾涔夋娴�
                     if (!string.IsNullOrWhiteSpace(measureBind.DetectionId))
                     {
                         string detectionName = (ML.InitialConfig as MLInitialConfigBase).DetectionConfigs.FirstOrDefault(u => u.Id == measureBind.DetectionId)?.Name;
 
-
-                        //List<string> pidList2 = new List<string>();//pidList.Select(u => u.Split('_')[u.Split('_').Length - 1]).ToList();
-                        //Dictionary<string, string> dicpid = new Dictionary<string, string>();
-
-                        //for (int i = 0; i < pidList.Count; i++)
-                        //{
-                        //    var tem = pidList[i].Split('_')[pidList[i].Split('_').Length - 1];
-                        //    pidList2.Add(tem);
-                        //    dicpid[tem] = pidList[i];
-                        //}
+                        List<DetectResult> detectResults = ML?.RunMLDetectionSync(imgSet, pidList, measureBind.DetectionId, false, null, null, "", products[0].ImagePaths);
 
 
-                        List<DetectResult> detectResults = ML?.RunMLDetectionSync(imgSet, pidList, measureBind.DetectionId);
+
+                        if (measureBind.WorkPosition == "P1" && M141Config.StationCode == "S5" && detectResults.GetDefectDescList().Count == 0)
+                        {
+                            var defecttem = detectResults.SelectMany(u => u.AllNetResults.SelectMany(m => m.DetectDetails)).Where(u => u.ClassName == M141Config.defectname).ToList();
+
+                            List<Netdefectdetail> Netdefectdetails = mysqlhelper.GetNetdefectdetails(products[0].SEQUENCE);
+
+                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5妫�娴� S3鏁版嵁{Netdefectdetails.Count}  S5鏁版嵁{defecttem.Count}");
+
+                            Netdefectdetails.ForEach(x =>
+                            {
+                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5妫�娴� S3鏁版嵁{x.name}  {x.centerX},{x.centerY} ");
+                            });
+
+                            int num = 0;
+                            foreach (var item1 in defecttem)
+                            {
+                                double x1 = item1.Rect.Point_LU.X + item1.Rect.Width / 2.0;
+                                double y1 = item1.Rect.Point_LU.Y + item1.Rect.Height / 2.0;
+                                num++;
+
+                                //HOperatorSet.AffineTransPoint2d(new HTuple(products[0].Centermatrix.ToArray()), x1, y1, out HTuple qx, out HTuple qy);
+                                //HOperatorSet.ProjectiveTransPixel(new HTuple(products[0].Centermatrix.ToArray()), x1, y1, out HTuple qx, out HTuple qy);
+
+                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5妫�娴�  鍘熷潗鏍噞num}   {x1},{y1}");
+                                HOperatorSet.ProjectiveTransPixel(new HTuple(products[0].Centermatrix.ToArray()), x1, y1, out HTuple qx, out HTuple qy);
+                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5妫�娴�  鏂板潗鏍噞num}   {qx},{qy}");
+
+
+                                Netdefectdetail temc = new Netdefectdetail()
+                                {
+                                    centerX = qx,
+                                    centerY = qy,
+                                    name = M141Config.defectname,
+                                };
+                                if (Netdefectdetails.Any(u => u == temc))
+                                {
+                                    item1.IsAbandoned = false;
+                                    item1.FinalResult = ResultState.NG;
+                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"浜у搧{products[0].PID}_{products[0].SEQUENCE}宸ヤ綅{measureBind.WorkPosition}   S3S5缁勫悎妫�娴嬫鍑虹己闄�:{item1.NetName}");
+                                    break;
+                                }
+                            }
+                        }
+
                         List<DetectResult> ngResults = new List<DetectResult>();
-
-
-                        //for (int i = 0; i < detectResults.Count; i++)
-                        //{
-                        //    detectResults[i].PID = dicpid[detectResults[i].PID];
-                        //}
-
-
                         detectResults.GroupBy(u => u.PID).ToList().ForEach(u =>
                         {
                             if (u.ToList().Count > 0 && u.ToList().Any(m => m.ResultState != EnumHelper.ResultState.OK))
@@ -360,21 +605,14 @@
                                     var errorSpec = _errorSpec.Copy();
                                     errorSpec.Code = "妫�娴婽BD";
                                     errorSpec.ActualValue = -999;
-                                    DetectResult ngResult = new DetectResult() { Specs = new List<ISpec>() { errorSpec }, PID = u.Key };
+                                    DetectResult ngResult = new DetectResult() { Specs = new List<ISpec>() { errorSpec }, PID = u.Key, Id = Guid.NewGuid().ToString() };
                                     ngResults.Add(ngResult);
                                 }
                             }
                         });
-
                         detectResults.AddRange(ngResults);
                         resultList.AddRange(detectResults);
-
-
                     }
-
-
-                    RunCustomizedMethod(products, triggerText, triggerSource, imgSet, measureBind.CustomizedMonitorId, resultList);
-                    RunCustomizedMethod(products, triggerText, triggerSource, imgSet, measureBind.CustomizedCombineMethodId, resultList);
 
                 }
                 catch (Exception ex)
@@ -598,7 +836,7 @@
                         {
                             products.ForEach(p =>
                             {
-                                var pResults = resultList.Where(u => u.PID == p.PID).ToList();
+                                var pResults = resultList.ToList();
                                 p.AddNewDetectResults(M141Config.StationCode, measureBind.WorkPosition, pResults);
                                 LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"浜у搧{p.PID}_{p.SEQUENCE}娣诲姞宸ヤ綅{measureBind.WorkPosition}妫�娴嬬粨鏋滐紝鏁伴噺{pResults.Count}");
                             });
@@ -704,6 +942,7 @@
             try
             {
                 ConcurrentDictionary<MeasureBind, IImageSet> imgSetDicts = new ConcurrentDictionary<MeasureBind, IImageSet>();
+                var positionSet = M141Config.WorkPositionCollection.Where(u => u.IsEnabled).FirstOrDefault(u => u.TriggerValue == triggerDatas[0]);
 
                 measureBinds.AsParallel().ForAll(b =>
                 {
@@ -715,6 +954,10 @@
                         try
                         {
                             imgSetDicts[b] = CollectHImage(camera, b.SnapshotOpConfig);
+                            if (positionSet.ispiccover)
+                            {
+                                Plc1.WriteSingleAddress(positionSet.plcover, 1, out _);
+                            }
                         }
                         catch (Exception ea)
                         {
@@ -815,6 +1058,23 @@
                     p.SEQUENCE = $"{tempSequence}_{i}";
                     p.PID = $"{pidstr}T_{i}";
 
+                    if (M141Config.Isreadbasketcode)
+                    {
+                        p.BasketCode = M141Config.basketcode;
+                        p.Zword = M141Config.zwoid;
+                    }
+                    else
+                    {
+                        p.BasketCode = mysqlhelper.Getbasketcode(p.SEQUENCE, out string sntem, out string zword);
+                        p.Zword = zword;
+                        p.SN = sntem;
+                        p.PID = $"{sntem}_{i}";
+                        if ("NoRead".Equals(p.BasketCode))
+                        {
+                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{p.PID}_{p.SEQUENCE}鑾峰彇妗嗗叿鐮佸け璐� 璧嬪�糔oread");
+                        }
+                    }
+
                     if (positionSet.IsLastPosition)
                     {
                         p.Initial(M141Config.StationCode, new List<string>() { positionSet.PositionName });
@@ -827,9 +1087,9 @@
                 });
             });
 
+            Thread.Sleep(50);
 
             int de = 0;
-
             measureBinds.Where(b => (b.CheckIndex == de || b.CheckIndex == 1) && b.ImageIndex == 0).AsParallel().ForAll(b =>
             {
                 List<int> temint = new List<int>();
@@ -843,8 +1103,9 @@
 
                     //鍒濆鍖栦骇鍝佺殑妫�娴嬫鏁�
                     var checkIndexList = M141Config.MeasureBindCollection.Where(u => u.WorkPosition == b.WorkPosition && u.ProductIndices.Contains(i)).Select(u => u.CheckIndex).OrderBy(u => u).ToList();
-                    p.InitialPositionCheckList(b.WorkPosition, checkIndexList);
+                    p.InitialPositionCheckList(b.WorkPosition, checkIndexList, M141Config.StationCode);
                     LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧{p.PID}_{p.SEQUENCE}宸叉竻鐞唟b.WorkPosition}妫�娴嬫暟鎹�傚綋鍓嶅凡瀹屾垚宸ヤ綅{string.Join(",", p.Details.Select(u => u.PositionName))}");
+
                 });
 
                 //鍒濆鍖栧伐浣嶇殑妫�娴嬫鏁�
@@ -930,34 +1191,46 @@
                         plcresult.Add(isOK);
                         List<string> specHeads = new List<string>();
                         string head = p.GetCSVHead(ref specHeads, positionName);
-                        if (!_positionSpecHeads.ContainsKey(positionName))
-                        {
-                            _positionSpecHeads[positionName] = specHeads;
-                        }
 
-                        string data = p.GetCSVData(_positionSpecHeads[positionName], positionName);
+                        //_positionSpecHeads[positionName] = specHeads;
+
+                        string data = p.GetCSVData(specHeads, positionName);
                         CSVRecordAsync($"{positionName}_Record_{DateTime.Now.ToString("yyyyMMdd")}.csv", data, head);
 
                         //UpdatePositionResultToDB(detail);
-                        var seqData = p.SEQUENCE.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries).ToList();
+                        //var seqData = p.SEQUENCE.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries).ToList();
+
+                        if (M141Config.StationCode == "S4" && isOK)
+                        {
+                            ////mysqlhelper.GetS2Result(productList[0].SEQUENCE);
+                            //Plc1.WriteSingleAddress(1526, mysqlhelper.GetS2Result(productList[0].SEQUENCE) ? 1 : 2, out _);
+
+                            bool temS2 = mysqlhelper.GetS2Result(p.SEQUENCE);
+                            ReplyPlcData(positionSet, new List<bool>() { temS2 });
+                            if (!temS2)
+                            {
+                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"{p.SN}    S2宸ョ珯NG鎶涙枡");
+                            }
+                        }
+                        else
+                        {
+                            ReplyPlcData(positionSet, plcresult);
+                        }
 
 
+
+                        mysqlhelper.UpdateProduct(p);
                         if (positionSet.IsLastPosition)
                         {
                             UpdateProductResultAsync(p);
+                            mysqlhelper.NewForAll(p, M141Config.StationCode, M141Config.defectname);
+                            if (M141Config.IsfinDevice)
+                            {
+                                SummaryAllprodata(p);
+                            }
                         }
                     });
-                    ReplyPlcData(positionSet, plcresult);
-                    if (positionSet.IsLastPosition)
-                    {
-                        if (_ct != null)
-                        {
-                            UpdateCT(null, (float)((DateTime.Now - _ct.Value).TotalSeconds));
-                        }
-                        _ct = DateTime.Now;
-                    }
 
-                    //ReplyPlcData(positionName, config.TriggerValue);
 
                     cameraIds.ForEach(c =>
                     {
@@ -968,6 +1241,162 @@
                             LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"鐩告満{camera.Name}娓呯悊缂撳瓨");
                         }
                     });
+
+                    //ReplyPlcData(positionSet, plcresult);
+                    if (positionSet.IsLastPosition)
+                    {
+                        if (_ct != null)
+                        {
+                            UpdateCT(null, (float)((DateTime.Now - _ct.Value).TotalSeconds));
+                        }
+                        _ct = DateTime.Now;
+
+                        if (M141Config.ISupMES && (M141Config.MESchannel == -1 || M141Config.MESchannel == 1))
+                        {
+                            if (M141Config.numpro >= 50)
+                            {
+                                M141Config.numpro = 0;
+                            }
+
+                            if (pList[0].Result == "OK")
+                            {
+                                M141Config.numpro++;
+                            }
+
+                            //mqtt.demes(productList[0], M141Config.zwoid);
+                            string Msgreceice = Task.Run(() => mqtt.MESForProduceAsync(pList[0], M141Config.mesnum2.ToString(),M141Config.numpro)).Result;
+                            M141Config.mesnum2++;
+                            if (Msgreceice == null)
+                            {
+                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{pList[0].PID}鏁版嵁涓婁紶MES寮傚父 杩斿洖鏁版嵁涓簄ull");
+                            }
+                            else
+                            {
+                                try
+                                {
+                                    var obj = JsonConvert.DeserializeObject<AutoLineMacBarcodeQueueBak>(Msgreceice);
+
+                                    if (obj.zstatus == "200")
+                                    {
+                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧{pList[0].PID}鏁版嵁涓婁紶MES鎴愬姛  {Msgreceice}");
+                                    }
+                                    else
+                                    {
+                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{pList[0].PID}鏁版嵁涓婁紶MES澶辫触  {Msgreceice}");
+                                    }
+                                }
+                                catch
+                                {
+                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{pList[0].PID}鏁版嵁涓婁紶MES寮傚父  {Msgreceice}");
+                                }
+                            }
+
+
+
+                            int numplca = Convert.ToInt32(pList[0].SEQUENCE.Split('_')[0]);
+                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"plc缁欏嚭鐨勪骇鍝佸簭鍙蜂负{numplca}");
+
+                            lock (plcnumlock)//1-29999   
+                            {
+
+                                if (PlcNumForAll == -1)
+                                {
+                                    PlcNumForAll = numplca;
+                                }
+
+                                int differ = numplca - PlcNumForAll;
+
+                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"涓や釜浜у搧涓棿鐨勫樊鍊糳iffer涓簕differ}");
+
+                                if (differ > 1)
+                                {
+                                    for (int i = PlcNumForAll + 1; i < numplca; i++)
+                                    {
+                                        try
+                                        {
+                                            var plist = mysqlhelper.GetProductList(i + "_1");
+                                            ProductModel newp = new ProductModel();
+                                            newp.SEQUENCE = plist[0].SEQUENCE;
+                                            newp.PID = plist[0].PID;
+                                            newp.BasketCode = plist[0].BasketCode;
+                                            newp.Zword = plist[0].Zword;
+                                            newp.Result = "NG";
+                                            newp.SN = plist[0].SN;
+                                            var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
+                                            M141Config.mesnum2++;
+                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"鍓嶇珯NG鎺掓枡浜у搧{newp.PID}鏁版嵁涓婁紶,缁撴灉涓簕newp.Result}");
+
+                                        }
+                                        catch
+                                        {
+
+                                        }
+                                    }
+                                }
+                                else if (differ == -29998 && differ == 1 && differ == 0)
+                                {
+                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"鐢熶骇杩囩▼涓湭澶卞幓浜у搧");
+                                }
+                                else if ( differ<0 && differ>-29998)
+                                {
+                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"PlcNumForAll涓簕PlcNumForAll}锛宯umplca涓簕numplca}");
+                                    //浜у搧浠庢柊璁℃暟鏃�
+                                    for (int i = PlcNumForAll + 1; i <= 29999; i++)
+                                    {
+                                        try
+                                        {
+                                            var plist = mysqlhelper.GetProductList(i + "_1");
+                                            ProductModel newp = new ProductModel();
+                                            newp.SEQUENCE = plist[0].SEQUENCE;
+                                            newp.PID = plist[0].PID;
+                                            newp.Zword = plist[0].Zword;
+                                            newp.BasketCode = plist[0].BasketCode;
+                                            newp.Result = "NG";
+                                            newp.SN = plist[0].SN;
+                                            var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
+                                            M141Config.mesnum2++;
+                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"PlcNumForAll锛屽墠绔橬G鎺掓枡涓攑lc瑙﹀彂娓呴浂浜у搧{newp.PID}鏁版嵁涓婁紶,缁撴灉涓簕newp.Result}");
+                                        }
+                                        catch
+                                        {
+
+                                        }
+                                    }
+                                    for (int i = 1; i < numplca; i++)
+                                    {
+                                        try
+                                        {
+                                            var plist = mysqlhelper.GetProductList(i + "_1");
+                                            ProductModel newp = new ProductModel();
+                                            newp.SEQUENCE = plist[0].SEQUENCE;
+                                            newp.PID = plist[0].PID;
+                                            newp.BasketCode = plist[0].BasketCode;
+                                            newp.Zword = plist[0].Zword;
+                                            newp.Result = "NG";
+                                            newp.SN = plist[0].SN;
+                                            var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
+                                            M141Config.mesnum2++;
+                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"numplca锛屽墠绔橬G鎺掓枡涓攑lc瑙﹀彂娓呴浂浜у搧{newp.PID}鏁版嵁涓婁紶,缁撴灉涓簕newp.Result}");
+                                        }
+                                        catch
+                                        {
+
+                                        }
+                                    }
+                                }
+
+
+
+                                PlcNumForAll = numplca;
+                            }
+
+                        }
+
+                    }
+
+                    //ReplyPlcData(positionName, config.TriggerValue);
+
+                   
 
                     return pList;
 
@@ -993,6 +1422,52 @@
         }
 
 
+        public void SummaryAllprodata(ProductModel p)
+        {
+            _taskFactory.StartNew(() =>
+            {
+                try
+                {
+                    ProductModel newp = new ProductModel();
+                    newp.SEQUENCE = p.SEQUENCE;
+                    newp.PID = p.PID;
+                    newp.BasketCode = p.BasketCode;
+                    newp.Zword = p.Zword;
+                    newp.Result = p.Result;
+                    newp.SN = p.SN;
+
+                    Thread.Sleep(500);
+                    var plist = mysqlhelper.GetProductList(p.SEQUENCE);
+
+
+                    if (plist != null)
+                    {
+                        foreach (var item in plist)
+                        {
+                            newp.Details.AddRange(item.Details);
+                        }
+                    }
+                    //LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"AllDeviceProductRecord浠庢暟鎹簱鑾峰彇鍒版暟鎹畕p.SEQUENCE} plist鏁伴噺{plist.Count} Details鏁伴噺{newp.Details.Count}");
+
+                    //newp.Details.AddRange(p.Details);
+
+                    List<string> specHeadListforall = new List<string>();
+                    List<string> positionListforall = new List<string>();
+                    string csvHeadforall = newp.GetCSVHead(ref specHeadListforall, ref positionListforall);
+                    CSVRecordAsync($"AllDeviceProductRecord.csv", newp.GetCSVData(specHeadListforall, positionListforall), csvHeadforall);
+
+                }
+                catch (Exception exx)
+                {
+                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, "AllDeviceProductRecord鏁版嵁姹囨�诲紓甯�  " + exx.ToString());
+                }
+            });
+
+        }
+
+
+
+
         #endregion
     }
 

--
Gitblit v1.8.0