From 86f899fa91e811415614dff1a699141144bfc802 Mon Sep 17 00:00:00 2001
From: quanzhou <quan.zhou@broconcentric.com>
Date: 星期五, 12 十二月 2025 13:25:37 +0800
Subject: [PATCH] S5上传mes逻辑修改及打印机逻辑修改和数据库存储数据增加

---
 src/Bro.M141.Process/MyMQTT.cs                 |   94 ++---
 src/Bro.M141.Process/UI/UIPrinter.cs           |    8 
 src/Bro.M141.Process/UI/DataPrinter.cs         |    3 
 src/Bro.M141_AOI1.Process/AOI1Process.cs       |  475 ++++++++++++++++++++------
 src/Bro.M141.Process/M141Process_Mysql.cs      |    4 
 src/Bro.M141.Process/M141Config.cs             |   64 +++
 src/Bro.M141.Process/M141Process.cs            |   26 -
 src/Bro.M141.Process/M141Process_ImageCheck.cs |  356 +++++++++++++++++++
 8 files changed, 842 insertions(+), 188 deletions(-)

diff --git a/src/Bro.M141.Process/M141Config.cs b/src/Bro.M141.Process/M141Config.cs
index bba1b8b..a115d5e 100644
--- a/src/Bro.M141.Process/M141Config.cs
+++ b/src/Bro.M141.Process/M141Config.cs
@@ -326,9 +326,73 @@
         public List<PlcAndBasketcode> PlcAndBasketcodes { get; set; } = new List<PlcAndBasketcode>();
 
 
+        [Category("MES閰嶇疆")]
+        [Description("浜у搧ID闆嗗悎")]
+        [DisplayName("浜у搧ID闆嗗悎")]
+        [TypeConverter(typeof(CollectionCountConvert))]
+        [Editor(typeof(ComplexCollectionEditor<ProductionID>), typeof(UITypeEditor))]
+        public List<ProductionID> Productioncode { get; set; } = new List<ProductionID>();
+
+        [Category("MES閰嶇疆")]
+        [Description("鏉$爜闆嗗悎")]
+        [DisplayName("鏉$爜闆嗗悎")]
+        [TypeConverter(typeof(CollectionCountConvert))]
+        [Editor(typeof(ComplexCollectionEditor<MES_code>), typeof(UITypeEditor))]
+        public List<MES_code> MES_codes { get; set; } = new List<MES_code>();
+
+
+    }
+    public class MES_code: IComplexDisplay
+    {
+        [Category("閰嶇疆")]
+        [Description("MES涓嬪彂鐨勬潯鐮�")]
+        [DisplayName("鏉$爜")]
+        public string Printers_code { get; set; }
+        public string GetDisplayText()
+        {
+            return $"{Printers_code}";
+        }
     }
 
 
+    public class ProductionID : IComplexDisplay
+    {
+        [Category("閰嶇疆")]
+        [Description("搴忓彿")]
+        [DisplayName("搴忓彿")]
+        public int Uptomesid { get; set; } = 0;
+
+        [Category("閰嶇疆")]
+        [Description("鏉$爜")]
+        [DisplayName("PID")]
+        public string PID { get; set; }
+
+        [Category("閰嶇疆")]
+        [Description("鏉$爜")]
+        [DisplayName("SEQUENCE")]
+        public string SEQUENCE { get; set; }
+
+        [Category("閰嶇疆")]
+        [Description("鏉$爜")]
+        [DisplayName("BasketCode")]
+        public string BasketCode { get; set; }
+
+        [Category("閰嶇疆")]
+        [Description("鏉$爜")]
+        [DisplayName("Zword")]
+        public string Zword { get; set; }
+
+        [Category("閰嶇疆")]
+        [Description("鏉$爜")]
+        [DisplayName("SN")]
+        public string SN { get; set; }
+
+        public string GetDisplayText()
+        {
+            return $"浜у搧{PID}涓婁紶鎵规搴忓彿{Uptomesid}";
+        }
+    }
+
     public class WorkPositionSet : IComplexDisplay
     {
         [Category("plc鍦板潃")]
diff --git a/src/Bro.M141.Process/M141Process.cs b/src/Bro.M141.Process/M141Process.cs
index fdec168..37671b9 100644
--- a/src/Bro.M141.Process/M141Process.cs
+++ b/src/Bro.M141.Process/M141Process.cs
@@ -643,6 +643,7 @@
                         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();
@@ -1414,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}姹囨�籓K鏆傛椂涓嶄笂浼�");
                             }
                             else
                             {
@@ -1454,11 +1456,8 @@
 
                                         if (M141Config.Isprint && !string.IsNullOrEmpty(obj.tary_label))
                                         {
-                                            StartPrint(obj.tary_label);
+                                            StartPrint(obj.tary_label, "Honeywell PX240S(300 dpi)");
                                         }
-
-
-
                                     }
                                     else
                                     {
@@ -1470,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}");
@@ -1561,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锛屽墠绔橬G鎺掓枡涓攑lc瑙﹀彂娓呴浂浜у搧{newp.PID}鏁版嵁涓婁紶,缁撴灉涓簕newp.Result}");
 
                                         }
                                         catch
@@ -1696,7 +1690,7 @@
                             data += "NA,";
                         }
                     }
-                    CSVRecordAsync($"AllDeviceProductRecord.csv", data, Head);
+                    CSVRecordAsync($"AllDeviceProductRecord_{DateTime.Now.ToString("yyyyMMdd")}.csv", data, Head);
 
                 }
                 catch (Exception exx)
@@ -1894,7 +1888,7 @@
         PrintDocument printDocument1 = new PrintDocument();
         string Printmessage = "";
 
-        public void StartPrint(string str)
+        public void StartPrint(string str, string PrinterName)
         {
             try
             {
@@ -1915,6 +1909,7 @@
             }
 
         }
+
 
 
         //C229M2508250500002
@@ -1965,11 +1960,6 @@
 
 
         #endregion
-
-
-
-
-
 
     }
 
diff --git a/src/Bro.M141.Process/M141Process_ImageCheck.cs b/src/Bro.M141.Process/M141Process_ImageCheck.cs
index f054fd9..4d1f940 100644
--- a/src/Bro.M141.Process/M141Process_ImageCheck.cs
+++ b/src/Bro.M141.Process/M141Process_ImageCheck.cs
@@ -5,6 +5,7 @@
 using Bro.DataBase.Model;
 using Bro.M135.Common;
 using Bro.M135.DBManager;
+using Bro.UI.Model.Winform;
 using HalconDotNet;
 using Microsoft.VisualBasic;
 using Newtonsoft.Json;
@@ -17,6 +18,7 @@
 using System.Data;
 using System.Data.SqlTypes;
 using System.Diagnostics;
+using System.Drawing.Imaging;
 using System.Net;
 using System.Text;
 using System.Text.Encodings.Web;
@@ -26,6 +28,7 @@
 using static System.Net.Mime.MediaTypeNames;
 using static System.Net.WebRequestMethods;
 using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
+using File = System.IO.File;
 
 namespace Bro.M141.Process
 {
@@ -700,11 +703,355 @@
                     imgSet.HImage?.Dispose();
                     imgSet.HImage = null;
 
+                    Bitmap originImage = new Bitmap(imageFileNames[i]);
+                    DetectResultSaveExcelAsync(detectResults, sn, originImage, DateTime.Now);
                 }
             });
         }
 
