quanzhou
2 天以前 86f899fa91e811415614dff1a699141144bfc802
src/Bro.M141.Process/M141Process.cs
@@ -13,6 +13,7 @@
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Function;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Ocsp;
@@ -24,11 +25,14 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using Windows.ApplicationModel.Appointments;
using Windows.Devices.PointOfService;
using ZXing;
using ZXing.QrCode;
using static Bro.Common.Helper.EnumHelper;
using static Bro.Process.ProcessControl;
using static Org.BouncyCastle.Math.EC.ECCurve;
@@ -79,6 +83,8 @@
                ThHeartPlc.IsBackground = true;
                ThHeartPlc.Start();
            }
            printDocument1.PrintPage += new PrintPageEventHandler(printDocument_Print);
        }
        public override void ProcessRunStateChanged()
@@ -97,6 +103,7 @@
        public PLCBase Plc1;
        bool devicestate = false;
        PLCBase Plc2;
        public PLCBase Plc3;
        public Thread ThHeartPlc;
        public RabbitMQHelper mqtt;
@@ -121,6 +128,8 @@
            }
            _errorSpec = M141Config.SpecCollection.FirstOrDefault(u => u.Code == M141Config.CheckErrorSpecCode) as Spec;
            //InitialProductList();
            NetWarmUp();
@@ -137,8 +146,12 @@
                mqtt = new RabbitMQHelper(M141Config.zIP, M141Config.zport, M141Config.zuser, M141Config.zpassword);
                mqtt.Connect(M141Config.MESchannel);
            }
            else
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"已关闭上传mes");
            }
            InitialContinuousNGAlarm();
                InitialContinuousNGAlarm();
        }
@@ -189,6 +202,9 @@
            Dictionary<string, List<int>> StateDIC = new Dictionary<string, List<int>>();
            List<string> AlarmTypeList = new List<string>();
            int numplc = 0;
            while (true)
            {
@@ -232,18 +248,18 @@
                    //        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();
                        //        }
                        //    }
                        //}
                    //        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)
                {
@@ -285,16 +301,13 @@
                                }
                                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();
@@ -304,43 +317,98 @@
                                    foreach (var item2 in item)
                                    {
                                        item2.value = Allbin[item2.address2];
                                        if (!AlarmTypeList.Contains(item2.alarmtype))
                                        {
                                            AlarmTypeList.Add(item2.alarmtype);
                                        }
                                    }
                                }
                                string StateDICKey = "";
                                foreach (var item in AlarmTypeList)
                                {
                                    StateDICKey = plcdev.Name +"_"+ item;
                                    if (!StateDIC.ContainsKey(StateDICKey))
                                    {
                                        StateDIC[StateDICKey] = new List<int>();
                                    }
                                }
                                List<int> list = new List<int>();
                                Dictionary<string, AlarmTypeData> AlarmType = new Dictionary<string, AlarmTypeData>();
                                foreach (var item in alrams)
                                {
                                    csvhead += $",{item.alarmname}";
                                    csvdata += $",{(item.value == 1 ? "1" : "")}";
                                    list.Add(item.value);
                                }
                                    string key = item.alarmtype;
                                if (!StateDIC[plcdev.Name].SequenceEqual(list))
                                    if (!AlarmType.TryGetValue(key, out var alarmData))
                                    {
                                        // 不存在,创建新的
                                        alarmData = new AlarmTypeData()
                                        {
                                            CSVhead = csvhead,
                                            CSVdata = csvdata,
                                        };
                                        AlarmType.Add(item.alarmtype, alarmData);
                                    }
                                    alarmData.CSVhead += $",{item.alarmname}";
                                    alarmData.CSVdata += $",{(item.value == 1 ? "1" : "")}";
                                    alarmData.AlarmTypeValue.Add(item.value);
                                }
                                foreach(var item in AlarmType.Keys)
                                {
                                    StateDIC[plcdev.Name].Clear();
                                    StateDIC[plcdev.Name].AddRange(list);
                                    CSVRecordAsync($"PLCstate_{plcdev.Name}.csv", csvdata, csvhead);
                                    list = AlarmType[item].AlarmTypeValue;
                                    var showdata = alrams.Where(u => u.value == 1).Select(u => u.alarmname).ToList();
                                    string key = plcdev.Name+"_"+item;
                                    if (showdata == null)
                                    if (!StateDIC[key].SequenceEqual(list))
                                    {
                                        showdata = new List<string>();
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{plcdev.Name}报警类型:{item}的信号发生变化,保存的数据为{AlarmType[item].CSVdata}");
                                        StateDIC[key].Clear();
                                        StateDIC[key].AddRange(list);
                                        CSVRecordAsync($"PLCstate_{DateTime.Now.ToString("yyyyMMdd")}_{key}.csv", AlarmType[item].CSVdata, AlarmType[item].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");
                                        }
                                    }
                                    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(Exception EXC)
                            {
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"PLC报警存储记录发生异常 {EXC.ToString()}");
                            }
                        }
                    }
@@ -350,8 +418,6 @@
                {
                }
                try
                {
@@ -375,6 +441,18 @@
                Thread.Sleep(1000);
            }
        }
        public class AlarmTypeData
        {
            public List <int> AlarmTypeValue = new List<int>();
            public string CSVhead;
            public string CSVdata;
        }
        /// <summary>
        /// 网络预热
@@ -564,6 +642,10 @@
                        if (measureBind.WorkPosition == "P1" && M141Config.StationCode == "S5" && detectResults.GetDefectDescList().Count == 0)
                        {
                            var defecttem1 = detectResults.SelectMany(u => u.AllNetResults).SelectMany(m => m.DetectDetails).Select(detail => detail.ClassName).ToList();
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{products[0].SN}  S3S5检测 缺陷名称集合为{string.Join(",", defecttem1)}");
                            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);