+        object _excelOpLock = new object();
+        int _columnWidth = 0;
+        int _columnWidth1 = 0;
 
+        int _exportNum = 0;
+
+        public async void DetectResultSaveExcelAsync(List<DetectResult> detectResults, string sn, Bitmap originImage, DateTime dt)
+        {
+            await Task.Run(() =>
+            {
+                if (detectResults.All(u => u.ResultState == EnumHelper.ResultState.OK))
+                    return;
+
+                try
+                {
+                    string excel_Path = Path.Combine(CSVHelper.BaseDirectory, $"{DateTime.Now.ToString("yyyyMMdd")}");
+                    if (!Directory.Exists(excel_Path))//濡傛灉涓嶅瓨鍦ㄥ氨鍒涘缓file鏂囦欢澶�
+                    {
+                        Directory.CreateDirectory(excel_Path);//鍒涘缓璇ユ枃浠跺す
+                    }
+                    excel_Path = Path.Combine(excel_Path, $"OfflineRecord_{DateTime.Now.ToString("yyyyMMdd")}.xlsx");
+                    List<string> datas = new List<string>() { "妫�娴嬫椂闂�", "SN", "缂洪櫡鍚嶇О", "浣嶇疆", "缂洪櫡闈㈢Н", "瀹為檯闈㈢Н", "缂洪櫡鎴浘1", "缂洪櫡鎴浘2" };
+
+                    NPOI.SS.UserModel.IRow irow;
+                    NPOI.SS.UserModel.ICell icell;
+
+                    Interlocked.Increment(ref _exportNum);
+                    lock (_excelOpLock)
+                    {
+                        if (!File.Exists(excel_Path))
+                        {
+                            XSSFWorkbook wb = new XSSFWorkbook();
+                            ISheet sheet = wb.CreateSheet("DefectDetail");
+                            irow = sheet.CreateRow(0);
+                            for (int i = 0; i < datas.Count; i++)
+                            {
+                                icell = irow.CreateCell(i);
+                                icell.SetCellValue(datas[i]);
+                            }
+                            FileStream fs = new FileStream(excel_Path, FileMode.OpenOrCreate, FileAccess.Write);
+                            wb.Write(fs); fs.Close();
+                            fs.Dispose();
+                        }
+
+                        using (FileStream newfs = new FileStream(excel_Path, FileMode.Open, FileAccess.ReadWrite))
+                        {
+                            //鍒涘缓宸ヤ綔绨垮璞�
+                            XSSFWorkbook newwb = new XSSFWorkbook(newfs);
+                            //鏍规嵁宸ヤ綔琛ㄥ悕鑾峰彇宸ヤ綔绨垮璞★紝涔熷彲閫氳繃绱㈠紩鑾峰彇宸ヤ綔琛╳b.GetSheetAt(int index)
+                            ISheet newsheet = newwb.GetSheet("DefectDetail");
+                            int countrow = newsheet.LastRowNum + 1;
+
+                            //ICellStyle hlink_style = newwb.CreateCellStyle();
+                            //IFont hlink_font = newwb.CreateFont();
+                            //hlink_font.Underline = FontUnderlineType.Single;
+                            //hlink_font.Color = HSSFColor.Blue.Index;
+                            //hlink_style.SetFont(hlink_font);
+
+                            XSSFDrawing patriarchDefectImageFile = (XSSFDrawing)newsheet.CreateDrawingPatriarch();
+
+                            var details = detectResults.SelectMany(u => u.NetResults).SelectMany(u => u.DetectDetails).Where(u => u.FinalResult != EnumHelper.ResultState.OK).ToList();
+
+                            details.ForEach(d =>
+                            {
+                                //"妫�娴嬫椂闂�", "SN", "缂洪櫡鍚嶇О", "浣嶇疆", "缂洪櫡闈㈢Н", "瀹為檯闈㈢Н", "缂洪櫡鎴浘1", "缂洪櫡鎴浘2"
+                                List<string> data = new List<string>() { dt.ToString("HH:mm:ss.fff").ToString(), sn, d.ClassName, (d.Tag ?? "").ToString(), d.Area.ToString(), d.AreaInActual.ToString("f3") };
+
+                                irow = newsheet.CreateRow(countrow);
+
+                                for (int i = 0; i < datas.Count; i++)
+                                {
+                                    icell = irow.CreateCell(i);
+
+                                    switch (i)
+                                    {
+                                        case 6:
+                                            {
+                                                byte[] bytesDefectImageFile = CaptureImage(originImage, (int)d.Rect.Width, (int)d.Rect.Height, (int)d.Rect.X, (int)d.Rect.Y, out int actWidth, out int actHeight);
+                                                int pictureIdxDefectImageFile = newwb.AddPicture(bytesDefectImageFile, NPOI.SS.UserModel.PictureType.JPEG);
+
+                                                // 鎻掑浘鐗囩殑浣嶇疆  HSSFClientAnchor锛坉x1,dy1,dx2,dy2,col1,row1,col2,row2) 鍚庨潰鍐嶄綔瑙i噴
+                                                XSSFClientAnchor anchorDefectImageFile = new XSSFClientAnchor(1, 1, 1, 1, i, countrow, i + 1, countrow + 1);
+                                                //鎶婂浘鐗囨彃鍒扮浉搴旂殑浣嶇疆
+                                                XSSFPicture pictDefectImageFile = (XSSFPicture)patriarchDefectImageFile.CreatePicture(anchorDefectImageFile, pictureIdxDefectImageFile);
+
+                                                ////int colWidth = actWidth * 32;
+                                                ////if (colWidth > _columnWidth)
+                                                ////{
+                                                ////    _columnWidth = colWidth;
+                                                ////    newsheet.SetColumnWidth(i, _columnWidth);
+                                                ////}
+
+                                                irow.Height = (short)(actHeight * 16);
+                                                //pictDefectImageFile.Resize();
+                                            }
+                                            break;
+                                        case 7:
+                                            {
+                                                byte[] bytesDefectImageFile = CaptureImage(originImage, (int)d.Rect.Width, (int)d.Rect.Height, (int)d.Rect.X, (int)d.Rect.Y, out int actWidth, out int actHeight, d);
+                                                int pictureIdxDefectImageFile = newwb.AddPicture(bytesDefectImageFile, NPOI.SS.UserModel.PictureType.JPEG);
+
+                                                XSSFClientAnchor anchorDefectImageFile = new XSSFClientAnchor(1, 1, 1, 1, i, countrow, i + 5, countrow + 1);
+                                                //鎶婂浘鐗囨彃鍒扮浉搴旂殑浣嶇疆
+                                                XSSFPicture pictDefectImageFile = (XSSFPicture)patriarchDefectImageFile.CreatePicture(anchorDefectImageFile, pictureIdxDefectImageFile);
+
+                                                //int colWidth = actWidth * 32;
+                                                //if (colWidth > _columnWidth1)
+                                                //{
+                                                //    _columnWidth1 = colWidth;
+                                                //    newsheet.SetColumnWidth(i, _columnWidth1);
+                                                //}
+                                                //pictDefectImageFile.Resize();
+                                            }
+                                            break;
+                                        default:
+                                            string strvalue = data[i];
+                                            icell.SetCellValue(strvalue);
+                                            break;
+                                    }
+                                }
+                                countrow++;
+
+                            });
+
+                            using (var temp = File.OpenWrite(excel_Path))
+                            {
+                                newwb.Write(temp);//鍚戞墦寮�鐨勮繖涓獂ls鏂囦欢涓啓鍏ユ暟鎹� 
+                            }
+                            newfs.Close();
+                            newfs.Dispose();
+                        }
+                    }
+                    Interlocked.Decrement(ref _exportNum);
+                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"{detectResults[0].PID}Excel杈撳嚭瀹屾垚锛岃繕鏈墈_exportNum}鏉¤褰�");
+                }
+                catch (Exception ex)
+                {
+                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{detectResults[0].PID}缂洪櫡鎻掑叆Excel鎶ラ敊锛歿ex.Message.ToString()}");
+                }
+                finally
+                {
+                    originImage.Dispose();
+                    originImage = null;
+                }
+            });
+        }
+
+        int _spaceRemain = 60;
+        //public byte[] CaptureImage(Bitmap originImage, int width, int height, int spaceX, int spaceY, out int actWidth, out int actHeight, DefectDetail defect = null)
+        //{
+        //    spaceX -= _spaceRemain;
+        //    spaceY -= _spaceRemain;
+
+        //    width += _spaceRemain * 2;
+        //    height += _spaceRemain * 2;
+
+        //    if (spaceX < 0)
+        //    {
+        //        spaceX = 0;
+        //    }
+
+        //    if (spaceY < 0)
+        //    {
+        //        spaceY = 0;
+        //    }
+
+        //    if (spaceX + width > originImage.Width)
+        //    {
+        //        width = originImage.Width - spaceX;
+        //    }
+
+        //    if (spaceY + height > originImage.Height)
+        //    {
+        //        height = originImage.Height - spaceY;
+        //    }
+
+        //    actHeight = height;
+        //    actWidth = width;
+
+        //    Bitmap imageBack = originImage;
+
+        //    if (defect != null)
+        //    {
+        //        PolygonResultDisplay display = new PolygonResultDisplay(defect, defect.ClassName, Color.Red, false, (int)(width * GlobalVar.WIDTH_RATIO));
+
+        //        imageBack = new Bitmap(originImage.Width, originImage.Height, PixelFormat.Format24bppRgb);
+        //        using (Graphics g = Graphics.FromImage(imageBack))
+        //        {
+        //            g.DrawImage(originImage, 0, 0);
+        //            display.Draw(g);
+        //        }
+        //    }
+
+        //    //鍒涘缓鏂板浘浣嶅浘   
+        //    Bitmap bitmap = new Bitmap(width, height, imageBack.PixelFormat);
+        //    //鍒涘缓浣滃浘鍖哄煙   
+        //    using (Graphics graphic = Graphics.FromImage(bitmap))
+        //    {
+        //        //鎴彇鍘熷浘鐩稿簲鍖哄煙鍐欏叆浣滃浘鍖�   
+        //        graphic.DrawImage(imageBack, 0, 0, new Rectangle(spaceX, spaceY, width, height), GraphicsUnit.Pixel);
+        //    }
+
+        //    byte[] bt = null;
+        //    using (MemoryStream mostream = new MemoryStream())
+        //    {
+        //        bitmap.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);//灏嗗浘鍍忎互鎸囧畾鐨勬牸寮忓瓨鍏ョ紦瀛樺唴瀛樻祦
+        //        bt = new byte[mostream.Length];
+        //        mostream.Position = 0;//璁剧疆鐣欑殑鍒濆浣嶇疆
+        //        mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
+        //    }
+
+        //    bitmap.Dispose();
+        //    return bt;
+        //}
+
+        public byte[] CaptureImage(Bitmap originImage, int width, int height, int spaceX, int spaceY,
+    out int actWidth, out int actHeight, DefectDetail defect = null)
+        {
+            spaceX -= _spaceRemain;
+            spaceY -= _spaceRemain;
+
+            width += _spaceRemain * 2;
+            height += _spaceRemain * 2;
+
+            if (spaceX < 0)
+            {
+                spaceX = 0;
+            }
+
+            if (spaceY < 0)
+            {
+                spaceY = 0;
+            }
+
+            if (spaceX + width > originImage.Width)
+            {
+                width = originImage.Width - spaceX;
+            }
+
+            if (spaceY + height > originImage.Height)
+            {
+                height = originImage.Height - spaceY;
+            }
+
+            actHeight = height;
+            actWidth = width;
+
+            Bitmap imageBack = originImage;
+            bool needDisposeImageBack = false; // 鏂板锛氭爣璁版槸鍚﹂渶瑕侀噴鏀緄mageBack
+
+            if (defect != null)
+            {
+                PolygonResultDisplay display = new PolygonResultDisplay(defect, defect.ClassName, Color.Red, false, (int)(width * GlobalVar.WIDTH_RATIO));
+
+                // 淇敼鐐�1锛氱‘淇濆垱寤虹殑Bitmap鏀寔Graphics
+                // 浣跨敤Format24bppRgb鎴朏ormat32bppArgb
+                imageBack = new Bitmap(originImage.Width, originImage.Height, PixelFormat.Format24bppRgb);
+                needDisposeImageBack = true; // 鏍囪涓洪渶瑕侀噴鏀�
+
+                // 淇敼鐐�2锛氭鏌ュ師濮嬪浘鍍忔牸寮忥紝濡傛灉鏄储寮曟牸寮忛渶瑕佺壒娈婂鐞�
+                if (IsIndexedPixelFormat(originImage.PixelFormat))
+                {
+                    // 鍒涘缓鏀寔Graphics鐨勬牸寮�
+                    using (Bitmap tempImage = new Bitmap(originImage.Width, originImage.Height, PixelFormat.Format24bppRgb))
+                    using (Graphics tempG = Graphics.FromImage(tempImage))
+                    {
+                        tempG.DrawImage(originImage, 0, 0);
+
+                        using (Graphics g = Graphics.FromImage(imageBack))
+                        {
+                            g.DrawImage(tempImage, 0, 0);
+                            display.Draw(g);
+                        }
+                    }
+                }
+                else
+                {
+                    // 鍘熷浠g爜閫昏緫
+                    using (Graphics g = Graphics.FromImage(imageBack))
+                    {
+                        g.DrawImage(originImage, 0, 0);
+                        display.Draw(g);
+                    }
+                }
+            }
+            else if (IsIndexedPixelFormat(originImage.PixelFormat))
+            {
+                // 淇敼鐐�3锛氬嵆浣挎病鏈塪efect锛屽鏋滄槸绱㈠紩鏍煎紡涔熼渶瑕佽浆鎹�
+                imageBack = new Bitmap(originImage.Width, originImage.Height, PixelFormat.Format24bppRgb);
+                needDisposeImageBack = true;
+
+                using (Graphics g = Graphics.FromImage(imageBack))
+                {
+                    g.DrawImage(originImage, 0, 0);
+                }
+            }
+
+            // 淇敼鐐�4锛氱‘淇漛itmap鐨勫儚绱犳牸寮忔敮鎸丟raphics
+            PixelFormat bitmapFormat = imageBack.PixelFormat;
+            if (IsIndexedPixelFormat(bitmapFormat))
+            {
+                // 濡傛灉imageBack浠嶇劧鏄储寮曟牸寮忥紙鐞嗚涓婁笉搴旇锛夛紝杞崲涓烘敮鎸佹牸寮�
+                bitmapFormat = PixelFormat.Format24bppRgb;
+            }
+
+            //鍒涘缓鏂板浘浣嶅浘   
+            Bitmap bitmap = new Bitmap(width, height, bitmapFormat);
+
+            //鍒涘缓浣滃浘鍖哄煙   
+            using (Graphics graphic = Graphics.FromImage(bitmap))
+            {
+                //鎴彇鍘熷浘鐩稿簲鍖哄煙鍐欏叆浣滃浘鍖�   
+                graphic.DrawImage(imageBack, 0, 0, new Rectangle(spaceX, spaceY, width, height), GraphicsUnit.Pixel);
+            }
+
+            byte[] bt = null;
+            using (MemoryStream mostream = new MemoryStream())
+            {
+                bitmap.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);//灏嗗浘鍍忎互鎸囧畾鐨勬牸寮忓瓨鍏ョ紦瀛樺唴瀛樻祦
+                bt = new byte[mostream.Length];
+                mostream.Position = 0;//璁剧疆鐣欑殑鍒濆浣嶇疆
+                mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
+            }
+
+            bitmap.Dispose();
+
+            // 淇敼鐐�5锛氶噴鏀句复鏃跺垱寤虹殑imageBack
+            if (needDisposeImageBack && imageBack != originImage)
+            {
+                imageBack.Dispose();
+            }
+
+            return bt;
+        }
+
+        // 鏂板杈呭姪鏂规硶锛氭鏌ユ槸鍚︿负绱㈠紩鍍忕礌鏍煎紡
+        private bool IsIndexedPixelFormat(PixelFormat format)
+        {
+            return format == PixelFormat.Format1bppIndexed ||
+                   format == PixelFormat.Format4bppIndexed ||
+                   format == PixelFormat.Format8bppIndexed ||
+                   format == PixelFormat.Indexed;
+        }
 
         [ProcessMethod("printer", "printer", "鎵撳嵃鏈烘墦鍗�", InvokeType.TestInvoke)]
         public ResponseMessage Printer(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
@@ -712,8 +1059,13 @@
             ResponseMessage msg = new ResponseMessage();
 
             Plc2 = invokeDevice as PLCBase;
-            string message = "nothing";
-            StartPrint(message);
+            //string message = "nothing";
+            if (M141Config.MES_codes.Count >= 1)
+            {
+                string message = M141Config.MES_codes[0].Printers_code;
+                StartPrint(message, "Honeywell PX240S(300 dpi)1");
+                M141Config.MES_codes.RemoveAt(0);
+            }                               
             return msg;
         }
 
diff --git a/src/Bro.M141.Process/M141Process_Mysql.cs b/src/Bro.M141.Process/M141Process_Mysql.cs
index e14519a..592ceda 100644
--- a/src/Bro.M141.Process/M141Process_Mysql.cs
+++ b/src/Bro.M141.Process/M141Process_Mysql.cs
@@ -120,7 +120,7 @@
 
                 if (!string.IsNullOrEmpty(index))
                 {
-                    string str2 = $"delete from forlocal where id < ({index}-1000)";
+                    string str2 = $"delete from forlocal where id < ({index}-2000)";
                     Operatoremysql(str2, connStrLocal);
                 }
 
@@ -283,7 +283,7 @@
 
                         if (!string.IsNullOrEmpty(index))
                         {
-                            string str2 = $"delete from forall where id < ({index}-1000)";
+                            string str2 = $"delete from forall where id < ({index}-2000)";
                             Operatoremysql(str2, connStrAll);
                         }
 
diff --git a/src/Bro.M141.Process/MyMQTT.cs b/src/Bro.M141.Process/MyMQTT.cs
index da6a495..e458671 100644
--- a/src/Bro.M141.Process/MyMQTT.cs
+++ b/src/Bro.M141.Process/MyMQTT.cs
@@ -114,6 +114,7 @@
                     if (MSGClasses.Any(u => u.zguid == obj?.zbguid))
                     {
                         var tem = MSGClasses.FirstOrDefault(u => u.zguid == obj?.zbguid);
+
                         if (!string.IsNullOrEmpty(tem.receive))
                         {
                             tem.receive = message;
@@ -140,7 +141,15 @@
                 }
                 else
                 {
-                    CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"RabbitMQ 鐗╂枡 鏀跺埌鏈尮閰� zbguid锛歿obj?.zbguid}");
+                    Thread.Sleep(100);
+                    if (_pendingTask2.TryRemove(obj.zbguid, out var tcs2))
+                    {
+                        tcs2.TrySetResult(message);
+                    }
+                    else
+                    {
+                        CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"RabbitMQ 鐗╂枡 鏀跺埌鏈尮閰� zbguid锛歿obj?.zbguid}");
+                    }
                 }
             }
             catch (Exception ex)