@@ -815,7 +897,6 @@
            });
        }
        public async Task RunImageCheckAsync(List<ProductModel> products, string triggerText, string triggerSource, MeasureBind measureBind)
        {
            await Task.Run(() =>
@@ -894,7 +975,6 @@
            });
        }
        private void RunCustomizedMethod(List<ProductModel> products, string triggerText, string triggerSource, IImageSet imgSet, string methodId, List<DetectResult> resultList)
        {
            try
@@ -941,10 +1021,6 @@
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"自定义检测过程异常,{ex.GetExceptionMessage()}");
            }
        }
        #region plc
        public ResponseMessage RunImageCheck_plc(IOperationConfig config)
@@ -1023,7 +1099,6 @@
            CheckPositionDoneAsync_plc(measureBinds[0].WorkPosition, inputSequence, config, cameraIds);
            return msg;
        }
@@ -1074,8 +1149,6 @@
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"相机{camera.Name}检测前清理缓存完成");
                }
            });
            inputSequence = triggerDatas[triggerDatas.Length - 1];
@@ -1161,13 +1234,12 @@
        public async Task<List<ProductModel>> CheckPositionDoneAsync_plc(string positionName, string inputSequence, IOperationConfig config, List<string> cameraIds)
        {
            string triggerSource = config.TriggerSource;
            return await _taskFactory.StartNew(() =>
            {
                try
                {
                    string index = config.TriggerStr.Split(',')[1];
                    var positionSet = M141Config.WorkPositionCollection.FirstOrDefault(u => u.PositionName == positionName);
@@ -1343,8 +1415,9 @@
                            if (pList[0].Result == "OK")
                            {
                                M141Config.numpro++;
                                Msgreceice = Task.Run(() => mqtt.MESForProduceAsync(pList[0], M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                //M141Config.numpro++;
                                //Msgreceice = Task.Run(() => mqtt.MESForProduceAsync(pList[0], M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{pList[0].PID}汇总OK暂时不上传");
                            }
                            else
                            {
@@ -1380,6 +1453,11 @@
                                    if (obj.zstatus == "200")
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{pList[0].PID}数据上传MES成功  {Msgreceice}");
                                        if (M141Config.Isprint && !string.IsNullOrEmpty(obj.tary_label))
                                        {
                                            StartPrint(obj.tary_label, "Honeywell PX240S(300 dpi)");
                                        }
                                    }
                                    else
                                    {
@@ -1391,8 +1469,6 @@
                                    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}");
@@ -1482,9 +1558,6 @@
                                            {
                                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{newp.PID}关闭NG上传");
                                            }
                                            //var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
                                            //M141Config.mesnum2++;
                                            //LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"PlcNumForAll,前站NG排料且plc触发清零产品{newp.PID}数据上传,结果为{newp.Result}");
                                        }
                                        catch
@@ -1533,7 +1606,10 @@
                            }
                        }
                        else
                        {
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"已关闭mes连接或者数据上传接口");
                        }
                    }
                    //ReplyPlcData(positionName, config.TriggerValue);
@@ -1614,7 +1690,7 @@
                            data += "NA,";
                        }
                    }
                    CSVRecordAsync($"AllDeviceProductRecord.csv", data, Head);
                    CSVRecordAsync($"AllDeviceProductRecord_{DateTime.Now.ToString("yyyyMMdd")}.csv", data, Head);
                }
                catch (Exception exx)
@@ -1806,6 +1882,85 @@
            return new ResponseMessage();
        }
        #region  打印机相关
        PrintDocument printDocument1 = new PrintDocument();
        string Printmessage = "";
        public void StartPrint(string str, string PrinterName)
        {
            try
            {
                int ttwith = 240;
                int ttheigh = 80;
                Printmessage = str;
                this.printDocument1.DefaultPageSettings.PrinterSettings.PrinterName = "Honeywell PX240S (300 dpi)";
                this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custum", ttwith, ttheigh);
                this.printDocument1.PrintController = new System.Drawing.Printing.StandardPrintController();
                this.printDocument1.Print();
            }
            catch
            {
            }
        }
        //C229M2508250500002
        private void printDocument_Print(object sender, PrintPageEventArgs e)
        {
            Font fntTxt = new Font("黑体", 15, System.Drawing.FontStyle.Bold);//正文文字
            System.Drawing.Brush brush = new SolidBrush(System.Drawing.Color.Black);//画刷
            try
            {
                var g = e.Graphics;
                g.Clear(Color.White);
                BarcodeWriter writer = new BarcodeWriter();
                writer.Format = BarcodeFormat.QR_CODE;
                QrCodeEncodingOptions options = new QrCodeEncodingOptions()
                {
                    DisableECI = true,//设置内容编码
                    CharacterSet = "UTF-8",  //设置二维码的宽度和高度
                    Width = 60,
                    Height = 60,
                    Margin = 1//设置二维码的边距,单位不是固定像素
                };
                writer.Options = options;
                Bitmap map = writer.Write(Printmessage);
                e.Graphics.DrawImage(map, new System.Drawing.Point(90, 4));
                // 在二维码下方画内容文字
                using (Font font = new Font("Arial", 10))
                using (Brush brush3 = new SolidBrush(Color.Black))
                {
                    // 让文字居中到二维码下方
                    SizeF textSize = e.Graphics.MeasureString(Printmessage, font);
                    float textX = 90 + (map.Width - textSize.Width) / 2;
                    float textY = 1 + map.Height;
                    e.Graphics.DrawString(Printmessage, font, brush3, textX, textY);
                }
            }
            catch (Exception ee)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, ee.ToString());
            }
        }
        #endregion
    }
    public class DefectNGRecord