@@ -149,8 +158,7 @@
             }
         }
 
-        //Dictionary<string, Task> dic_ispass = new Dictionary<string, Task>();///value涓烘敹鍒版暟鎹�
-
+        int num = 0;
         public async Task<string> MESForBasketAsync(string ztype, string zlsn, string zlpn, string zstatus, string zversion, int timeoutMes = 30000)
         {
 
@@ -158,31 +166,32 @@
 
             if (MSGClasses.Any(u => u.key == keystr))
             {
-                var tem = MSGClasses.FirstOrDefault(u => u.key == keystr);
-
-                DateTime dt = DateTime.Now;
-                while ((DateTime.Now - dt).TotalMilliseconds < timeoutMes)
+                CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"{keystr}鍖归厤鎴愬姛");
+                num++;
+                //var tem = MSGClasses.FirstOrDefault(u => u.key == keystr);
+                var tem = MSGClasses.Where(u => u.key == "1" && !string.IsNullOrEmpty(u.receive)).ToList();
+                //DateTime dt = DateTime.Now;
+                if (num < 10)
                 {
-                    if (!string.IsNullOrEmpty(tem.receive))
-                    {
-
-                        CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"RabbitMQ {keystr}浜屾鎺ユ敹 杩斿洖鍊兼甯� {tem.receive}");
-                    
-                        return tem.receive;
-                    }
-                    Thread.Sleep(1000);
+                    //while ((DateTime.Now - dt).TotalMilliseconds < timeoutMes)
+                    //{
+                        if (!string.IsNullOrEmpty(tem[0].receive))
+                        {
+                            CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"RabbitMQ {keystr}浜屾鎺ユ敹 杩斿洖鍊兼甯� {tem[0].receive}");
+                            return tem[0].receive;
+                        }
+                        Thread.Sleep(1000);
+                    //}
                 }
-                if (MSGClasses.Count > 10)
+                else 
                 {
-                    MSGClasses.RemoveAt(0);
-                    CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"RabbitMQ浜屾鎺ユ敹鏁版嵁瓒呰繃鍗佹潯 娓呴櫎绗竴鏉¤秴鏃舵暟鎹�");
+                    num = 0;
+                    CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"RabbitMQ瓒呮椂澶勭悊娆℃暟瓒呰繃鍗佹");
+                    //return null;
                 }
-                //MSGClasses.RemoveAll(u => u.key == keystr);
-               
-
-                return null;
+                CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"RabbitMQ浜屾鎺ユ敹鏁版嵁鎺ユ敹涓虹┖");
+                //return null;
             }
-
 
             var guid = Guid.NewGuid().ToString();
             var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -215,14 +224,20 @@
             }
             else
             {
+                CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"RabbitMQ 绡叿 杩斿洖瓒呮椂1锛寊bguid={guid}");
+
                 MSGClasses.Add(new MSGClass()
                 {
                     key = keystr,
                     zguid = guid,
                 });
 
+                if (MSGClasses.Count > 10)
+                {
+                    MSGClasses.RemoveAt(0);                    
+                }
 
-                CommonLogger.LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"RabbitMQ 绡叿 杩斿洖瓒呮椂1锛寊bguid={guid}");
+               
                 return null;
             }
         }
@@ -243,31 +258,6 @@
             {
                 zresult = "NG";
             }
-            //string zr;
-            //switch (pro.Result)
-            //{
-            //    case "ok":
-            //        zr = "";
-            //        break;
-            //    case "寮傝壊":
-            //        zr = "SZ2001";
-            //        break;
-            //    case "纾ㄥ嵃":
-            //        zr = "SZ2012";
-            //        break;
-            //    case "鍘嬩激":
-            //        zr = "SZ2014";
-            //        break;
-            //    case "鍙樺舰":
-            //        zr = "SZ2014";
-            //        break;
-            //    case "鍒掍激":
-            //        zr = "SZ2021";
-            //        break;
-            //    default:
-            //        zr = "S31006";
-            //        break;
-            //}
 
             var DefectCodeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
             {
@@ -292,10 +282,6 @@
                 zbarcode = pro.SN,
                 zresult = zresult,
                 zreson = zr,
-                //zreson = pro.Result == "OK" ? "" : "SZ2014",
-                //
-
-                //
                 zno = znonum.ToString(),
                 zwoid = pro.Zword,
                 endtray = endtray,
@@ -308,7 +294,7 @@
             _sendChannel.BasicPublish("", "auto_line_mac_barcode_queue", null, body);
 
             var completed = await Task.WhenAny(tcs.Task, Task.Delay(timeoutMs));
-            _pendingTask2.TryRemove(guid, out _);
+            //_pendingTask2.TryRemove(guid, out _);
             if (completed == tcs.Task)
                 return await tcs.Task;
             else
diff --git a/src/Bro.M141.Process/UI/DataPrinter.cs b/src/Bro.M141.Process/UI/DataPrinter.cs
index e842daa..31ab720 100644
--- a/src/Bro.M141.Process/UI/DataPrinter.cs
+++ b/src/Bro.M141.Process/UI/DataPrinter.cs
@@ -79,7 +79,6 @@
                     // 灏嗘潯鐮佸叏閮ㄩ�変腑锛屼笅涓�娆℃壂鐮佺殑鏃跺�欙紝鏃ф潯鐮佸氨浼氳鏂版潯鐮佽鐩�
                     Data_Textbox.SelectAll();
                     // 澶勭悊鏉$爜
-                    // ProcessBarcode(barcode);
                     DatatoGridView(barcode);
 
                     Data_Textbox.Focus();
@@ -152,7 +151,7 @@
 
                                         if (Config141.Isprint && !string.IsNullOrEmpty(obj.tary_label))
                                         {
-                                            Process141.StartPrint(obj.tary_label);
+                                            Process141.StartPrint(obj.tary_label, "Honeywell PX240S(300 dpi)");
                                         }
                                     }
                                     else
diff --git a/src/Bro.M141.Process/UI/UIPrinter.cs b/src/Bro.M141.Process/UI/UIPrinter.cs
index 59b576c..0278d89 100644
--- a/src/Bro.M141.Process/UI/UIPrinter.cs
+++ b/src/Bro.M141.Process/UI/UIPrinter.cs
@@ -74,6 +74,14 @@
                 this.printDocument1.PrintController = new System.Drawing.Printing.StandardPrintController();
                 this.printDocument1.Print();
 
+                this.printDocument1.DefaultPageSettings.PrinterSettings.PrinterName = "Honeywell PX240S (300 dpi)1";
+                this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custum", ttwith, ttheigh);
+
+                this.printDocument1.PrintController = new System.Drawing.Printing.StandardPrintController();
+                this.printDocument1.Print();
+
+
+
             }
             catch
             {
diff --git a/src/Bro.M141_AOI1.Process/AOI1Process.cs b/src/Bro.M141_AOI1.Process/AOI1Process.cs
index 8d82bef..f4c2e15 100644
--- a/src/Bro.M141_AOI1.Process/AOI1Process.cs
+++ b/src/Bro.M141_AOI1.Process/AOI1Process.cs
@@ -11,12 +11,16 @@
 using Newtonsoft.Json.Linq;
 using NPOI.OpenXmlFormats.Vml;
 using NPOI.POIFS.Crypt.Dsig;
+using NPOI.POIFS.FileSystem;
 using NPOI.SS.Formula.Functions;
 using NPOI.XSSF.Streaming.Values;
+using ScottPlot.Drawing.Colormaps;
+using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Net.Sockets;
 using System.Text.RegularExpressions;
+using Windows.Media.AppBroadcasting;
 using static Bro.Common.Helper.EnumHelper;
 using static NPOI.HSSF.Util.HSSFColor;
 using static Org.BouncyCastle.Crypto.Engines.SM2Engine;
@@ -132,7 +136,7 @@
                     }
                     var tool = GetHalconTool(null, "", opConfig.AlgorithemPath);
                     var ret = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", imageSet.HImage } }, new List<string>() { "OUTPUT_Results" }, null);
-                    //var ret = tool.RunProcedure(null, null, new List<string>() { "OUTPUT_Results" }, null);
+                   // var ret = tool.RunProcedure(null, null, new List<string>() { "OUTPUT_Results" }, null);
                     List<IShapeElement> eleList = new List<IShapeElement>();
                     TextDisplay text = new TextDisplay();
                     text.LineLimit = M141Config.LineLimit_p;
@@ -140,22 +144,40 @@
                     eleList.Add(text);
                     text.StartX = text.StartY = 0;
                     text.AddText("鐐规杩愯鎴愬姛", Color.Lime, Color.Transparent);
+
                     var b = ret.Item2["OUTPUT_Results"].HTupleToDouble();
-                    if (ret != null&& results1.Count== b.Count())
+
+                    if (results1 != null&& results1.Count== b.Count())
                     {
+
                         var itemDict = results1.ToDictionary(u => u.OutputIndex);
-                        b.ForEach(u =>
+
+                        for (int i = 0; i < itemDict.Count(); i++)
                         {
-                            int index = b.IndexOf(u); // 鑾峰彇褰撳墠鍊肩殑绱㈠紩
-                            if (itemDict.TryGetValue(index, out var item))
+                            double CValue;
+                            if (itemDict[i].CompensationValue != null)
                             {
-                                double diff = u - item.StandardValue;
-                                bool isInTolerance = (diff - item.Tolrenance_Positive) *(diff - item.Tolrenance_Negative) <= 0;
-                                text.AddText($"{item.Code} {u}", isInTolerance == true ? Color.Lime: Color.Red, Color.Transparent);
-                                 Head += $"{item.Code},";
-                                 data += $"{u},";
+                                CValue = itemDict[i].CompensationValue[0];
                             }
-                        });           
+                            else
+                            {
+                                CValue = 0;
+                            }
+                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"鐐规缁撴灉{itemDict[i].Code}绠楁硶杈撳嚭鍊间负{b[i]}");
+                            double diff = b[i] + CValue;
+                            double Upvalue = itemDict[i].StandardValue + itemDict[i].Tolrenance_Positive;
+                            double Downvalue = itemDict[i].StandardValue - itemDict[i].Tolrenance_Negative;
+                            bool isInTolerance = false;
+
+                            if (diff >= Downvalue && diff <= Upvalue)
+                            {
+                                isInTolerance = true;
+                            }
+                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"鐐规缁撴灉{itemDict[i].Code}涓簕isInTolerance}");
+                            text.AddText($"{itemDict[i].Code} {diff}", isInTolerance == true ? Color.Lime : Color.Red, Color.Transparent);
+                            Head += $"{itemDict[i].Code},";
+                            data += $"{diff},";
+                        }                       
                     }                   
                     camera.SaveFitImage(eleList, imageSet);
                     LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"鐐规鍔熻兘杩愯鎴愬姛");
@@ -341,11 +363,11 @@
                                     LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"RabbitMQ zwoid鑾峰彇澶辫触 {zwordstr} ");
                                 }
                             }
-                            catch
+                            catch(Exception ex)
                             {
                                 Plc1.WriteSingleAddress(1524, 2, out _);
                                 Plc1.WriteSingleAddress(1514, 1, out _);
-                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"RabbitMQ zwoid鑾峰彇寮傚父  杩斿洖鏁版嵁涓� {zwordstr} ");
+                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"RabbitMQ zwoid鑾峰彇寮傚父  杩斿洖鏁版嵁涓� {zwordstr},寮傚父閿欒{ex.GetExceptionMessage()}");
                             }
                         }                       
                     }
@@ -593,105 +615,121 @@
             return msg;
         }
 
-        [ProcessMethod("", "MESupdata", "MES姝e父涓婁紶OK浜у搧鑾峰彇鏉$爜", InvokeType.TestInvoke)]
+        [ProcessMethod("", "MESupdata", "MES姝e父涓婁紶鍗曚釜OK浜у搧鑾峰彇鏉$爜", InvokeType.TestInvoke)]
         public ResponseMessage MESupdata(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
         {
             ResponseMessage msg = new ResponseMessage();
 
             Plc3 = invokeDevice as PLCBase;
-            ///浜у搧1涓婁紶
+            //涓婁紶鍙嶉缁撴灉          
+            bool Issuccess = false;
+            bool Issuccess1 = false;
+
+            string tary_label = string.Empty;
+
+            string tary_label1 = string.Empty;
+
             var plcnum = Plc3.Read(2100, 1, out _);
-            if (plcnum[0] != 0)
+            var plcnum1 = Plc3.Read(2102, 1, out _);
+            if (plcnum[0] == 0)
             {
-                var plist = mysqlhelper.GetProductList(plcnum + "_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 = "OK";
-                newp.SN = plist[0].SN;
+                Issuccess = true;
+            }
+            else
+            {
+                Issuccess = UpMES(plcnum[0] + "_1", "N", out tary_label);
+                if (M141Config.Isprint && !string.IsNullOrEmpty(tary_label))
+                {
+                    StartPrint(tary_label, "Honeywell PX240S(300 dpi)");
+                }
+            }
+            if (plcnum1[0] == 0)
+            {
+                Issuccess1 = true;               
+            }
+            else
+            {
+                Issuccess1 = UpMES(plcnum1[0] + "_1", "N", out tary_label1);
 
-                var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
-                M141Config.mesnum2++;
-                if (tems == null)
+                if (M141Config.Isprint && !string.IsNullOrEmpty(tary_label1))
                 {
-                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES寮傚父 杩斿洖鏁版嵁涓簄ull");
+                    StartPrint(tary_label1, "Honeywell PX240S(300 dpi)");
                 }
-                else
-                {
-                    try
-                    {
-                        var obj = JsonConvert.DeserializeObject<AutoLineMacBarcodeQueueBak>(tems);
-                        if (obj.zstatus == "200")
-                        {
-                            Plc1.WriteSingleAddress(2120, 1, out _);
-                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES鎴愬姛  {tems}");
-                        }
-                        else
-                        {
-                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES澶辫触  {tems}");
-                        }
-                    }
-                    catch (Exception)
-                    {
-                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES澶辫触  {tems}");
-                    }
-                }
-                ///浜у搧1涓婁紶
-                var plcnum1 = Plc3.Read(2102, 1, out _);
-                if (plcnum1[0] != 0)
-                {
-                    var plist1 = mysqlhelper.GetProductList(plcnum1 + "_1");
-                    ProductModel newp1 = new ProductModel();
-                    newp1.SEQUENCE = plist[0].SEQUENCE;
-                    newp1.PID = plist[0].PID;
-                    newp1.BasketCode = plist[0].BasketCode;
-                    newp1.Zword = plist[0].Zword;
-                    newp1.Result = "OK";
-                    newp1.SN = plist[0].SN;
-
-                    var tems1 = Task.Run(() => mqtt.MESForProduceAsync(newp1, M141Config.mesnum2.ToString(), M141Config.numpro)).Result;
-                    M141Config.mesnum2++;
-                    if (tems1 == null)
-                    {
-                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES寮傚父 杩斿洖鏁版嵁涓簄ull");
-                    }
-                    else
-                    {
-                        try
-                        {
-                            var obj1 = JsonConvert.DeserializeObject<AutoLineMacBarcodeQueueBak>(tems1);
-                            if (obj1.zstatus == "200")
-                            {
-                                Plc1.WriteSingleAddress(2120, 1, out _);
-                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES鎴愬姛  {tems}");
-                            }
-                            else
-                            {
-                                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES澶辫触  {tems}");
-                            }
-                        }
-                        catch (Exception)
-                        {
-                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES澶辫触  {tems}");
-                        }
-                    }
-                }
-                
+            }                      
+            if (Issuccess && Issuccess1)
+            {
+                Plc3.WriteSingleAddress(2120, 1, out _);
+            }
+            else
+            {
+                Plc3.WriteSingleAddress(2120, 2, out _);
             }
             return msg;
         }
 
-        [ProcessMethod("", "MESupFinallydata", "MES涓婁紶灏剧洏OK浜у搧鑾峰彇鏉$爜", InvokeType.TestInvoke)]
+        [ProcessMethod("", "MESupFinallydata", "MES涓婁紶鍗曚釜灏剧洏OK浜у搧鑾峰彇鏉$爜", InvokeType.TestInvoke)]
         public ResponseMessage MESupFinallydata(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
         {
             ResponseMessage msg = new ResponseMessage();
 
             Plc3 = invokeDevice as PLCBase;
-            ///浜у搧1涓婁紶
+            //涓婁紶鍙嶉缁撴灉          
+            bool Issuccess = false;
+            bool Issuccess1 = false;
+
+            string tary_label = string.Empty;
+
+            string tary_label1 = string.Empty;
+
             var plcnum = Plc3.Read(2100, 1, out _);
-            var plist = mysqlhelper.GetProductList(plcnum+"_1");
+            var plcnum1 = Plc3.Read(2102, 1, out _);
+            if (plcnum[0] != 0|| plcnum1[0] != 0)
+            {
+                if (plcnum[0] == 0)
+                {
+                    Issuccess1 = UpMES(plcnum1[0] + "_1", "Y", out tary_label1);
+                    if (M141Config.Isprint && !string.IsNullOrEmpty(tary_label1))
+                    {
+                        StartPrint(tary_label1, "Honeywell PX240S(300 dpi)");
+                    }
+                }
+                else if(plcnum1[0] == 0)
+                {
+                    Issuccess = UpMES(plcnum[0] + "_1", "Y", out tary_label);
+                    if (M141Config.Isprint && !string.IsNullOrEmpty(tary_label))
+                    {
+                        StartPrint(tary_label, "Honeywell PX240S(300 dpi)");
+                    }
+                }
+                else if (plcnum[0] != 0 && plcnum1[0] != 0)
+                {
+                    Issuccess = UpMES(plcnum[0] + "_1", "N", out tary_label);                   
+                    if (M141Config.Isprint && !string.IsNullOrEmpty(tary_label1))
+                    {
+                        StartPrint(tary_label1, "Honeywell PX240S(300 dpi)");
+                    }
+                    Issuccess1 = UpMES(plcnum1[0] + "_1", "Y", out tary_label1);
+                    if (M141Config.Isprint && !string.IsNullOrEmpty(tary_label))
+                    {
+                        StartPrint(tary_label, "Honeywell PX240S(300 dpi)");
+                    }
+                }
+            }
+           
+            if (Issuccess && Issuccess1)
+            {
+                Plc3.WriteSingleAddress(2120, 1, out _);
+            }
+            else
+            {
+                Plc3.WriteSingleAddress(2120, 2, out _);
+            }
+            return msg;
+        }
+
+        private bool UpMES(string PLCNum ,string endtray , out string result )
+        {
+            var plist = mysqlhelper.GetProductList(PLCNum);
             ProductModel newp = new ProductModel();
             newp.SEQUENCE = plist[0].SEQUENCE;
             newp.PID = plist[0].PID;
@@ -699,12 +737,24 @@
             newp.Zword = plist[0].Zword;
             newp.Result = "OK";
             newp.SN = plist[0].SN;
-            //涓婁紶灏剧洏鏁版嵁
-            var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.mesnum2.ToString(), M141Config.numpro,"Y")).Result;
-            M141Config.mesnum2 = 0;
+            bool isok = UptoMES(newp, endtray, out result);
+            return isok;
+
+        }
+
+        private bool UptoMES( ProductModel pro, string endtray,  out string result)
+        {
+            if (M141Config.numpro >= 50)
+            {
+                M141Config.numpro = 0;
+            }
+            M141Config.numpro++;
+            var tems = Task.Run(() => mqtt.MESForProduceAsync(pro, M141Config.mesnum2.ToString(), M141Config.numpro, endtray)).Result;
             if (tems == null)
             {
-                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES寮傚父 杩斿洖鏁版嵁涓簄ull");
+                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{pro.PID}鏁版嵁涓婁紶MES寮傚父 杩斿洖鏁版嵁涓簄ull");
+                result = string.Empty;
+                return false;
             }
             else
             {
@@ -713,28 +763,237 @@
                     var obj = JsonConvert.DeserializeObject<AutoLineMacBarcodeQueueBak>(tems);
                     if (obj.zstatus == "200")
                     {
-                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES鎴愬姛  {tems}");
-
-
-                        //鎵撳嵃鑾峰彇鐨勬潯鐮�
-                        if (M141Config.Isprint && !string.IsNullOrEmpty(obj.tary_label))
-                        {
-                            StartPrint(obj.tary_label);
-                        }
+                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧{pro.PID}鏁版嵁涓婁紶MES鎴愬姛 {tems}");
+                        result = obj.tary_label;
+                        return true;
                     }
                     else
                     {
-                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES澶辫触  {tems}");
+                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{pro.PID}鏁版嵁涓婁紶MES澶辫触  {tems}");
+                        result = "obj.zerrmsg";
+                        if (obj.zerrmsg.Contains("閲嶅鏁版嵁"))
+                        {
+                            return true;
+                        }
+                        return false;
                     }
                 }
                 catch (Exception)
                 {
-                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{plist[0].PID}鏁版嵁涓婁紶MES澶辫触  {tems}");
+                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"浜у搧{pro.PID}鏁版嵁涓婁紶MES澶辫触  {tems}");
+                    result = string.Empty;
+                    return false;
                 }
+
+            }
+        }
+
+       [ProcessMethod("", "PLCtosaveproduction", "MES閫氳繃plc鑾峰彇浜у搧PID骞朵繚瀛�", InvokeType.TestInvoke)]
+        public ResponseMessage PLCtosaveproduction(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
+        {
+            ResponseMessage msg = new ResponseMessage();
+
+            Plc3 = invokeDevice as PLCBase;
+
+            bool Issuccess = false;
+
+            bool Issuccess1 = false;
+
+            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧淇℃伅璁板綍淇濆瓨瑙﹀彂");
+
+            var plcnum = Plc3.Read(2100, 1, out _);
+            Issuccess = GetProImformation(plcnum[0]);
+
+            var plcnum1 = Plc3.Read(2102, 1, out _);
+            Issuccess1 = GetProImformation(plcnum1[0]);
+            
+            if (Issuccess && Issuccess1)
+            {
+                Plc3.WriteSingleAddress(2120, 1, out _);
+            }
+            else
+            {
+                Plc3.WriteSingleAddress(2120, 2, out _);
             }
             return msg;
         }
 
+        private bool GetProImformation(int PLC_order)
+        {
+            if (PLC_order == 0)
+            {
+                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"PLC鍙嶉鏈烘鎵嬪惛鐩樻棤浜у搧");
+                return true;
+            }
+            else
+            {
+                var plist = mysqlhelper.GetProductList(PLC_order + "_1");
+                if (plist != null)
+                {
+                    if (!M141Config.Productioncode.Any(u => u.PID == plist[0].PID))
+                    {
+                        int num = M141Config.Productioncode.Count + 1;
+                        M141Config.Productioncode.Add(new ProductionID
+                        {
+                            Uptomesid = num,
+                            PID = plist[0].PID,
+                            SEQUENCE = plist[0].SEQUENCE,
+                            BasketCode = plist[0].BasketCode,
+                            Zword = plist[0].Zword,
+                            //newp.Result = "OK";
+                            SN = plist[0].SN
+                        });
+                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧{plist[0].PID}鏁版嵁璁板綍鎴愬姛");
+                        return true;                       
+                    }
+                    else
+                    {
+                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"浜у搧{plist[0].PID}鏁版嵁閲嶅锛岃褰曞け璐�");
+                        return false;                      
+                    }
+                }
+                else
+                {
+                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"PLC搴忓彿锛歿PLC_order}鏃犳硶浠庢暟鎹簱涓幏鍙栨暟鎹�");
+                    return false;
+                }
+            }
+           
+        }
+
+        [ProcessMethod("", "MEStogetcode", "MES涓婁紶鏁存壒鏁版嵁骞惰幏鍙栨潯鐮�", InvokeType.TestInvoke)]
+        public ResponseMessage MEStogetcode(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
+        {
+            ResponseMessage msg = new ResponseMessage();
+            Plc3 = invokeDevice as PLCBase;
+            bool Issuccess = false;
+            bool Issuccess1 = false;
+
+            var plcnum = Plc3.Read(2100, 1, out _);
+            Issuccess = GetProImformation(plcnum[0]);
+
+            var plcnum1 = Plc3.Read(2102, 1, out _);
+            Issuccess1 = GetProImformation(plcnum1[0]);
+
+            if (!Issuccess && !Issuccess1)
+            {
+                Plc3.WriteSingleAddress(2120, 2, out _);
+                return msg;
+            }
+                      
+            LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧淇℃伅涓婁紶MES瑙﹀彂");
+
+            if (M141Config.Productioncode.Count == 50)
+            {
+                //浜у搧姝e父涓婁紶
+                while(M141Config.Productioncode.Count>0)
+                {
+                    ProductModel newp = new ProductModel();
+                    newp.SEQUENCE = M141Config.Productioncode[0].SEQUENCE;
+                    newp.PID = M141Config.Productioncode[0].PID;
+                    newp.BasketCode = M141Config.Productioncode[0].BasketCode;
+                    newp.Zword = M141Config.Productioncode[0].Zword;
+                    newp.Result = "OK";
+                    newp.SN = M141Config.Productioncode[0].SN;
+                    string tary_ID = string.Empty;
+                    bool isok = UptoMES(newp, "N", out tary_ID);
+                    if (!isok)
+                    {
+                        Plc3.WriteSingleAddress(2120, 2, out _);
+                    }
+                    if (M141Config.Isprint && !string.IsNullOrEmpty(tary_ID))
+                    {
+                        StartPrint(tary_ID, "Honeywell PX240S(300 dpi)");
+                        M141Config.MES_codes.Add(new MES_code
+                        {
+                            Printers_code = tary_ID
+                        });
+                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"鏉$爜锛歿tary_ID}宸茶Е鍙慡6鎵撳嵃骞朵笖淇濆瓨");
+                    }                
+                    M141Config.Productioncode.RemoveAt(0);
+                }
+            }
+            else if (M141Config.Productioncode.Count > 50)
+            {
+                //涓�旀湁浜у搧琚彇璧�
+                for (int i = 0; i < 50; i++)
+                {
+                    ProductModel newp = new ProductModel();
+                    newp.SEQUENCE = M141Config.Productioncode[-1].SEQUENCE;
+                    newp.PID = M141Config.Productioncode[-1].PID;
+                    newp.BasketCode = M141Config.Productioncode[-1].BasketCode;
+                    newp.Zword = M141Config.Productioncode[-1].Zword;
+                    newp.Result = "OK";
+                    newp.SN = M141Config.Productioncode[-1].SN;
+                    string tary_ID = string.Empty;
+                    bool isok = UptoMES(newp, "N", out tary_ID);
+                    if (!isok)
+                    {
+                        Plc3.WriteSingleAddress(2120, 2, out _);
+                    }
+                    if (M141Config.Isprint && !string.IsNullOrEmpty(tary_ID))
+                    {
+                        StartPrint(tary_ID, "Honeywell PX240S(300 dpi)");
+                        M141Config.MES_codes.Add(new MES_code
+                        {
+                            Printers_code = tary_ID
+                        });
+                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"鏉$爜锛歿tary_ID}宸茶Е鍙慡6鎵撳嵃骞朵笖淇濆瓨");
+                    }
+                    M141Config.Productioncode.RemoveAt(-1);
+                }
+                M141Config.Productioncode.Clear();
+            }
+            else if (M141Config.Productioncode.Count < 50)
+            {
+                //浜у搧缂哄皯闇�瑕侀澶栫殑鏉$爜琛ユ晳
+                while (M141Config.Productioncode.Count > 0)
+                {
+                    ProductModel newp = new ProductModel();
+                    newp.SEQUENCE = M141Config.Productioncode[0].SEQUENCE;
+                    newp.PID = M141Config.Productioncode[0].PID;
+                    newp.BasketCode = M141Config.Productioncode[0].BasketCode;
+                    newp.Zword = M141Config.Productioncode[0].Zword;
+                    newp.Result = "OK";
+                    newp.SN = M141Config.Productioncode[0].SN;
+                    string tary_ID = string.Empty;
+                    bool isok = false;
+                                                        
+                    if (M141Config.Productioncode.Count==1)
+                    {
+                        isok = UptoMES(newp, "Y", out tary_ID);
+                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"浜у搧{newp.PID}瑙﹀彂闆舵暟灏剧洏");
+                    }
+                    else
+                    {
+                        isok = UptoMES(newp, "N", out tary_ID);
+                    }
+                    if (!isok)
+                    {
+                        Plc3.WriteSingleAddress(2120, 2, out _);
+                    }
+                    if (M141Config.Isprint && !string.IsNullOrEmpty(tary_ID))
+                    {
+                        StartPrint(tary_ID, "Honeywell PX240S(300 dpi)");
+                        M141Config.MES_codes.Add(new MES_code
+                        {
+                            Printers_code = tary_ID
+                        });
+                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"鏉$爜锛歿tary_ID}宸茶Е鍙慡6鎵撳嵃骞朵笖淇濆瓨");
+                    }
+                    M141Config.Productioncode.RemoveAt(0);
+                }
+            }
+            if (Issuccess && Issuccess1)
+            {
+                Plc3.WriteSingleAddress(2120, 1, out _);
+            }
+            else
+            {
+                Plc3.WriteSingleAddress(2120, 2, out _);
+            }
+            return msg;
+        }
 
         [ProcessMethod("", "MESup1", "MES涓婁紶杩涙枡鍙g┖绡�", InvokeType.TestInvoke)]
         public ResponseMessage MESup1(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
@@ -871,7 +1130,6 @@
                                 }
                                 Plc1.WriteSingleAddress(1590, 2, out _);
                             }
-
                             LogAsync(DateTime.Now, obj?.zstatus == "200" ? EnumHelper.LogLevel.Information : EnumHelper.LogLevel.Exception, $"RabbitMQ 绡叿  杩涙枡鍙f弧杞� 涓婁紶{(obj?.zstatus == "200" ? "鎴愬姛" : "澶辫触")}   {obj?.zstatus}");
                         }
                         catch
@@ -892,8 +1150,6 @@
                 LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"宸插叧闂璵es杩炴帴");
                 Plc1.WriteSingleAddress(1590, 1, out _);
             }
-
-
             return msg;
         }
 
@@ -909,7 +1165,6 @@
                 string Msg = Task.Run(() => mqtt.MESForBasketAsync("3", "DS02217", ConfigAOI1.PlcAndBasketcodes.Any(u => u.id == num) ? ConfigAOI1.PlcAndBasketcodes.FirstOrDefault(u => u.id == num).code : "NoRead", "0", ConfigAOI1.mesnum3.ToString())).Result;
                 if (Msg != null)
                 {
-
                     try
                     {
                         var obj = JsonConvert.DeserializeObject<AutoLineMacQueueBak>(Msg);

--
Gitblit v1.8.0