yaoxiaohan vor 9 Monaten
Ursprung
Commit
2286ef12dc
31 geänderte Dateien mit 2853 neuen und 569 gelöschten Zeilen
  1. 117 0
      TeamAAS-VM/Core/FileHelper.cs
  2. 98 0
      TeamAAS-VM/Core/FileNameTemplate.cs
  3. 640 129
      TeamAAS-VM/Core/Management.cs
  4. 103 10
      TeamAAS-VM/Core/RectangleCenterCalculator.cs
  5. 34 3
      TeamAAS-VM/Interfaces/IConfigService.cs
  6. 21 4
      TeamAAS-VM/Interfaces/IMesService.cs
  7. 2 2
      TeamAAS-VM/Interfaces/IRemoteCommandService.cs
  8. 180 0
      TeamAAS-VM/Models/CTQ_Data.cs
  9. 109 0
      TeamAAS-VM/Models/DataFormCtq.cs
  10. 79 5
      TeamAAS-VM/Models/DeviceInfo.cs
  11. 27 0
      TeamAAS-VM/Models/PLC/PlcPoint.cs
  12. 16 0
      TeamAAS-VM/Models/PressureModel.cs
  13. 12 0
      TeamAAS-VM/Models/Product/ProcedureModel.cs
  14. 11 11
      TeamAAS-VM/Models/ShowRender.cs
  15. 1 1
      TeamAAS-VM/Properties/AssemblyInfo.cs
  16. 9 0
      TeamAAS-VM/Resources/Languages/Lang.Designer.cs
  17. 1 0
      TeamAAS-VM/Resources/Languages/Lang.resx
  18. 27 0
      TeamAAS-VM/Resources/Languages/Lang.zh-TW.resx
  19. 165 21
      TeamAAS-VM/Services/ConfigService.cs
  20. 206 37
      TeamAAS-VM/Services/MesService.cs
  21. 96 16
      TeamAAS-VM/Services/RemoteCommandService.cs
  22. 4 0
      TeamAAS-VM/TeamAAS-VP.csproj
  23. 43 0
      TeamAAS-VM/ValueConverter/ImageFileNameFormatConverter.cs
  24. 3 1
      TeamAAS-VM/ViewModels/HomeViewModel.cs
  25. 1 15
      TeamAAS-VM/ViewModels/MainWindowViewModel.cs
  26. 124 10
      TeamAAS-VM/ViewModels/SettingViewModel.cs
  27. 273 67
      TeamAAS-VM/Views/Home/ShowVisionRender.xaml.cs
  28. 2 2
      TeamAAS-VM/Views/HomeView.xaml
  29. 47 10
      TeamAAS-VM/Views/Product/ProcedureParams.xaml
  30. 398 225
      TeamAAS-VM/Views/SettingView.xaml
  31. 4 0
      TeamAAS-VM/Views/SettingView.xaml.cs

+ 117 - 0
TeamAAS-VM/Core/FileHelper.cs

@@ -863,5 +863,122 @@ namespace TeamAAS_VP.Core
             }
             }
         }
         }
         #endregion
         #endregion
+
+        #region 写CTQ的csv
+        public static void WriteDataToCSV(DataFormCtq cd)
+        {
+            string s1, s2, s3, s4,
+                t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18,
+                r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18;
+            //
+            string path = "D:\\Data\\产品数据\\";
+            if (!Directory.Exists(path))
+            {
+                Directory.CreateDirectory(path);
+            }
+            //
+            t1 = "PPID";
+            t2 = "PROCESS_NAME";
+            t3 = "PROCESS_START_TIME";
+            t4 = "CTQ_NAME";
+            t5 = "CTQ_VALUE";
+            t6 = "CTQ_LSL";
+            t7 = "CTQ_USL";
+            t8 = "PROCESS_END_TIME";
+            t9 = "SUPPLIER_NAME";
+            t10 = "COMMODITY_TYPE";
+            t11 = "REVISION";
+            t12 = "WO#";
+            t13 = "MFG_LOT#";
+            t14 = "MFG_ASSY_LINE";
+            t15 = "PROCESS_OUTCOME";
+            t16 = "PROCESS_MACHINE_ID";
+            t17 = "CTQ_UNIT_OF_MEASURE";
+            t18 = "ERROR_MESSAGE";
+            //
+            r1 = cd.PPID;
+            r2 = cd.PROCESS_NAME;
+            r3 = cd.PROCESS_START_TIME;
+            r4 = cd.CTQ_NAME;
+            r5 = cd.CTQ_VALUE.ToString();
+            r6 = cd.CTQ_LSL.ToString();
+            r7 = cd.CTQ_USL.ToString();
+            r8 = cd.PROCESS_END_TIME;
+            r9 = cd.SUPPLIER_NAME;
+            r10 = cd.COMMODITY_TYPE;
+            r11 = cd.REVISION;
+            r12 = cd.WO;
+            r13 = cd.MFG_LOT;
+            r14 = cd.MFG_ASSY_LINE;
+            r15 = cd.PROCESS_OUTCOME;
+            r16 = cd.PROCESS_MACHINE_ID;
+            r17 = cd.CTQ_UNIT_OF_MEASURE;
+            r18 = cd.ERROR_MESSAGE;
+
+            //=========================
+            s1 = path;
+            s2 = DateTime.Now.ToString("yyyyMMdd"); //表格命名以天记录
+            s3 = t1 + "," + t2 + "," + t3 + "," + t4 + "," + t5 + "," + t6 + "," + t7 + "," + t8 + "," + t9 + "," + t10
+                + "," + t11 + "," + t12 + "," + t13 + "," + t14 + "," + t15 + "," + t16 + "," + t17 + "," + t18;
+            s4 = r1 + "," + r2 + "," + r3 + "," + r4 + "," + r5 + "," + r6 + "," + r7 + "," + r8 + "," + r9 + "," + r10
+                + "," + r11 + "," + r12 + "," + r13 + "," + r14 + "," + r15 + "," + r16 + "," + r17 + "," + r18;
+            //
+            Save(s1, s2, s3, s4);
+        }
+
+
+
+        //写csv
+        public static bool Save(string fullPath, string fileName, string RowName, string Data)
+        {
+            bool result = true;
+            try
+            {
+                if (!Directory.Exists(fullPath))
+                {
+                    Directory.CreateDirectory(fullPath);
+                }
+
+                if (fileName == null)
+                {
+                    fileName = DateTime.Now.ToString("yyyyMMdd");
+                }
+
+                string text = "";
+                string path = fullPath + "\\" + text;
+                string text2 = ".csv";
+                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
+                if (!File.Exists(fullPath + "\\" + fileNameWithoutExtension + fileName + text2))
+                {
+                    using (File.Create(fullPath + "\\" + fileNameWithoutExtension + fileName + text2))
+                    {
+                    }
+
+                    FileStream fileStream2 = new FileStream(fullPath + "\\" + fileNameWithoutExtension + fileName + text2, FileMode.Append);
+                    StreamWriter streamWriter = new StreamWriter(fileStream2, Encoding.UTF8);
+                    streamWriter.WriteLine(RowName);
+                    streamWriter.WriteLine(Data);
+                    streamWriter.Flush();
+                    streamWriter.Close();
+                    fileStream2.Close();
+                }
+                else
+                {
+                    FileStream fileStream2 = new FileStream(fullPath + "\\" + fileNameWithoutExtension + fileName + text2, FileMode.Append);
+                    StreamWriter streamWriter = new StreamWriter(fileStream2, Encoding.UTF8);
+                    streamWriter.WriteLine(Data);
+                    streamWriter.Flush();
+                    streamWriter.Close();
+                    fileStream2.Close();
+                }
+            }
+            catch
+            {
+                result = false;
+            }
+
+            return result;
+        }
+        #endregion
     }
     }
 }
 }

+ 98 - 0
TeamAAS-VM/Core/FileNameTemplate.cs

@@ -0,0 +1,98 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core
+{
+    public class FileNameTemplate
+    {
+        private readonly string _template;
+        private readonly Dictionary<string, Func<object>> _variables;
+
+        public FileNameTemplate(string template)
+        {
+            _template = template ?? throw new ArgumentNullException(nameof(template));
+            _variables = new Dictionary<string, Func<object>>(StringComparer.OrdinalIgnoreCase);
+
+            // 注册内置变量
+            RegisterDefaultVariables();
+        }
+
+        // 注册自定义变量
+        public void RegisterVariable(string name, Func<object> valueProvider)
+        {
+            _variables[name] = valueProvider ?? throw new ArgumentNullException(nameof(valueProvider));
+        }
+
+        // 生成文件名
+        public string Generate()
+        {
+            string result = _template;
+
+            // 查找所有 {变量名[:格式化字符串]} 格式的占位符
+            var matches = Regex.Matches(_template, @"\{([^}:]+)(?::([^}]+))?\}");
+
+            foreach (Match match in matches)
+            {
+                string fullPlaceholder = match.Value;
+                string varName = match.Groups[1].Value;
+                string format = match.Groups[2].Success ? match.Groups[2].Value : null;
+
+                if (_variables.TryGetValue(varName, out var valueProvider))
+                {
+                    object value = valueProvider();
+                    string replacement = FormatValue(value, format);
+                    result = result.Replace(fullPlaceholder, replacement);
+                }
+            }
+
+            // 移除文件名中不允许的字符
+            result = SanitizeFileName(result);
+
+            return result;
+        }
+
+        private string FormatValue(object value, string format)
+        {
+            if (value == null) return "";
+
+            // 如果是日期时间类型,应用格式
+            if (value is DateTime dateTime && !string.IsNullOrEmpty(format))
+            {
+                return dateTime.ToString(format);
+            }
+
+            // 如果是数值类型,应用格式
+            if (value is IFormattable formattable && !string.IsNullOrEmpty(format))
+            {
+                return formattable.ToString(format, null);
+            }
+
+            return value.ToString();
+        }
+
+        private string SanitizeFileName(string fileName)
+        {
+            // 移除文件名中不允许的字符
+            char[] invalidChars = System.IO.Path.GetInvalidFileNameChars();
+            foreach (char c in invalidChars)
+            {
+                fileName = fileName.Replace(c.ToString(), "");
+            }
+            return fileName;
+        }
+
+        private void RegisterDefaultVariables()
+        {
+            // 日期时间变量
+            RegisterVariable("Now", () => DateTime.Now);
+            RegisterVariable("Today", () => DateTime.Today);
+            RegisterVariable("UtcNow", () => DateTime.UtcNow);
+
+            // 可以在这里添加更多内置变量
+        }
+    }
+}

+ 640 - 129
TeamAAS-VM/Core/Management.cs

@@ -1,63 +1,30 @@
-using Basler.Pylon;
-using Cognex.VisionPro;
-using Cognex.VisionPro.ToolBlock;
-using CSScripting;
-using iTextSharp.testutils;
-using MathNet.Numerics.Distributions;
+using Cognex.VisionPro.ToolBlock;
 using MathNet.Numerics.LinearAlgebra;
 using MathNet.Numerics.LinearAlgebra;
-using MathNet.Numerics.RootFinding;
-using NPOI.SS.Formula.Functions;
-using NPOI.Util;
-using Opc.Ua;
 using OpenCvSharp;
 using OpenCvSharp;
-using OpenCvSharp.Flann;
 using Prism.Events;
 using Prism.Events;
 using Prism.Ioc;
 using Prism.Ioc;
 using Prism.Mvvm;
 using Prism.Mvvm;
 using Prism.Regions;
 using Prism.Regions;
-using Prism.Services.Dialogs;
 using System;
 using System;
-using System.Collections;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Collections.ObjectModel;
-using System.ComponentModel;
-using System.Diagnostics;
 using System.Drawing;
 using System.Drawing;
 using System.IO;
 using System.IO;
 using System.Linq;
 using System.Linq;
-using System.Net.Sockets;
-using System.Reflection.Metadata;
-using System.Security.Cryptography;
 using System.Text;
 using System.Text;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Documents;
-using System.Windows.Interop;
 using System.Windows.Media;
 using System.Windows.Media;
-using System.Windows.Media.Media3D;
-using Team.FFFeederService;
 using Team.FFFeederService.Interfaces;
 using Team.FFFeederService.Interfaces;
-using TeamAAS_VP;
 using TeamAAS_VP.Core.PLCs;
 using TeamAAS_VP.Core.PLCs;
-using TeamAAS_VP.Core.Robots;
 using TeamAAS_VP.Core.ScrewDriver;
 using TeamAAS_VP.Core.ScrewDriver;
-using TeamAAS_VP.Data;
 using TeamAAS_VP.Enums;
 using TeamAAS_VP.Enums;
 using TeamAAS_VP.Events;
 using TeamAAS_VP.Events;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Models;
-using TeamAAS_VP.Models.Calibration;
-using TeamAAS_VP.Models.Feeder;
-using TeamAAS_VP.Models.Product;
 using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.Resources.Languages;
-using TeamAAS_VP.Services;
-using TeamAAS_VP.ViewModels.Home;
 using TouchSocket.Core;
 using TouchSocket.Core;
 using TouchSocket.Sockets;
 using TouchSocket.Sockets;
-using static MaterialDesignThemes.Wpf.Theme.ToolBar;
-using static Org.BouncyCastle.Math.EC.ECCurve;
-using static System.Windows.Forms.AxHost;
 
 
 namespace TeamAAS_VP.Core
 namespace TeamAAS_VP.Core
 {
 {
@@ -107,6 +74,7 @@ namespace TeamAAS_VP.Core
         /// 超时自动停止秒数
         /// 超时自动停止秒数
         /// </summary>
         /// </summary>
         private int _pressureMaxDurationSeconds = 30; //超时自动停止秒数
         private int _pressureMaxDurationSeconds = 30; //超时自动停止秒数
+        DateTime[] StartCtqTime = new DateTime[3];//开始采集Ctq数据的时间
         #endregion
         #endregion
 
 
         #region 属性
         #region 属性
@@ -185,6 +153,17 @@ namespace TeamAAS_VP.Core
             get { return _CTtime; }
             get { return _CTtime; }
             set { SetProperty(ref _CTtime, value); }
             set { SetProperty(ref _CTtime, value); }
         }
         }
+
+
+        private ObservableCollection<DataFormCtq> _dfc = new ObservableCollection<DataFormCtq>();
+        /// <summary>
+        /// CTQ数据集合
+        /// </summary>
+        public ObservableCollection<DataFormCtq> DFC
+        {
+            get { return _dfc; }
+            set { SetProperty(ref _dfc, value); }
+        }
         #endregion
         #endregion
 
 
         #region 命令
         #region 命令
@@ -1152,13 +1131,21 @@ namespace TeamAAS_VP.Core
         /// </summary>
         /// </summary>
         string PartSN = "";
         string PartSN = "";
         /// <summary>
         /// <summary>
+        /// 产品SN
+        /// </summary>
+        string[] ProductMainSN = new string[10];//产品主sn
+        /// <summary>
+        /// 工单信息
+        /// </summary>
+        string[] wo = new string[10];
+        /// <summary>
         /// 复检结果
         /// 复检结果
         /// </summary>
         /// </summary>
         string gapString = "";
         string gapString = "";
         /// <summary>
         /// <summary>
         /// 二次定位相机的工具坐标
         /// 二次定位相机的工具坐标
         /// </summary>
         /// </summary>
-        PointF DownTool = new PointF();
+        ToolCoord DownTool = new ToolCoord();
         double _FixedUpCameraAngle = 0;
         double _FixedUpCameraAngle = 0;
         double _MoveCameraAngle = 0;
         double _MoveCameraAngle = 0;
 
 
@@ -1177,7 +1164,7 @@ namespace TeamAAS_VP.Core
         Int16 _LastPickINC = 0;
         Int16 _LastPickINC = 0;
         Int16[] _LastMesCheck = new Int16[10];
         Int16[] _LastMesCheck = new Int16[10];
         DateTime[] _LastMesCheckTime = new DateTime[10];
         DateTime[] _LastMesCheckTime = new DateTime[10];
-        Dictionary<int, double> currentPressure = new Dictionary<int, double>();//当前压力
+        double[] currentPressure = new double[10];//当前压力
         /// <summary>
         /// <summary>
         /// PLC命令触发时
         /// PLC命令触发时
         /// </summary>
         /// </summary>
@@ -1201,18 +1188,18 @@ namespace TeamAAS_VP.Core
                     return;
                     return;
                 }
                 }
 
 
-                //获取产品编码
-                _productService.CurrentProductCode = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, 0));
-                //如果产品编码为空,则以当前的时间戳作为编码
-                if (string.IsNullOrEmpty(_productService.CurrentProductCode))
-                {
-                    _productService.CurrentProductCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
-                }
+                ////获取产品编码
+                //_productService.CurrentProductCode = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, 0));
+                ////如果产品编码为空,则以当前的时间戳作为编码
+                //if (string.IsNullOrEmpty(_productService.CurrentProductCode))
+                //{
+                //    _productService.CurrentProductCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
+                //}
 
 
 
 
                 bool isDryMode = plc.ReadNode<bool>(addressConfig.In_DryMode.Address);
                 bool isDryMode = plc.ReadNode<bool>(addressConfig.In_DryMode.Address);
 
 
-                // 触发下相机拍照
+                // 触发下相机拍照--下相机拍屏幕,预定位
                 if (addressConfig.In_DowmCameraExe.Address.Contains(tuple.nodeId))
                 if (addressConfig.In_DowmCameraExe.Address.Contains(tuple.nodeId))
                 {
                 {
                     if (tuple.value is bool state)
                     if (tuple.value is bool state)
@@ -1270,11 +1257,14 @@ namespace TeamAAS_VP.Core
                                     if (visionResult.IsSucceed)
                                     if (visionResult.IsSucceed)
                                     {
                                     {
 
 
-                                        float toolX = (float)(visionResult.X - currentPosition.X);
-                                        float toolY = (float)(visionResult.Y - currentPosition.Y);
+                                        //float toolX = (float)(visionResult.X - currentPosition.X);
+                                        //float toolY = (float)(visionResult.Y - currentPosition.Y);
+
+                                        DowmCameraResults[0] = new OpenCvSharp.Point3f((float)visionResult.X, (float)visionResult.Y, (float)visionResult.U);
+                                        //DownTool = new PointF(toolX, toolY);
+                                        //以LCD的的上边中心创建工具坐标
+                                        DownTool.ComputeTool(currentPosition.X, currentPosition.Y, currentPosition.U, DowmCameraResults[0].X, DowmCameraResults[0].Y);
 
 
-                                        DowmCameraResults[cameraIndex] = new OpenCvSharp.Point3f(toolX, toolY, (float)visionResult.U);
-                                        DownTool = new PointF(toolX, toolY);
                                         await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
                                         await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
                                         return;
                                         return;
                                     }
                                     }
@@ -1309,8 +1299,8 @@ namespace TeamAAS_VP.Core
                                     }
                                     }
                                     // 执行视觉任务
                                     // 执行视觉任务
                                     var _cts = new CancellationTokenSource();
                                     var _cts = new CancellationTokenSource();
-                                    var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 1, null);
-                                    var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 2, null);
+                                    var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, null, _cts.Token, 1, null);
+                                    var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, null, _cts.Token, 2, null);
                                     var visionResults = await Task.WhenAll(task1, task2);
                                     var visionResults = await Task.WhenAll(task1, task2);
                                     if (isDryMode)
                                     if (isDryMode)
                                     {
                                     {
@@ -1322,8 +1312,13 @@ namespace TeamAAS_VP.Core
                                         float toolX = (float)(visionResults[0].X + visionResults[1].X) / 2;
                                         float toolX = (float)(visionResults[0].X + visionResults[1].X) / 2;
                                         float toolY = (float)(visionResults[0].Y + visionResults[1].Y) / 2;
                                         float toolY = (float)(visionResults[0].Y + visionResults[1].Y) / 2;
                                         _FixedUpCameraAngle = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)visionResults[0].X, (float)visionResults[0].Y), new PointF((float)visionResults[1].X, (float)visionResults[1].Y));
                                         _FixedUpCameraAngle = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)visionResults[0].X, (float)visionResults[0].Y), new PointF((float)visionResults[1].X, (float)visionResults[1].Y));
-                                        DowmCameraResults[cameraIndex] = new OpenCvSharp.Point3f(toolX, toolY, (float)_FixedUpCameraAngle);
-                                        DownTool = new PointF(toolX, toolY);
+                                        SendTaskMessage($"屏幕中心点位:{toolX:F3},{toolY:F4},{_FixedUpCameraAngle:F4}", MessageLevel.Info);
+                                        SendTaskMessage($"当前机器人点位:{currentPosition.X:F3},{currentPosition.Y:F4},{currentPosition.U:F4}", MessageLevel.Info);
+                                        DowmCameraResults[0] = new OpenCvSharp.Point3f(toolX, toolY, (float)_FixedUpCameraAngle);
+                                        //DownTool = new PointF(toolX, toolY);
+                                        //以LCD的的上边中心创建工具坐标
+                                        DownTool.ComputeTool(currentPosition.X, currentPosition.Y, currentPosition.U, DowmCameraResults[0].X, DowmCameraResults[0].Y);
+                                        SendTaskMessage($"屏幕Tool:{DownTool.X:F3},{DownTool.Y:F4}", MessageLevel.Info);
                                         await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
                                         await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
                                         return;
                                         return;
                                     }
                                     }
@@ -1419,7 +1414,7 @@ namespace TeamAAS_VP.Core
                                         float toolY = (float)(visionResults[0].Y + visionResults[1].Y) / 2;
                                         float toolY = (float)(visionResults[0].Y + visionResults[1].Y) / 2;
                                         _FixedUpCameraAngle = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)visionResults[0].X, (float)visionResults[0].Y), new PointF((float)visionResults[1].X, (float)visionResults[1].Y));
                                         _FixedUpCameraAngle = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)visionResults[0].X, (float)visionResults[0].Y), new PointF((float)visionResults[1].X, (float)visionResults[1].Y));
                                         DowmCameraResults[cameraIndex] = new OpenCvSharp.Point3f(toolX, toolY, (float)_FixedUpCameraAngle);
                                         DowmCameraResults[cameraIndex] = new OpenCvSharp.Point3f(toolX, toolY, (float)_FixedUpCameraAngle);
-                                        DownTool = new PointF(toolX, toolY);
+                                        //DownTool = new PointF(toolX, toolY);
                                         await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
                                         await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
                                         return;
                                         return;
                                     }
                                     }
@@ -1821,7 +1816,7 @@ namespace TeamAAS_VP.Core
                         }
                         }
                     }
                     }
                 }
                 }
-                // 固定相机取料拍照
+                // 固定相机取料拍照--屏幕拍照,取上边沿中心(防呆作用)
                 else if (addressConfig.In_FixedCameraPickExe.Address.Contains(tuple.nodeId))
                 else if (addressConfig.In_FixedCameraPickExe.Address.Contains(tuple.nodeId))
                 {
                 {
                     if (tuple.value is bool state)
                     if (tuple.value is bool state)
@@ -1883,17 +1878,106 @@ namespace TeamAAS_VP.Core
                             }
                             }
                             if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
                             if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
                             {
                             {
-
-                                Vector<double> p1 = Vector<double>.Build.Dense(new double[] { visionResults[1].X, visionResults[1].Y });
-                                Vector<double> p2 = Vector<double>.Build.Dense(new double[] { visionResults[2].X, visionResults[2].Y });
-                                Vector<double> p3 = Vector<double>.Build.Dense(new double[] { visionResults[3].X, visionResults[3].Y });
-                                Vector<double> p4 = Vector<double>.Build.Dense(new double[] { visionResults[0].X, visionResults[0].Y });
-
-                                var center = RectangleCenterCalculator.CalculateByPCAWithKnownOrder(new List<Vector<double>> { p1, p2, p3, p4 });
-                                UpCameraPutResults[1].X = (float)center.Center[0];
-                                UpCameraPutResults[1].Y = (float)center.Center[1];
+                                Vector<double> p1 = Vector<double>.Build.Dense(new double[] { visionResults[0].X, visionResults[0].Y });
+                                Vector<double> p2 = Vector<double>.Build.Dense(new double[] { visionResults[1].X, visionResults[1].Y });
+                                Vector<double> p3 = Vector<double>.Build.Dense(new double[] { visionResults[2].X, visionResults[2].Y });
+                                Vector<double> p4 = Vector<double>.Build.Dense(new double[] { visionResults[3].X, visionResults[3].Y });
+
+                                //var center = RectangleCenterCalculator.CalculateByDirectMethod(new List<Vector<double>> { p1, p2, p3, p4 });
+                                var center = RectangleCenterCalculator.CalculateOptimalCenter(new List<Vector<double>> { p1, p2, p3, p4 });//0215修改,不考虑点顺序
+                                //UpCameraPutResults[1].X = (float)center.Center[0];
+                                //UpCameraPutResults[1].Y = (float)center.Center[1];
+                                //UpCameraPutResults[1].Z = (float)center.MajorAxisAngle;
+                                UpCameraPutResults[1].X = ((float)center.TopLeft[0] + (float)center.TopRight[0]) / 2;
+                                UpCameraPutResults[1].Y = ((float)center.TopLeft[1] + (float)center.TopRight[1]) / 2;
                                 UpCameraPutResults[1].Z = (float)center.MajorAxisAngle;
                                 UpCameraPutResults[1].Z = (float)center.MajorAxisAngle;
                                 SendTaskMessage($"LCD拍照结果:X={UpCameraPutResults[1].X},Y={UpCameraPutResults[1].Y},Angle={UpCameraPutResults[1].Z}", MessageLevel.Info);
                                 SendTaskMessage($"LCD拍照结果:X={UpCameraPutResults[1].X},Y={UpCameraPutResults[1].Y},Angle={UpCameraPutResults[1].Z}", MessageLevel.Info);
+
+                                var dist1 = RectangleCenterCalculator.Distance(center.TopLeft, center.TopRight);//长1
+                                var dist2 = RectangleCenterCalculator.Distance(center.TopRight, center.BottomRight);//宽1
+                                var dist3 = RectangleCenterCalculator.Distance(center.BottomLeft, center.BottomRight);//长2
+                                var dist4 = RectangleCenterCalculator.Distance(center.TopLeft, center.BottomLeft);//宽2
+                                LogHelper.WriteLogInfo($"dist1={dist1};dist2={dist2};dist3={dist3};dist4={dist4};");
+                                if (currentProduct.GlobalParamListCollection.Count >= 4)
+                                {
+                                    var param = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == 2);
+                                    if (param != null)//长
+                                    {
+                                        var length = Double.Parse(param.Param1);
+                                        var limtDown = Double.Parse(param.Param2);
+                                        var LimtUp = Double.Parse(param.Param3);
+                                        if (!(((length + limtDown) <= dist1) && (dist1 <= (length + LimtUp)) && (((length + limtDown) <= dist3) && (dist3 <= (length + LimtUp)))))
+                                        {
+                                            SendTaskMessage($"屏幕长度超范围:长1={dist1},长2={dist3},para1={length},para2={limtDown},para3={LimtUp}", MessageLevel.Alarm);
+                                            await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                            return;
+                                        }
+                                        SendTaskMessage($"屏幕长度防呆:长1={dist1},长2={dist3},para1={length},para2={limtDown},para3={LimtUp}", MessageLevel.Info);
+                                    }
+                                    param = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == 3);
+                                    if (param != null)//宽
+                                    {
+                                        var length = Double.Parse(param.Param1);
+                                        var limtDown = Double.Parse(param.Param2);
+                                        var LimtUp = Double.Parse(param.Param3);
+                                        if (!(((length + limtDown) <= dist2) && (dist2 <= (length + LimtUp)) && (((length + limtDown) <= dist4) && (dist4 <= (length + LimtUp)))))
+                                        {
+                                            SendTaskMessage($"屏幕宽度超范围:宽1={dist2},宽2={dist4},para1={length},para2={limtDown},para3={LimtUp}", MessageLevel.Alarm);
+                                            await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                            return;
+                                        }
+                                        SendTaskMessage($"屏幕宽度防呆:宽1={dist2},宽2={dist4},para1={length},para2={limtDown},para3={LimtUp}", MessageLevel.Info);
+                                    }
+
+                                    if (currentProduct.GlobalParamListCollection.Count >= 7)
+                                    {
+                                        param = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == 4);
+                                        if (param != null)//X防呆
+                                        {
+                                            var Limt_val = Double.Parse(param.Param1);
+                                            var limtDown = Double.Parse(param.Param2);
+                                            var LimtUp = Double.Parse(param.Param3);
+                                            var dist = UpCameraPutResults[1].X - UpCameraPutResults[0].X;
+                                            if (!(((Limt_val + limtDown) <= dist) && (dist <= (Limt_val + LimtUp))))
+                                            {
+                                                SendTaskMessage($"贴合X防呆超限:X实际差值={dist},X允许差值={Limt_val},下限={limtDown},上限={LimtUp}", MessageLevel.Info);
+                                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                                return;
+                                            }
+                                            SendTaskMessage($"贴合X防呆:X实际差值={dist},X允许差值={Limt_val},下限={limtDown},上限={LimtUp}", MessageLevel.Info);
+                                        }
+                                        param = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == 5);
+                                        if (param != null)//Y防呆
+                                        {
+                                            var Limt_val = Double.Parse(param.Param1);
+                                            var limtDown = Double.Parse(param.Param2);
+                                            var LimtUp = Double.Parse(param.Param3);
+                                            var dist = UpCameraPutResults[1].Y - UpCameraPutResults[0].Y;
+                                            if (!(((Limt_val + limtDown) <= dist) && (dist <= (Limt_val + LimtUp))))
+                                            {
+                                                SendTaskMessage($"贴合Y防呆超限:Y实际差值={dist},Y允许差值={Limt_val},下限={limtDown},上限={LimtUp}", MessageLevel.Info);
+                                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                                return;
+                                            }
+                                            SendTaskMessage($"贴合Y防呆:Y实际差值={dist},Y允许差值={Limt_val},下限={limtDown},上限={LimtUp}", MessageLevel.Info);
+                                        }
+                                        param = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == 6);
+                                        if (param != null)//U防呆
+                                        {
+                                            var Limt_val = Double.Parse(param.Param1);
+                                            var limtDown = Double.Parse(param.Param2);
+                                            var LimtUp = Double.Parse(param.Param3);
+                                            var dist = UpCameraPutResults[1].Z - UpCameraPutResults[0].Z;
+                                            if (!(((Limt_val + limtDown) <= dist) && (dist <= (Limt_val + LimtUp))))
+                                            {
+                                                SendTaskMessage($"贴合U防呆超限:U实际差值={dist},X允许差值={Limt_val},下限={limtDown},上限={LimtUp}", MessageLevel.Info);
+                                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                                return;
+                                            }
+                                            SendTaskMessage($"贴合U防呆:U实际差值={dist},X允许差值={Limt_val},下限={limtDown},上限={LimtUp}", MessageLevel.Info);
+                                        }
+                                    }
+                                }
                             }
                             }
                             else
                             else
                             {
                             {
@@ -1911,7 +1995,7 @@ namespace TeamAAS_VP.Core
                         }
                         }
                     }
                     }
                 }
                 }
-                // 固定相机锁附/组装拍照
+                // 固定相机锁附/组装拍照--外壳拍照
                 else if (addressConfig.In_FixedCameraPutExe.Address.Contains(tuple.nodeId))
                 else if (addressConfig.In_FixedCameraPutExe.Address.Contains(tuple.nodeId))
                 {
                 {
                     if (tuple.value is bool state)
                     if (tuple.value is bool state)
@@ -1972,17 +2056,56 @@ namespace TeamAAS_VP.Core
                             }
                             }
                             if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
                             if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
                             {
                             {
-
-                                Vector<double> p1 = Vector<double>.Build.Dense(new double[] { visionResults[1].X, visionResults[1].Y });
-                                Vector<double> p2 = Vector<double>.Build.Dense(new double[] { visionResults[2].X, visionResults[2].Y });
-                                Vector<double> p3 = Vector<double>.Build.Dense(new double[] { visionResults[3].X, visionResults[3].Y });
-                                Vector<double> p4 = Vector<double>.Build.Dense(new double[] { visionResults[0].X, visionResults[0].Y });
-
-                                var center = RectangleCenterCalculator.CalculateByPCAWithKnownOrder(new List<Vector<double>> { p1, p2, p3, p4 });
-                                UpCameraPutResults[0].X = (float)center.Center[0];
-                                UpCameraPutResults[0].Y = (float)center.Center[1];
+                                Vector<double> p1 = Vector<double>.Build.Dense(new double[] { visionResults[0].X, visionResults[0].Y });
+                                Vector<double> p2 = Vector<double>.Build.Dense(new double[] { visionResults[1].X, visionResults[1].Y });
+                                Vector<double> p3 = Vector<double>.Build.Dense(new double[] { visionResults[2].X, visionResults[2].Y });
+                                Vector<double> p4 = Vector<double>.Build.Dense(new double[] { visionResults[3].X, visionResults[3].Y });
+
+                                //var center = RectangleCenterCalculator.CalculateByDirectMethod(new List<Vector<double>> { p1, p2, p3, p4 });
+                                var center = RectangleCenterCalculator.CalculateOptimalCenter(new List<Vector<double>> { p1, p2, p3, p4 });//0215修改,不考虑点顺序
+                                //UpCameraPutResults[0].X = (float)center.Center[0];
+                                //UpCameraPutResults[0].Y = (float)center.Center[1];
+                                UpCameraPutResults[0].X = ((float)center.TopLeft[0] + (float)center.TopRight[0]) / 2;
+                                UpCameraPutResults[0].Y = ((float)center.TopLeft[1] + (float)center.TopRight[1]) / 2;
                                 UpCameraPutResults[0].Z = (float)center.MajorAxisAngle;
                                 UpCameraPutResults[0].Z = (float)center.MajorAxisAngle;
                                 SendTaskMessage($"产品拍照结果:X={UpCameraPutResults[0].X},Y={UpCameraPutResults[0].Y},Angle={UpCameraPutResults[0].Z}", MessageLevel.Info);
                                 SendTaskMessage($"产品拍照结果:X={UpCameraPutResults[0].X},Y={UpCameraPutResults[0].Y},Angle={UpCameraPutResults[0].Z}", MessageLevel.Info);
+
+                                var dist1 = RectangleCenterCalculator.Distance(center.TopLeft, center.TopRight);//长1
+                                var dist2 = RectangleCenterCalculator.Distance(center.TopRight, center.BottomRight);//宽1
+                                var dist3 = RectangleCenterCalculator.Distance(center.BottomLeft, center.BottomRight);//长2
+                                var dist4 = RectangleCenterCalculator.Distance(center.TopLeft, center.BottomLeft);//宽2
+                                LogHelper.WriteLogInfo($"dist1={dist1};dist2={dist2};dist3={dist3};dist4={dist4};");
+                                if (currentProduct.GlobalParamListCollection.Count >= 4)
+                                {
+                                    var param = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == 0);
+                                    if (param != null)//长
+                                    {
+                                        var length = Double.Parse(param.Param1);
+                                        var limtDown = Double.Parse(param.Param2);
+                                        var LimtUp = Double.Parse(param.Param3);
+                                        if (!(((length + limtDown) <= dist1) && (dist1 <= (length + LimtUp)) && (((length + limtDown) <= dist3) && (dist3 <= (length + LimtUp)))))
+                                        {
+                                            SendTaskMessage($"外壳长度超范围:长1={dist1},长2={dist3},para1={length},para2={limtDown},para3={LimtUp}", MessageLevel.Alarm);
+                                            await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)2);
+                                            return;
+                                        }
+                                        SendTaskMessage($"外壳长度防呆:长1={dist1},长2={dist3},para1={length},para2={limtDown},para3={LimtUp}", MessageLevel.Info);
+                                    }
+                                    param = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == 1);
+                                    if (param != null)//宽
+                                    {
+                                        var length = Double.Parse(param.Param1);
+                                        var limtDown = Double.Parse(param.Param2);
+                                        var LimtUp = Double.Parse(param.Param3);
+                                        if (!(((length + limtDown) <= dist2) && (dist2 <= (length + LimtUp)) && (((length + limtDown) <= dist4) && (dist4 <= (length + LimtUp)))))
+                                        {
+                                            SendTaskMessage($"外壳宽度超范围:宽1={dist2},宽2={dist4},para1={length},para2={limtDown},para3={LimtUp}", MessageLevel.Alarm);
+                                            await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)2);
+                                            return;
+                                        }
+                                        SendTaskMessage($"外壳宽度防呆:宽1={dist2},宽2={dist4},para1={length},para2={limtDown},para3={LimtUp}", MessageLevel.Info);
+                                    }
+                                }
                             }
                             }
                             else
                             else
                             {
                             {
@@ -2062,7 +2185,7 @@ namespace TeamAAS_VP.Core
                             if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
                             if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
                             {
                             {
                                 SendTaskMessage($"固定相机检测OK", MessageLevel.Debug);
                                 SendTaskMessage($"固定相机检测OK", MessageLevel.Debug);
-                                gapString = $"1-{visionResults[0].distance},2-{visionResults[1].distance},3-{visionResults[2].distance},4-{visionResults[3].distance}";
+                                gapString = $"1-{visionResults[0].distance.Split(',')[1]},2-{visionResults[1].distance.Split(',')[1]},3-{visionResults[2].distance.Split(',')[1]},4-{visionResults[3].distance.Split(',')[1]}";
                                 await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)1);
                                 await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)1);
                                 return;
                                 return;
                             }
                             }
@@ -2099,10 +2222,10 @@ namespace TeamAAS_VP.Core
                         {
                         {
                             SendTaskMessage($"收到多相机坐标合并请求,开始合并...", MessageLevel.Debug);
                             SendTaskMessage($"收到多相机坐标合并请求,开始合并...", MessageLevel.Debug);
 
 
-                            if (isDryMode)
+                            if (isDryMode)//空跑模式
                             {
                             {
                                 var point1 = currentProduct.ScrewPoints[0].Clone();
                                 var point1 = currentProduct.ScrewPoints[0].Clone();
-                                SendTaskMessage($"点:1,{point1.X_Position:F3},{point1.Y_Position:F4},{point1.U_Position:F4}", MessageLevel.Info);
+                                SendTaskMessage($"空跑模式点:1,{point1.X_Position:F3},{point1.Y_Position:F4},{point1.U_Position:F4}", MessageLevel.Info);
                                 await point1.WriteToPlcAddress(addressConfig.Out_Screw, plc);
                                 await point1.WriteToPlcAddress(addressConfig.Out_Screw, plc);
                                 await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)1);
                                 await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)1);
                                 await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
                                 await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
@@ -2120,26 +2243,68 @@ namespace TeamAAS_VP.Core
                             }
                             }
                             var currentPosition = robot.GetRobotPos();
                             var currentPosition = robot.GetRobotPos();
 
 
+                            //已经通过下相机拍屏幕两角获取--DownTool
                             //以LCD的中线创建工具坐标
                             //以LCD的中线创建工具坐标
-                            ToolCoord toolCoord = new ToolCoord();
-                            toolCoord.ComputeTool(currentPosition.X, currentPosition.Y, currentPosition.U, UpCameraPutResults[1].X, UpCameraPutResults[1].Y);
-
+                            //ToolCoord toolCoord = new ToolCoord();
+                            //toolCoord.ComputeTool(currentPosition.X, currentPosition.Y, currentPosition.U, UpCameraPutResults[1].X, UpCameraPutResults[1].Y);
 
 
-                            //计算放料角度
-                            double angle = currentPosition.U - UpCameraPutResults[1].Z + UpCameraPutResults[0].Z;
+                            //添加新的补偿算法--20260213
+                            double offset_X = 0, offset_Y = 0, offset_U = 0;
+                            var current = _productService.GetCurrentProduct();
+                            if (current.ScrewPoints == null || current.ScrewPoints.Count <= 0)
+                            {
+                                SendTaskMessage($"未找到任务贴合补偿参数", MessageLevel.Alarm);
+                                await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
+                                return;
+                            }
+                            offset_X = current.ScrewPoints[0].X_Offset;
+                            offset_Y = current.ScrewPoints[0].Y_Offset;
+                            offset_U = current.ScrewPoints[0].U_Offset;
+                            SendTaskMessage($"放料补偿:X={offset_X},Y={offset_Y},U={offset_U}", MessageLevel.Info);
+                            //利用补偿偏差算出,补偿后的壳体中心,p_new
+                            ToolCoord toolCoord2 = new ToolCoord();
+                            toolCoord2.SetTool(offset_X, offset_Y);
+                            var p_new_Vector = Vector<double>.Build.Dense(new double[] { UpCameraPutResults[0].X, UpCameraPutResults[0].Y });
+                            var p_new = toolCoord2.GetToolnCoord(p_new_Vector, UpCameraPutResults[0].Z);
+                            SendTaskMessage($"放料原点:1,{UpCameraPutResults[0].X:F3},{UpCameraPutResults[0].Y:F4},{UpCameraPutResults[0].Z:F4}", MessageLevel.Info);
+                            SendTaskMessage($"放料补偿点:2,{p_new[0]:F3},{p_new[1]:F4},{UpCameraPutResults[0].Z:F4}", MessageLevel.Info);
+
+                            //计算放料角度--带入下相机的角度
+                            double angle = currentPosition.U - DowmCameraResults[0].Z + UpCameraPutResults[0].Z + offset_U;
 
 
                             //将产品的中心点坐标转换为Tool0下的坐标
                             //将产品的中心点坐标转换为Tool0下的坐标
                             var point = currentProduct.ScrewPoints[0].Clone();
                             var point = currentProduct.ScrewPoints[0].Clone();
-                            var pn = Vector<double>.Build.Dense(new double[] { UpCameraPutResults[0].X, UpCameraPutResults[0].Y });
-                            var p0 = toolCoord.GetTool0Coord(pn, angle);
+                            //var pn = Vector<double>.Build.Dense(new double[] { UpCameraPutResults[0].X, UpCameraPutResults[0].Y });
+                            var pn = p_new;
+                            //var p0 = toolCoord.GetTool0Coord(pn, angle);
+                            var p0 = DownTool.GetTool0Coord(pn, angle);//下相机拍照tool,动态Tool
                             point.X_Position = (float)p0[0];
                             point.X_Position = (float)p0[0];
                             point.Y_Position = (float)p0[1];
                             point.Y_Position = (float)p0[1];
                             point.U_Position = (float)angle;
                             point.U_Position = (float)angle;
                             PlaceActualCoord = new OpenCvSharp.Point3f(point.X_Position, point.Y_Position, point.U_Position);
                             PlaceActualCoord = new OpenCvSharp.Point3f(point.X_Position, point.Y_Position, point.U_Position);
-                            SendTaskMessage($"点:1,{point.X_Position:F3},{point.Y_Position:F4},{point.U_Position:F4}", MessageLevel.Info);
-                            await point.WriteToPlcAddress(addressConfig.Out_Screw, plc);
+                            //SendTaskMessage($"点:1,{point.X_Position:F3},{point.Y_Position:F4},{point.U_Position:F4}", MessageLevel.Info);
+                            SendTaskMessage($"目标点:3,{point.X_Position:F3},{point.Y_Position:F4},{point.U_Position:F4}", MessageLevel.Info);
+                            await point.WriteToPlcAddressEx2(addressConfig.Out_Screw, plc);//补偿参数提前代入计算,直接发最终点位
                             await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)1);
                             await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)1);
                             await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
                             await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
+
+
+                            //原计算方法--20260213
+                            ////计算放料角度
+                            //double angle = currentPosition.U - UpCameraPutResults[1].Z + UpCameraPutResults[0].Z;
+
+                            ////将产品的中心点坐标转换为Tool0下的坐标
+                            //var point = currentProduct.ScrewPoints[0].Clone();
+                            //var pn = Vector<double>.Build.Dense(new double[] { UpCameraPutResults[0].X, UpCameraPutResults[0].Y });
+                            //var p0 = toolCoord.GetTool0Coord(pn, angle);
+                            //point.X_Position = (float)p0[0];
+                            //point.Y_Position = (float)p0[1];
+                            //point.U_Position = (float)angle;
+                            //PlaceActualCoord = new OpenCvSharp.Point3f(point.X_Position, point.Y_Position, point.U_Position);
+                            //SendTaskMessage($"点:1,{point.X_Position:F3},{point.Y_Position:F4},{point.U_Position:F4}", MessageLevel.Info);
+                            //await point.WriteToPlcAddress(addressConfig.Out_Screw, plc);
+                            //await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)1);
+                            //await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
                         }
                         }
                         else
                         else
                         {
                         {
@@ -2202,7 +2367,7 @@ namespace TeamAAS_VP.Core
                             var _cts = new CancellationTokenSource();
                             var _cts = new CancellationTokenSource();
 
 
                             await _remoteCommandService.SetLightBeforePhoto(qrCodeProcess);
                             await _remoteCommandService.SetLightBeforePhoto(qrCodeProcess);
-                            var qrCodeResult = _remoteCommandService.ExecutePhoto(qrCodeProcess, out CogToolBlockTerminalCollection outputCollection);
+                            var qrCodeResult = _remoteCommandService.ExecutePhoto(1, qrCodeProcess, out CogToolBlockTerminalCollection outputCollection);
 
 
                             if (qrCodeResult && outputCollection.Contains("QR"))
                             if (qrCodeResult && outputCollection.Contains("QR"))
                             {
                             {
@@ -2234,7 +2399,7 @@ namespace TeamAAS_VP.Core
                             await plc.WriteNodeAsync(addressConfig.Out_QrCodePhotoResault.Address, (Int16)0);
                             await plc.WriteNodeAsync(addressConfig.Out_QrCodePhotoResault.Address, (Int16)0);
                         }
                         }
                     }
                     }
-                   
+
                 }
                 }
                 else
                 else
                 {
                 {
@@ -2255,60 +2420,158 @@ namespace TeamAAS_VP.Core
                                 }
                                 }
                                 var code = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, i));
                                 var code = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, i));
                                 string comp = PartSN;
                                 string comp = PartSN;
-                                //code = "CN0NJTYVLXU0061W0001";
-                                //comp = "110RNYV4123456789012345";
+                                SendTaskMessage($"产品sn:{code},辅料码:{comp}", MessageLevel.Info);
                                 //询问mes
                                 //询问mes
                                 if (state == 1)
                                 if (state == 1)
                                 {
                                 {
-                                    //这里缺少从MES获取产品配方的内容,需要补充
+                                    // 这里缺少从MES获取产品配方的内容,需要补充
 
 
-                                    _LastMesCheckTime[i] = DateTime.UtcNow;
+                                    _LastMesCheckTime[i] = (await _mesService.GetServerTimeAsync(i, code, 2)).Now;
 
 
-                                    LogHelper.WriteLogMes($"【mes开始QUERY】");
-                                    SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
-                                    (bool isSuccess, string response) = await _mesService.StationGetAsync(i,code, comp, 2);
-                                    if (i == 0)
+                                    //获取当前工位的配置
+                                    var stationConfig = _configService.GetDeviceInfo(i);
+                                    if (stationConfig.EnableDoubleMes)
                                     {
                                     {
-                                        SendTaskMessage($"收到当前过站检查请求(当站是否生产)...", MessageLevel.Debug);
-                                    }
-                                    else
-                                    {
-                                        SendTaskMessage($"收到{i}过站检查请求(当站是否生产)...", MessageLevel.Debug);
-                                    }
-                                    if (isSuccess)
-                                    {
-                                        //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
-                                        await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
-                                        await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
+                                        SendTaskMessage($"收到{i}:{stationConfig.DeviceName}过站检查请求(当站是否生产)(当前需要双MES验证)...", MessageLevel.Debug);
 
 
-                                        LogHelper.WriteLogMes($"询问mes成功");
-                                        SendTaskMessage($"询问mes成功", MessageLevel.Debug);
+                                        LogHelper.WriteLogMes($"【mes开始QUERY】");
+                                        SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
+                                        (bool isSuccess, string response) = await _mesService.StationGetExAsync(i, code, "", 2);//询问mes
+                                        if (isSuccess)
+                                        {
+                                            LogHelper.WriteLogMes($"询问mes成功");
+                                            SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+                                            string ProductMainSN_Temp = "";
+                                            if (response != "MES功能未启用!")
+                                            {
+                                                string[] item = response.Split('\n');
+                                                //获取过度件sn
+                                                string snItem = item.FirstOrDefault(f => f.Contains("sn="));
+                                                if (snItem != null)
+                                                {
+                                                    ProductMainSN_Temp = snItem.Replace("sn=", "").Trim();
+                                                    SendTaskMessage($"过度件sn:{ProductMainSN_Temp}", MessageLevel.Info);
+                                                }
+                                            }
+
+                                            (bool isSuccess2, string response2) = await _mesService.StationGetAsync(i, ProductMainSN_Temp, "", 2);//询问mes
+                                            if (isSuccess2)
+                                            {
+                                                LogHelper.WriteLogMes($"第二次询问mes成功");
+                                                SendTaskMessage($"第二次询问mes成功:{response2}", MessageLevel.Debug);
+                                                if (response2 != "MES功能未启用!")
+                                                {
+                                                    string[] item = response2.Split('\n');
+                                                    //获取产品主sn和wo用于后续上传数据使用
+                                                    string snItem = item.FirstOrDefault(f => f.Contains("sn="));
+                                                    if (snItem != null)
+                                                    {
+                                                        ProductMainSN[i] = snItem.Replace("sn=", "").Trim();
+                                                        if (i == 0)
+                                                        {
+                                                            _productService.CurrentProductCode = ProductMainSN[i];
+                                                        }
+                                                        SendTaskMessage($"产品主sn:{ProductMainSN[i]}", MessageLevel.Info);
+                                                    }
+                                                    string woItem = item.FirstOrDefault(f => f.Contains("wo="));
+                                                    if (woItem != null)
+                                                    {
+                                                        wo[i] = woItem.Replace("wo=", "").Trim();
+                                                        SendTaskMessage($"工单信息:{wo[i]}", MessageLevel.Info);
+                                                    }
+                                                }
+
+                                                //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+                                                await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
+                                                await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
+                                            }
+                                            else
+                                            {
+                                                LogHelper.WriteLogMes($"第二次询问mes失败");
+                                                SendTaskMessage($"第二次询问mes失败:{response2}", MessageLevel.Error);
+
+                                                //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+                                                await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
+                                                await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)2);
+                                            }
+                                        }
+                                        else
+                                        {
+                                            //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+                                            await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
+                                            await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)2);
+
+                                            LogHelper.WriteLogMes($"询问mes失败");
+                                            SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
 
 
+                                            //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+                                            await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
+                                            await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)2);
+                                        }
                                         LogHelper.WriteLogMes($"【mes结束QUERY】");
                                         LogHelper.WriteLogMes($"【mes结束QUERY】");
                                         SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
                                         SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
-                                        return;
                                     }
                                     }
                                     else
                                     else
                                     {
                                     {
-                                        //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
-                                        await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
-                                        await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)2);
-
-                                        LogHelper.WriteLogMes($"询问mes失败");
-                                        SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
+                                        SendTaskMessage($"收到{i}:{stationConfig.DeviceName}过站检查请求(当站是否生产)(当前不需要双MES验证)...", MessageLevel.Debug);
 
 
+                                        LogHelper.WriteLogMes($"【mes开始QUERY】");
+                                        SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
+                                        (bool isSuccess, string response) = await _mesService.StationGetAsync(i, code, "", 2);//询问mes
+                                        if (isSuccess)
+                                        {
+                                            if (response != "MES功能未启用!")
+                                            {
+                                                string[] item = response.Split('\n');
+                                                //获取产品主sn和wo用于后续上传数据使用
+                                                string snItem = item.FirstOrDefault(f => f.Contains("sn="));
+                                                if (snItem != null)
+                                                {
+                                                    ProductMainSN[i] = snItem.Replace("sn=", "").Trim();
+                                                    if (i == 0)
+                                                    {
+                                                        _productService.CurrentProductCode = ProductMainSN[i];
+                                                    }
+                                                    SendTaskMessage($"产品主sn:{ProductMainSN[i]}", MessageLevel.Info);
+                                                }
+                                                string woItem = item.FirstOrDefault(f => f.Contains("wo="));
+                                                if (woItem != null)
+                                                {
+                                                    wo[i] = woItem.Replace("wo=", "").Trim();
+                                                    SendTaskMessage($"工单信息:{wo[i]}", MessageLevel.Info);
+                                                }
+                                            }
+
+                                            LogHelper.WriteLogMes($"询问mes成功");
+                                            SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+                                            //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+                                            await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
+                                            await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
+                                        }
+                                        else
+                                        {
+                                            LogHelper.WriteLogMes($"询问mes失败");
+                                            SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
+                                            //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+                                            await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
+                                            await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)2);
+                                        }
                                         LogHelper.WriteLogMes($"【mes结束QUERY】");
                                         LogHelper.WriteLogMes($"【mes结束QUERY】");
                                         SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
                                         SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
-                                        return;
                                     }
                                     }
                                 }
                                 }
                                 // 上传本站数据
                                 // 上传本站数据
                                 else if (state == 2)
                                 else if (state == 2)
                                 {
                                 {
-                                    SendTaskMessage($"收到{i}上传本站数据请求...", MessageLevel.Debug);
+                                    DFC.Clear();
+
+                                    //获取当前工位的配置
+                                    var stationConfig = _configService.GetDeviceInfo(i);
+                                    SendTaskMessage($"收到{i}:{stationConfig.DeviceName}上传本站数据请求...", MessageLevel.Debug);
+                                    //从服务器中获取当前时间
+                                    var serverTimeResult = await _mesService.GetServerTimeAsync(i, code, 2);
 
 
-                                    //这里缺少上传MES的本站数据结果及开始和结束时间,需要补充
-                                    double ct = DateTime.UtcNow.Subtract(_LastMesCheckTime[i]).TotalSeconds;
+                                    double ct = serverTimeResult.Now.Subtract(_LastMesCheckTime[i]).TotalSeconds;
                                     if (i == 0)
                                     if (i == 0)
                                     {
                                     {
                                         CTtime = ct;
                                         CTtime = ct;
@@ -2326,7 +2589,7 @@ namespace TeamAAS_VP.Core
                                     assemblyRecord.AssemblyDurationSeconds = ct;
                                     assemblyRecord.AssemblyDurationSeconds = ct;
                                     assemblyRecord.AssemblyPressure = pressure;
                                     assemblyRecord.AssemblyPressure = pressure;
                                     assemblyRecord.DeviceId = i;
                                     assemblyRecord.DeviceId = i;
-                                    assemblyRecord.DeviceName = $"";
+                                    assemblyRecord.DeviceName = stationConfig.DeviceName;
                                     assemblyRecord.OperatorName = _systemDatabaseService.GetCurrentUser().UserName;
                                     assemblyRecord.OperatorName = _systemDatabaseService.GetCurrentUser().UserName;
                                     assemblyRecord.Success = resultIndex == 1 ? true : false;
                                     assemblyRecord.Success = resultIndex == 1 ? true : false;
                                     assemblyRecord.DownCameraCoord1 = "";
                                     assemblyRecord.DownCameraCoord1 = "";
@@ -2370,19 +2633,162 @@ namespace TeamAAS_VP.Core
 
 
                                     LogHelper.WriteLogMes($"【mes开始ADD】");
                                     LogHelper.WriteLogMes($"【mes开始ADD】");
                                     SendTaskMessage($"mes开始ADD", MessageLevel.Info);
                                     SendTaskMessage($"mes开始ADD", MessageLevel.Info);
+
+                                    Dictionary<string, string> data = new Dictionary<string, string>();
+
                                     string gap = ""; string press = ""; string presstime = ""; string assypress = "";
                                     string gap = ""; string press = ""; string presstime = ""; string assypress = "";
-                                    if (i==0)
+                                    if (i == 0)
                                     {
                                     {
                                         gap = gapString;
                                         gap = gapString;
-                                        assypress = currentPressure[0].ToString();
+                                        try
+                                        {
+                                            assypress = currentPressure[0].ToString("F2");
+                                            if (currentPressure[0] >= p1.PressureDownLimit && currentPressure[0] <= p1.PressureUpLimit)
+                                            {
+                                                resultIndex = 1;
+                                            }
+                                            else
+                                            {
+                                                resultIndex = 2;
+                                            }
+                                        }
+                                        catch (Exception ex)
+                                        {
+                                            assypress = "0";
+                                            resultIndex = 2;
+                                        }
+                                        data.Add("gap", gap);
+                                        data.Add("assy_pressure", assypress);
+                                        SendTaskMessage($"gap:{gap},组装压力:{assypress}", MessageLevel.Info);
+                                        #region 数据
+                                        bool assyPresRes;
+                                        if (currentPressure[0] >= p1.PressureDownLimit && currentPressure[0] <= p1.PressureUpLimit)
+                                        {
+                                            assyPresRes = true;
+                                        }
+                                        else assyPresRes = false;
+                                        DFC.Clear();
+                                        DFC.Add(new DataFormCtq
+                                        {
+                                            PPID = ProductMainSN[i],
+                                            PROCESS_NAME = stationConfig.DataInfo.PROCESS_NAME,
+                                            PROCESS_START_TIME = _LastMesCheckTime[i].ToString(),
+                                            CTQ_NAME = "Gap",
+                                            CTQ_VALUE = gap,
+                                            CTQ_LSL = "",
+                                            CTQ_USL = "",
+                                            PROCESS_END_TIME = serverTimeResult.Now.ToString(),
+                                            SUPPLIER_NAME = stationConfig.DataInfo.SUPPLIER_NAME,
+                                            COMMODITY_TYPE = stationConfig.DataInfo.COMMODITY_TYPE,
+                                            REVISION = stationConfig.DataInfo.REVISION,
+                                            WO = wo[i],
+                                            MFG_LOT = stationConfig.DataInfo.MFG_LOT,
+                                            MFG_ASSY_LINE = stationConfig.DataInfo.MFG_ASSY_LINE,
+                                            PROCESS_OUTCOME = "PASS",
+                                            PROCESS_MACHINE_ID = stationConfig.DataInfo.PROCESS_MACHINE_ID,
+                                            CTQ_UNIT_OF_MEASURE = "string",
+                                            ERROR_MESSAGE = ""
+                                        });
+                                        DFC.Add(new DataFormCtq
+                                        {
+                                            PPID = ProductMainSN[i],
+                                            PROCESS_NAME = stationConfig.DataInfo.PROCESS_NAME,
+                                            PROCESS_START_TIME = _LastMesCheckTime[i].ToString(),
+                                            CTQ_NAME = "Assy_Pressure",
+                                            CTQ_VALUE = assypress,
+                                            CTQ_LSL = p1.PressureDownLimit.ToString("F3"),
+                                            CTQ_USL = p1.PressureUpLimit.ToString("F3"),
+                                            PROCESS_END_TIME = serverTimeResult.Now.ToString(),
+                                            SUPPLIER_NAME = stationConfig.DataInfo.SUPPLIER_NAME,
+                                            COMMODITY_TYPE = stationConfig.DataInfo.COMMODITY_TYPE,
+                                            REVISION = stationConfig.DataInfo.REVISION,
+                                            WO = wo[i],
+                                            MFG_LOT = stationConfig.DataInfo.MFG_LOT,
+                                            MFG_ASSY_LINE = stationConfig.DataInfo.MFG_ASSY_LINE,
+                                            PROCESS_OUTCOME = assyPresRes ? "PASS" : "FAIL",
+                                            PROCESS_MACHINE_ID = stationConfig.DataInfo.PROCESS_MACHINE_ID,
+                                            CTQ_UNIT_OF_MEASURE = "kg",
+                                            ERROR_MESSAGE = assyPresRes ? "" : "Assy_Pressure OOS"
+                                        });
+                                        #endregion
                                     }
                                     }
                                     else if (i == 1)
                                     else if (i == 1)
                                     {
                                     {
-                                        press = currentPressure[1].ToString();
+                                        try
+                                        {
+                                            press = currentPressure[1].ToString("F2");
+                                            if (currentPressure[1] >= p2.PressureDownLimit && currentPressure[1] <= p2.PressureUpLimit)
+                                            {
+                                                resultIndex = 1;
+                                            }
+                                            else
+                                            {
+                                                resultIndex = 2;
+                                            }
+                                        }
+                                        catch (Exception ex)
+                                        {
+                                            press = "0";
+                                            resultIndex = 2;
+                                        }
                                         presstime = p2.PressureTime.ToString();
                                         presstime = p2.PressureTime.ToString();
+                                        data.Add("pressure", press);
+                                        data.Add("pressure_time", presstime);
+                                        SendTaskMessage($"保压压力:{press},保压时间:{presstime}", MessageLevel.Info);
+                                        #region 数据
+                                        bool presRes;
+                                        if (currentPressure[1] >= p2.PressureDownLimit && currentPressure[1] <= p2.PressureUpLimit)
+                                        {
+                                            presRes = true;
+                                        }
+                                        else presRes = false;
+                                        DFC.Clear();
+                                        DFC.Add(new DataFormCtq
+                                        {
+                                            PPID = ProductMainSN[i],
+                                            PROCESS_NAME = stationConfig.DataInfo.PROCESS_NAME,
+                                            PROCESS_START_TIME = _LastMesCheckTime[i].ToString(),
+                                            CTQ_NAME = "Pressure",
+                                            CTQ_VALUE = press,
+                                            CTQ_LSL = p2.PressureDownLimit.ToString("F3"),
+                                            CTQ_USL = p2.PressureUpLimit.ToString("F3"),
+                                            PROCESS_END_TIME = serverTimeResult.Now.ToString(),
+                                            SUPPLIER_NAME = stationConfig.DataInfo.SUPPLIER_NAME,
+                                            COMMODITY_TYPE = stationConfig.DataInfo.COMMODITY_TYPE,
+                                            REVISION = stationConfig.DataInfo.REVISION,
+                                            WO = wo[i],
+                                            MFG_LOT = stationConfig.DataInfo.MFG_LOT,
+                                            MFG_ASSY_LINE = stationConfig.DataInfo.MFG_ASSY_LINE,
+                                            PROCESS_OUTCOME = presRes ? "PASS" : "FAIL",
+                                            PROCESS_MACHINE_ID = stationConfig.DataInfo.PROCESS_MACHINE_ID,
+                                            CTQ_UNIT_OF_MEASURE = "kg",
+                                            ERROR_MESSAGE = presRes ? "" : "Assy_Pressure OOS"
+                                        });
+                                        DFC.Add(new DataFormCtq
+                                        {
+                                            PPID = ProductMainSN[i],
+                                            PROCESS_NAME = stationConfig.DataInfo.PROCESS_NAME,
+                                            PROCESS_START_TIME = _LastMesCheckTime[i].ToString(),
+                                            CTQ_NAME = "Pressure_time",
+                                            CTQ_VALUE = Math.Round(double.Parse(presstime), 3).ToString(),
+                                            CTQ_LSL = p2.PressureTime.ToString("F3"),
+                                            CTQ_USL = p2.PressureTime.ToString("F3"),
+                                            PROCESS_END_TIME = serverTimeResult.Now.ToString(),
+                                            SUPPLIER_NAME = stationConfig.DataInfo.SUPPLIER_NAME,
+                                            COMMODITY_TYPE = stationConfig.DataInfo.COMMODITY_TYPE,
+                                            REVISION = stationConfig.DataInfo.REVISION,
+                                            WO = stationConfig.DataInfo.WO,
+                                            MFG_LOT = stationConfig.DataInfo.MFG_LOT,
+                                            MFG_ASSY_LINE = stationConfig.DataInfo.MFG_ASSY_LINE,
+                                            PROCESS_OUTCOME = "PASS",
+                                            PROCESS_MACHINE_ID = stationConfig.DataInfo.PROCESS_MACHINE_ID,
+                                            CTQ_UNIT_OF_MEASURE = "s",
+                                            ERROR_MESSAGE = ""
+                                        });
+                                        #endregion
                                     }
                                     }
                                     //gap-复检gap参数, press-保压站实际压力值, presstime-保压站保压时间, assypress-组装站实际压力值
                                     //gap-复检gap参数, press-保压站实际压力值, presstime-保压站保压时间, assypress-组装站实际压力值
-                                    (bool isSuccess, string response) = await _mesService.SubmitGetAsync(i,code, comp, gap, press, presstime, assypress, resultIndex == 1 ? true : false, _LastMesCheckTime[i], DateTime.UtcNow);
+                                    (bool isSuccess, string response) = await _mesService.SubmitGetAsync(i, code, comp, resultIndex == 1 ? true : false, data, _LastMesCheckTime[i], serverTimeResult.Now);
                                     if (isSuccess)
                                     if (isSuccess)
                                     {
                                     {
                                         LogHelper.WriteLogMes($"上传mes成功");
                                         LogHelper.WriteLogMes($"上传mes成功");
@@ -2394,8 +2800,35 @@ namespace TeamAAS_VP.Core
                                         SendTaskMessage($"上传mes失败", MessageLevel.Error);
                                         SendTaskMessage($"上传mes失败", MessageLevel.Error);
                                     }
                                     }
                                     await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)3);
                                     await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)3);
+
+                                    //是否保存当前的产品记录至CSV?
+                                    if (stationConfig.SaveCsv)
+                                    {
+                                        //判断锁付路径字符串是否为空,如果不为空则保存,否则不保存
+                                        if (!string.IsNullOrEmpty(stationConfig.SaveCsvPath))
+                                        {
+                                            bool recordResult = RecordStationResult(i, DFC, ProductMainSN[i], serverTimeResult.Now.Subtract(_LastMesCheckTime[i]).TotalSeconds, _LastMesCheckTime[i], stationConfig.SaveCsvPath);
+                                            if (recordResult)
+                                            {
+                                                SendTaskMessage($"{i}:{stationConfig.DeviceName}产品记录保存成功", MessageLevel.Debug);
+                                            }
+                                            else
+                                            {
+                                                SendTaskMessage($"{i}:{stationConfig.DeviceName}产品记录保存失败", MessageLevel.Error);
+                                            }
+                                        }
+                                        else
+                                        {
+                                            SendTaskMessage($"{i}:{stationConfig.DeviceName}工位未配置保存路径,无法保存产品记录", MessageLevel.Error);
+                                        }
+                                    }
+                                    else
+                                    {
+                                        SendTaskMessage($"{i}:{stationConfig.DeviceName}工位未配置保存产品记录", MessageLevel.Debug);
+                                    }
                                     LogHelper.WriteLogMes($"【mes结束ADD】");
                                     LogHelper.WriteLogMes($"【mes结束ADD】");
                                     SendTaskMessage($"mes结束ADD", MessageLevel.Info);
                                     SendTaskMessage($"mes结束ADD", MessageLevel.Info);
+
                                     return;
                                     return;
                                 }
                                 }
                                 else
                                 else
@@ -2430,14 +2863,11 @@ namespace TeamAAS_VP.Core
                                     SendTaskMessage($"收到开始保压信号[{i}]...", MessageLevel.Debug);
                                     SendTaskMessage($"收到开始保压信号[{i}]...", MessageLevel.Debug);
                                     // 开始采集压力值
                                     // 开始采集压力值
                                     StartPressureCollection(currentProduct.Name, code, i);
                                     StartPressureCollection(currentProduct.Name, code, i);
+                                    StartCtqTime[i] = DateTime.Now;
                                 }
                                 }
                                 else
                                 else
                                 {
                                 {
-                                    SendTaskMessage($"开始保压信号[{i}]已关闭", MessageLevel.Alarm);
-                                    //// 关闭时的处理(如需)可放在这里
-                                    //SendTaskMessage($"收到关闭保压信号[{i}]...", MessageLevel.Debug);
-                                    //// 停止采集压力并保存
-                                    //await StopAndSavePressureCollectionAsync(currentProduct.Name, code, i);
+                                    SendTaskMessage($"关闭开始保压信号[{i}]...", MessageLevel.Debug);
                                 }
                                 }
                             }
                             }
                         }
                         }
@@ -2778,6 +3208,87 @@ namespace TeamAAS_VP.Core
         }
         }
         #endregion
         #endregion
 
 
+        /// <summary>
+        /// 记录工位的结果,其他工位要存储的数据项按照键值对集合的形式传入,键为数据项名称,值为数据项的值
+        /// </summary>
+        /// <param name="stationIndex"></param>
+        /// <param name="dfcs"></param>
+        /// <param name="productMainSN"></param>
+        /// <param name="ct"></param>
+        /// <param name="timestamp"></param>
+        /// <param name="savePath"></param>
+        /// <param name="isFirstEnter"></param>
+        /// <returns></returns>
+        private bool RecordStationResult(int stationIndex, IEnumerable<DataFormCtq> dfcs, string productMainSN, double ct, DateTime timestamp, string savePath, bool isFirstEnter = true)
+        {
+            try
+            {
+                //获取当前工位的配置
+                var stationConfig = _configService.GetDeviceInfo(stationIndex);
+                if (stationConfig == null) return false;
+                //如果保存路径为空,则不保存
+                if (string.IsNullOrEmpty(savePath)) return false;
+                string fullPath = savePath;
+                //如果保存路径是一个文件路径,则直接保存,否则按照工位和日期进行保存
+                if (File.Exists(savePath) || Path.HasExtension(savePath))
+                {
+                    fullPath = savePath;
+                    //如果路径不存在,则创建
+                    // 创建目录
+                    string directory = Path.GetDirectoryName(fullPath);
+                    if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
+                    {
+                        Directory.CreateDirectory(directory);
+                    }
+                }
+                else
+                {
+                    //结果保存至CSV文件,文件名格式:savePath\yyyy-MM\工位编号_工位名称_yyyy-MM-dd.csv
+                    string datePath = timestamp.ToString("yyyy-MM") + "\\";
+                    string dirPath = Path.Combine(savePath, datePath);
+                    if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
+                    string fileName = $"{stationIndex}_{stationConfig.DeviceName}_{timestamp.ToString("yyyy-MM-dd")}.csv";
+                    fullPath = Path.Combine(dirPath, fileName);
+                }
+                StringBuilder sb = new StringBuilder();
+                if (!File.Exists(fullPath))
+                {
+                    sb.Append("PPID,PROCESS_NAME,PROCESS_START_TIME,CTQ_NAME,CTQ_VALUE,CTQ_LSL,CTQ_USL,PROCESS_END_TIME,SUPPLIER_NAME,COMMODITY_TYPE,REVISION,WO#,MFG_LOT#," +
+                        "MFG_ASSY_LINE,PROCESS_OUTCOME,PROCESS_MACHINE_ID,CTQ_UNIT_OF_MEASURE,ERROR_MESSAGE");
+                    sb.AppendLine();
+                }
+                if (dfcs == null || dfcs.Count() == 0)
+                {
+                    return false;
+                }
+                foreach (var dfc in dfcs)
+                {
+                    sb.Append($"{dfc.PPID},{dfc.PROCESS_NAME},{dfc.PROCESS_START_TIME},{dfc.CTQ_NAME},{dfc.CTQ_VALUE},{dfc.CTQ_LSL},{dfc.CTQ_USL},{dfc.PROCESS_END_TIME},{dfc.SUPPLIER_NAME},{dfc.COMMODITY_TYPE},{dfc.REVISION},{dfc.WO},{dfc.MFG_LOT},{dfc.MFG_ASSY_LINE},{dfc.PROCESS_OUTCOME},{dfc.PROCESS_MACHINE_ID},{dfc.CTQ_UNIT_OF_MEASURE},{dfc.ERROR_MESSAGE}");
+                    sb.AppendLine();
+                }
+                // 使用 StreamWriter 以追加模式打开文件
+                StreamWriter sw = new StreamWriter(fullPath, true, Encoding.UTF8);
+                sw.Write(sb.ToString());
+                sw.Close();
+                sw.Dispose();
+                return true;
+            }
+            catch (Exception ex)
+            {
+                if (!isFirstEnter)
+                {
+                    return false;
+                }
+                LogHelper.WriteLogError("记录其他工位结果时出错!", ex);
+                //我希望在这里生成一个临时文件来保存这次的记录,因为如果本地文件被打开时可能会导致无法写入,如果不保存的话可能会丢失这次的记录,所以我想在这里生成一个临时文件来保存这次的记录
+                //生成临时文件的路径,格式为savePath\yyyy-MM\工位编号_yyyy-MM-dd_temp\工位编号_yyyy-MM-dd_HH-mm-ss-fff_temp.csv
+                string datePath = timestamp.ToString("yyyy-MM") + "\\";
+                string tempDirPath = Path.Combine(savePath, datePath, $"{stationIndex}_{timestamp.ToString("yyyy-MM-dd")}_temp");
+                string tempFileName = $"{stationIndex}_{timestamp.ToString("yyyy-MM-dd_HH-mm-ss-fff")}_temp.csv";
+                RecordStationResult(stationIndex, dfcs, productMainSN, ct, timestamp, tempFileName, false);
+                return false;
+            }
+        }
         #endregion
         #endregion
     }
     }
 }
 }

+ 103 - 10
TeamAAS-VM/Core/RectangleCenterCalculator.cs

@@ -97,13 +97,7 @@ namespace TeamAAS_VP.Core
             if (corners == null || corners.Count != 4)
             if (corners == null || corners.Count != 4)
                 throw new ArgumentException("需要4个角点");
                 throw new ArgumentException("需要4个角点");
 
 
-            // 这里可以添加自动排序逻辑,但既然您已知顺序,直接返回
-            // 如果未来需要自动排序,可以使用以下逻辑:
-            // 1. 找到最左边的两个点作为左边界
-            // 2. 根据Y坐标区分左上和左下
-            // 3. 计算中心点,确定其他点位置
-
-            return corners; // 假设输入已经按正确顺序
+            return SortCornersByTopBottomHeuristic(corners);
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -204,7 +198,20 @@ namespace TeamAAS_VP.Core
         /// </summary>
         /// </summary>
         public static RectangleResult CalculateByPCAWithKnownOrder(List<Vector<double>> corners)
         public static RectangleResult CalculateByPCAWithKnownOrder(List<Vector<double>> corners)
         {
         {
+            //打印输入点以调试
+            //Console.WriteLine($"输入点 [1] : {corners[0][0]:F3},{corners[0][1]:F3}");
+            //Console.WriteLine($"输入点 [2] : {corners[1][0]:F3},{corners[1][1]:F3}");
+            //Console.WriteLine($"输入点 [3] : {corners[2][0]:F3},{corners[2][1]:F3}");
+            //Console.WriteLine($"输入点 [4] : {corners[3][0]:F3},{corners[3][1]:F3}");
+
             var orderedCorners = ValidateAndOrderCorners(corners);
             var orderedCorners = ValidateAndOrderCorners(corners);
+            Console.WriteLine($"");
+
+            //打印输入点以调试
+            //Console.WriteLine($"输出点 [1] : {orderedCorners[0][0]:F3},{orderedCorners[0][1]:F3}");
+            //Console.WriteLine($"输出点 [2] : {orderedCorners[1][0]:F3},{orderedCorners[1][1]:F3}");
+            //Console.WriteLine($"输出点 [3] : {orderedCorners[2][0]:F3},{orderedCorners[2][1]:F3}");
+            //Console.WriteLine($"输出点 [4] : {orderedCorners[3][0]:F3},{orderedCorners[3][1]:F3}");
 
 
             int dim = orderedCorners[0].Count;
             int dim = orderedCorners[0].Count;
             // 步骤1:使用所有点进行PCA得到初步估计
             // 步骤1:使用所有点进行PCA得到初步估计
@@ -343,7 +350,7 @@ namespace TeamAAS_VP.Core
             int n = axis.Count;
             int n = axis.Count;
             if (n == 0) throw new ArgumentException("axis must have positive dimension", nameof(axis));
             if (n == 0) throw new ArgumentException("axis must have positive dimension", nameof(axis));
 
 
-            // 专门处理2D:(-y, x) 是垂直向量
+            // 2D场景:(-y, x) 为垂直向量
             if (n == 2)
             if (n == 2)
             {
             {
                 var perp2 = Vector<double>.Build.DenseOfArray(new[] { -axis[1], axis[0] });
                 var perp2 = Vector<double>.Build.DenseOfArray(new[] { -axis[1], axis[0] });
@@ -351,7 +358,7 @@ namespace TeamAAS_VP.Core
                 return perp2.Normalize(2);
                 return perp2.Normalize(2);
             }
             }
 
 
-            // 一般n维:选一个与axis不共线的标准基向量
+            // 通用n维:选一个不与axis共线的标准基向量
             int idx = 0;
             int idx = 0;
             for (int i = 0; i < n; i++)
             for (int i = 0; i < n; i++)
             {
             {
@@ -367,7 +374,7 @@ namespace TeamAAS_VP.Core
         /// <summary>
         /// <summary>
         /// 辅助方法:计算两点距离
         /// 辅助方法:计算两点距离
         /// </summary>
         /// </summary>
-        private static double Distance(Vector<double> a, Vector<double> b)
+        public static double Distance(Vector<double> a, Vector<double> b)
         {
         {
             return (a - b).L2Norm();
             return (a - b).L2Norm();
         }
         }
@@ -426,5 +433,91 @@ namespace TeamAAS_VP.Core
 
 
             return Math.Sqrt(sumSquared / 4);
             return Math.Sqrt(sumSquared / 4);
         }
         }
+
+        /// <summary>
+        /// 自动排序角点:左上 → 右上 → 右下 → 左下
+        /// </summary>
+        /// <param name="unorderedCorners">任意顺序的四个角点</param>
+        /// <returns>按标准顺序排序的角点列表</returns>
+        public static List<Vector<double>> SortCornersToRectangleOrder(List<Vector<double>> unorderedCorners)
+        {
+            if (unorderedCorners == null || unorderedCorners.Count != 4)
+                throw new ArgumentException("需要4个角点");
+
+            // 方法1:基于上下分组+水平排序的稳健方法
+            return SortCornersByTopBottomHeuristic(unorderedCorners);
+        }
+
+        /// <summary>
+        /// 方法1:基于上下分组与水平排序的稳健方法
+        /// </summary>
+        private static List<Vector<double>> SortCornersByTopBottomHeuristic(List<Vector<double>> corners)
+        {
+            if (corners == null || corners.Count != 4)
+                throw new ArgumentException("需要4个角点");
+
+            var orderHighY = BuildOrderByTopBottom(corners, topIsHigher: true);
+            var orderLowY = BuildOrderByTopBottom(corners, topIsHigher: false);
+
+            double scoreHigh = RectangleOrderScore(orderHighY);
+            double scoreLow = RectangleOrderScore(orderLowY);
+
+            return scoreHigh <= scoreLow ? orderHighY : orderLowY;
+        }
+
+        private static List<Vector<double>> BuildOrderByTopBottom(List<Vector<double>> corners, bool topIsHigher)
+        {
+            var sortedByY = topIsHigher
+                ? corners.OrderByDescending(p => p[1]).ToList()
+                : corners.OrderBy(p => p[1]).ToList();
+
+            var topCandidates = sortedByY.Take(2).ToList();
+            var bottomCandidates = sortedByY.Skip(2).Take(2).ToList();
+
+            var top = topCandidates.OrderBy(p => p[0]).ToList();
+            var bottom = bottomCandidates.OrderBy(p => p[0]).ToList();
+
+            var topLeft = top[0];
+            var topRight = top[1];
+            var bottomLeft = bottom[0];
+            var bottomRight = bottom[1];
+
+            return new List<Vector<double>> { topLeft, topRight, bottomRight, bottomLeft };
+        }
+
+        private static double RectangleOrderScore(List<Vector<double>> ordered)
+        {
+            if (ordered == null || ordered.Count != 4)
+                return double.MaxValue;
+
+            var topLeft = ordered[0];
+            var topRight = ordered[1];
+            var bottomRight = ordered[2];
+            var bottomLeft = ordered[3];
+
+            double top = Distance(topLeft, topRight);
+            double bottom = Distance(bottomLeft, bottomRight);
+            double left = Distance(topLeft, bottomLeft);
+            double right = Distance(topRight, bottomRight);
+            double diag1 = Distance(topLeft, bottomRight);
+            double diag2 = Distance(topRight, bottomLeft);
+
+            double parallelScore = Math.Abs(top - bottom) + Math.Abs(left - right) + Math.Abs(diag1 - diag2);
+
+            double xOrderPenalty = 0.0;
+            if (topLeft[0] > topRight[0]) xOrderPenalty += 1000.0;
+            if (bottomLeft[0] > bottomRight[0]) xOrderPenalty += 1000.0;
+
+            return parallelScore + xOrderPenalty;
+        }
+
+        /// <summary>
+        /// 调整角点顺序为标准矩形顺序(左上→右上→右下→左下)
+        /// </summary>
+        private static List<Vector<double>> AdjustToRectangleOrder(List<Vector<double>> corners)
+        {
+            return SortCornersByTopBottomHeuristic(corners);
+        }
+
     }
     }
 }
 }

+ 34 - 3
TeamAAS-VM/Interfaces/IConfigService.cs

@@ -480,17 +480,48 @@ namespace TeamAAS_VP.Interfaces
         /// </summary>
         /// </summary>
         Task RecordScrewFeederBatchAsync(ScrewFeederBatchRecord record);
         Task RecordScrewFeederBatchAsync(ScrewFeederBatchRecord record);
 
 
-        // Device info
+        // Device info - 支持多设备
         /// <summary>
         /// <summary>
-        /// 获取或创建设备信息配置
+        /// 获取所有设备信息配置列表
+        /// </summary>
+        /// <returns>设备信息列表的只读集合</returns>
+        IReadOnlyCollection<DeviceInfo> GetAllDeviceInfos();
+
+        /// <summary>
+        /// 根据设备编号获取设备信息(兼容旧API,返回第一个设备)
         /// </summary>
         /// </summary>
         DeviceInfo GetDeviceInfo();
         DeviceInfo GetDeviceInfo();
 
 
         /// <summary>
         /// <summary>
-        /// 保存设备信息配置
+        /// 根据设备编号获取设备信息
+        /// </summary>
+        /// <param name="deviceNo">设备编号</param>
+        DeviceInfo GetDeviceInfo(int deviceNo);
+
+        /// <summary>
+        /// 保存设备信息配置(添加或更新)
         /// </summary>
         /// </summary>
         void SaveDeviceInfo(DeviceInfo deviceInfo);
         void SaveDeviceInfo(DeviceInfo deviceInfo);
 
 
+        /// <summary>
+        /// 保存所有设备信息列表
+        /// </summary>
+        /// <param name="deviceInfoList">设备信息列表</param>
+        void SaveAllDeviceInfos(IEnumerable<DeviceInfo> deviceInfoList);
+
+        /// <summary>
+        /// 添加新设备
+        /// </summary>
+        /// <returns>新添加的设备</returns>
+        DeviceInfo AddDeviceInfo();
+
+        /// <summary>
+        /// 删除设备
+        /// </summary>
+        /// <param name="deviceNo">设备编号</param>
+        /// <returns>是否删除成功</returns>
+        bool RemoveDeviceInfo(int deviceNo);
+
         //刷卡登录
         //刷卡登录
         /// <summary>
         /// <summary>
         /// 获取刷卡器配置
         /// 获取刷卡器配置

+ 21 - 4
TeamAAS-VM/Interfaces/IMesService.cs

@@ -27,7 +27,7 @@ namespace TeamAAS_VP.Interfaces
         /// - 实现应尊重 <paramref name="cancellationToken"/>,在取消时尽早抛出 <see cref="OperationCanceledException"/> 或返回失败结果。
         /// - 实现应尊重 <paramref name="cancellationToken"/>,在取消时尽早抛出 <see cref="OperationCanceledException"/> 或返回失败结果。
         /// - 若 <paramref name="sn"/> 无效,应抛出 <see cref="ArgumentNullException"/> 或 <see cref="ArgumentException"/>。
         /// - 若 <paramref name="sn"/> 无效,应抛出 <see cref="ArgumentNullException"/> 或 <see cref="ArgumentException"/>。
         /// </remarks>
         /// </remarks>
-        Task<(bool IsSuccess, string Response)> StationGetAsync(int num, string sn, string comp, CancellationToken cancellationToken = default);
+        Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, CancellationToken cancellationToken = default);
 
 
         /// <summary>
         /// <summary>
         /// 使用配置的过站(Station)URL 发起 GET 请求,携带序列号(sn)作为查询参数进行过站,并使用指定的超时时间(秒)。
         /// 使用配置的过站(Station)URL 发起 GET 请求,携带序列号(sn)作为查询参数进行过站,并使用指定的超时时间(秒)。
@@ -43,7 +43,16 @@ namespace TeamAAS_VP.Interfaces
         /// - 此重载方便在不使用 <see cref="CancellationToken"/> 的场景中指定超时时间。
         /// - 此重载方便在不使用 <see cref="CancellationToken"/> 的场景中指定超时时间。
         /// - 实现应验证 <paramref name="timeoutInSeconds"/> 为合理值(例如 > 0),否则可抛出 <see cref="ArgumentOutOfRangeException"/>。
         /// - 实现应验证 <paramref name="timeoutInSeconds"/> 为合理值(例如 > 0),否则可抛出 <see cref="ArgumentOutOfRangeException"/>。
         /// </remarks>
         /// </remarks>
-        Task<(bool IsSuccess, string Response)> StationGetAsync(int num, string sn, string comp, double timeoutInSeconds);
+        Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, double timeoutInSeconds);
+
+        /// <summary>
+        /// 过站请求的扩展版本,允许同时指定 <see cref="CancellationToken"/> 和超时时间(秒)。实现应优先考虑取消请求,但在未取消的情况下应用超时。
+        /// </summary>
+        /// <param name="sn"></param>
+        /// <param name="comp"></param>
+        /// <param name="timeoutInSeconds"></param>
+        /// <returns></returns>
+        Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, double timeoutInSeconds);
 
 
         /// <summary>
         /// <summary>
         /// 使用配置的提交(Submit)URL 发起 GET 请求,提交过站结果及时间信息。
         /// 使用配置的提交(Submit)URL 发起 GET 请求,提交过站结果及时间信息。
@@ -63,7 +72,7 @@ namespace TeamAAS_VP.Interfaces
         /// - 若 <paramref name="start_time"/> 晚于 <paramref name="stop_time"/>,实现应记录并视情况返回失败或抛出异常。
         /// - 若 <paramref name="start_time"/> 晚于 <paramref name="stop_time"/>,实现应记录并视情况返回失败或抛出异常。
         /// - 实现应尊重 <paramref name="cancellationToken"/>,并在取消时尽早中止请求。
         /// - 实现应尊重 <paramref name="cancellationToken"/>,并在取消时尽早中止请求。
         /// </remarks>
         /// </remarks>
-        Task<(bool IsSuccess, string Response)> SubmitGetAsync(int num, string sn, string comp, string gap, string press, string presstime, string assypress, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default);
+        Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo, string sn, string comp, bool isSuccess, Dictionary<string, string> data, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default);
 
 
         /// <summary>
         /// <summary>
         /// 使用配置的提交(Submit)URL 发起 GET 请求,提交过站结果及时间信息,并使用指定的超时时间(秒)。
         /// 使用配置的提交(Submit)URL 发起 GET 请求,提交过站结果及时间信息,并使用指定的超时时间(秒)。
@@ -82,6 +91,14 @@ namespace TeamAAS_VP.Interfaces
         /// - 此重载用于在不传入 <see cref="CancellationToken"/> 的场景中指定超时时间。
         /// - 此重载用于在不传入 <see cref="CancellationToken"/> 的场景中指定超时时间。
         /// - 实现应确保对时间参数与布尔参数进行适当的 URL 编码或格式化。
         /// - 实现应确保对时间参数与布尔参数进行适当的 URL 编码或格式化。
         /// </remarks>
         /// </remarks>
-        Task<(bool IsSuccess, string Response)> SubmitGetAsync(int num, string sn, string comp, string gap, string press, string presstime, string assypress, bool isSuccess, DateTime start_time, DateTime stop_time, double timeoutInSeconds);
+        Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo, string sn, string comp, bool isSuccess, Dictionary<string, string> data, DateTime start_time, DateTime stop_time, double timeoutInSeconds);
+
+        /// <summary>
+        /// 获取服务器当前时间
+        /// </summary>
+        /// <param name="sn"></param>
+        /// <param name="timeoutInSeconds"></param>
+        /// <returns></returns>
+        Task<(bool IsSuccess, DateTime Now)> GetServerTimeAsync(int deviceNo, string sn, double timeoutInSeconds);
     }
     }
 }
 }

+ 2 - 2
TeamAAS-VM/Interfaces/IRemoteCommandService.cs

@@ -239,7 +239,7 @@ namespace TeamAAS_VP.Interfaces
         /// <param name="InputTerminal"></param>
         /// <param name="InputTerminal"></param>
         /// <param name="outputCollection"></param>
         /// <param name="outputCollection"></param>
         /// <returns></returns>
         /// <returns></returns>
-        bool ExecutePhoto(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection);
+        bool ExecutePhoto(int index, ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection);
 
 
         /// <summary>
         /// <summary>
         /// 执行拍照二维码流程运行
         /// 执行拍照二维码流程运行
@@ -247,7 +247,7 @@ namespace TeamAAS_VP.Interfaces
         /// <param name="procedure"></param>
         /// <param name="procedure"></param>
         /// <param name="outputCollection"></param>
         /// <param name="outputCollection"></param>
         /// <returns></returns>
         /// <returns></returns>
-        bool ExecutePhoto(ProcedureModel procedure, out CogToolBlockTerminalCollection outputCollection);
+        bool ExecutePhoto(int index, ProcedureModel procedure, out CogToolBlockTerminalCollection outputCollection);
 
 
 
 
         /// <summary>
         /// <summary>

+ 180 - 0
TeamAAS-VM/Models/CTQ_Data.cs

@@ -0,0 +1,180 @@
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Models
+{
+    public class CTQ_Data : BindableBase
+    {
+        private string _PPID;
+        /// <summary>
+        /// sn
+        /// </summary>
+        public string PPID { get => _PPID; set => SetProperty(ref _PPID, value); }
+
+        private string _PROCESS_NAME;
+        /// <summary>
+        /// 设备名称
+        /// </summary>
+        public string PROCESS_NAME { get => _PROCESS_NAME; set => SetProperty(ref _PROCESS_NAME, value); }
+
+        private string _PROCESS_START_TIME;
+        /// <summary>
+        /// 开始时间
+        /// </summary>
+        public string PROCESS_START_TIME { get => _PROCESS_START_TIME; set => SetProperty(ref _PROCESS_START_TIME, value); }
+
+        private string _CTQ_NAME;
+        /// <summary>
+        /// 检测项名称
+        /// </summary>
+        public string CTQ_NAME { get => _CTQ_NAME; set => SetProperty(ref _CTQ_NAME, value); }
+
+        private double _CTQ_VALUE;
+        /// <summary>
+        /// 检测值
+        /// </summary>
+        public double CTQ_VALUE { get => _CTQ_VALUE; set => SetProperty(ref _CTQ_VALUE, value); }
+
+        //private double _CTQ_LSL_Torque;
+        ///// <summary>
+        ///// 下限(扭力)
+        ///// </summary>
+        //public double CTQ_LSL_Torque { get => _CTQ_LSL_Torque; set => SetProperty(ref _CTQ_LSL_Torque, value); }
+
+        //private double _CTQ_USL_Torque;
+        ///// <summary>
+        ///// 上限(扭力)
+        ///// </summary>
+        //public double CTQ_USL_Torque { get => _CTQ_USL_Torque; set => SetProperty(ref _CTQ_USL_Torque, value); }
+
+        //private double _CTQ_LSL_Turn;
+        ///// <summary>
+        ///// 下限(圈数)
+        ///// </summary>
+        //public double CTQ_LSL_Turn { get => _CTQ_LSL_Turn; set => SetProperty(ref _CTQ_LSL_Turn, value); }
+
+        //private double _CTQ_USL_Turn;
+        ///// <summary>
+        ///// 上限(圈数)
+        ///// </summary>
+        //public double CTQ_USL_Turn { get => _CTQ_USL_Turn; set => SetProperty(ref _CTQ_USL_Turn, value); }
+
+        //private double _CTQ_LSL_Pressure;
+        ///// <summary>
+        ///// 下限(压力)
+        ///// </summary>
+        //public double CTQ_LSL_Pressure { get => _CTQ_LSL_Pressure; set => SetProperty(ref _CTQ_LSL_Pressure, value); }
+
+        //private double _CTQ_USL_Pressure;
+        ///// <summary>
+        ///// 上限(压力)
+        ///// </summary>
+        //public double CTQ_USL_Pressure { get => _CTQ_USL_Pressure; set => SetProperty(ref _CTQ_USL_Pressure, value); }
+
+        private string _PROCESS_END_TIME;
+        /// <summary>
+        /// 结束时间
+        /// </summary>
+        public string PROCESS_END_TIME { get => _PROCESS_END_TIME; set => SetProperty(ref _PROCESS_END_TIME, value); }
+
+        private string _SUPPLIER_NAME;
+        public string SUPPLIER_NAME { get => _SUPPLIER_NAME; set => SetProperty(ref _SUPPLIER_NAME, value); }
+
+        private string _COMMODITY_TYPE;
+        public string COMMODITY_TYPE { get => _COMMODITY_TYPE; set => SetProperty(ref _COMMODITY_TYPE, value); }
+
+        private string _REVISION;
+        public string REVISION { get => _REVISION; set => SetProperty(ref _REVISION, value); }
+
+        private string _WO;
+        /// <summary>
+        /// 工单号
+        /// </summary>
+        public string WO { get => _WO; set => SetProperty(ref _WO, value); }
+
+        private string _MFG_LOT;
+        public string MFG_LOT { get => _MFG_LOT; set => SetProperty(ref _MFG_LOT, value); }
+
+        private string _MFG_ASSY_LINE;
+        /// <summary>
+        /// 线体
+        /// </summary>
+        public string MFG_ASSY_LINE { get => _MFG_ASSY_LINE; set => SetProperty(ref _MFG_ASSY_LINE, value); }
+
+        private string _PROCESS_OUTCOME;
+        /// <summary>
+        /// 结果
+        /// </summary>
+        public string PROCESS_OUTCOME { get => _PROCESS_OUTCOME; set => SetProperty(ref _PROCESS_OUTCOME, value); }
+
+        private string _PROCESS_MACHINE_ID;
+        /// <summary>
+        /// 设备ID
+        /// </summary>
+        public string PROCESS_MACHINE_ID { get => _PROCESS_MACHINE_ID; set => SetProperty(ref _PROCESS_MACHINE_ID, value); }
+
+        private string _CTQ_UNIT_OF_MEASURE;
+        /// <summary>
+        /// 单位
+        /// </summary>
+        public string CTQ_UNIT_OF_MEASURE { get => _CTQ_UNIT_OF_MEASURE; set => SetProperty(ref _CTQ_UNIT_OF_MEASURE, value); }
+
+        private string _ERROR_MESSAGE;
+        /// <summary>
+        /// 报错信息
+        /// </summary>
+        public string ERROR_MESSAGE { get => _ERROR_MESSAGE; set => SetProperty(ref _ERROR_MESSAGE, value); }
+
+        public CTQ_Data()
+        {
+            PPID = string.Empty;
+            PROCESS_NAME = string.Empty;
+            PROCESS_START_TIME = string.Empty;
+            CTQ_NAME = string.Empty;
+            CTQ_VALUE = 0.0;
+            //CTQ_LSL_Pressure = 0.0;
+            //CTQ_USL_Pressure = 0.0;
+            PROCESS_END_TIME = string.Empty;
+            SUPPLIER_NAME = string.Empty;
+            COMMODITY_TYPE = string.Empty;
+            REVISION = string.Empty;
+            WO = string.Empty;
+            MFG_LOT = string.Empty;
+            MFG_ASSY_LINE = string.Empty;
+            PROCESS_OUTCOME = string.Empty;
+            PROCESS_MACHINE_ID = string.Empty;
+            CTQ_UNIT_OF_MEASURE = string.Empty;
+            ERROR_MESSAGE = string.Empty;
+        }
+
+        public CTQ_Data Copy()
+        {
+            return new CTQ_Data
+            {
+                PPID = this.PPID,
+                PROCESS_NAME = this.PROCESS_NAME,
+                PROCESS_START_TIME = this.PROCESS_START_TIME,
+                CTQ_NAME = this.CTQ_NAME,
+                CTQ_VALUE = this.CTQ_VALUE,
+                //CTQ_LSL_Pressure = this.CTQ_LSL_Pressure,
+                //CTQ_USL_Pressure = this.CTQ_USL_Pressure,
+                PROCESS_END_TIME = this.PROCESS_END_TIME,
+                SUPPLIER_NAME = this.SUPPLIER_NAME,
+                COMMODITY_TYPE = this.COMMODITY_TYPE,
+                REVISION = this.REVISION,
+                WO = this.WO,
+                MFG_LOT = this.MFG_LOT,
+                MFG_ASSY_LINE = this.MFG_ASSY_LINE,
+                PROCESS_OUTCOME = this.PROCESS_OUTCOME,
+                PROCESS_MACHINE_ID = this.PROCESS_MACHINE_ID,
+                CTQ_UNIT_OF_MEASURE = this.CTQ_UNIT_OF_MEASURE,
+                ERROR_MESSAGE = this.ERROR_MESSAGE
+            };
+        }
+
+    }
+}

+ 109 - 0
TeamAAS-VM/Models/DataFormCtq.cs

@@ -0,0 +1,109 @@
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Models
+{
+    public class DataFormCtq : BindableBase
+    {
+        private string _PPID;
+        /// <summary>
+        /// sn
+        /// </summary>
+        public string PPID { get => _PPID; set => SetProperty(ref _PPID, value); }
+
+        private string _PROCESS_NAME;
+        /// <summary>
+        /// 设备名称
+        /// </summary>
+        public string PROCESS_NAME { get => _PROCESS_NAME; set => SetProperty(ref _PROCESS_NAME, value); }
+
+        private string _PROCESS_START_TIME;
+        /// <summary>
+        /// 开始时间
+        /// </summary>
+        public string PROCESS_START_TIME { get => _PROCESS_START_TIME; set => SetProperty(ref _PROCESS_START_TIME, value); }
+
+        private string _CTQ_NAME;
+        /// <summary>
+        /// 检测项名称
+        /// </summary>
+        public string CTQ_NAME { get => _CTQ_NAME; set => SetProperty(ref _CTQ_NAME, value); }
+
+        private string _CTQ_VALUE;
+        /// <summary>
+        /// 检测值
+        /// </summary>
+        public string CTQ_VALUE { get => _CTQ_VALUE; set => SetProperty(ref _CTQ_VALUE, value); }
+
+        private string _CTQ_LSL;
+        /// <summary>
+        /// 下限
+        /// </summary>
+        public string CTQ_LSL { get => _CTQ_LSL; set => SetProperty(ref _CTQ_LSL, value); }
+
+        private string _CTQ_USL;
+        /// <summary>
+        /// 上限
+        /// </summary>
+        public string CTQ_USL { get => _CTQ_USL; set => SetProperty(ref _CTQ_USL, value); }
+
+        private string _PROCESS_END_TIME;
+        /// <summary>
+        /// 结束时间
+        /// </summary>
+        public string PROCESS_END_TIME { get => _PROCESS_END_TIME; set => SetProperty(ref _PROCESS_END_TIME, value); }
+
+        private string _SUPPLIER_NAME;
+        public string SUPPLIER_NAME { get => _SUPPLIER_NAME; set => SetProperty(ref _SUPPLIER_NAME, value); }
+
+        private string _COMMODITY_TYPE;
+        public string COMMODITY_TYPE { get => _COMMODITY_TYPE; set => SetProperty(ref _COMMODITY_TYPE, value); }
+
+        private string _REVISION;
+        public string REVISION { get => _REVISION; set => SetProperty(ref _REVISION, value); }
+
+        private string _WO;
+        /// <summary>
+        /// 工单号
+        /// </summary>
+        public string WO { get => _WO; set => SetProperty(ref _WO, value); }
+
+        private string _MFG_LOT;
+        public string MFG_LOT { get => _MFG_LOT; set => SetProperty(ref _MFG_LOT, value); }
+
+        private string _MFG_ASSY_LINE;
+        /// <summary>
+        /// 线体
+        /// </summary>
+        public string MFG_ASSY_LINE { get => _MFG_ASSY_LINE; set => SetProperty(ref _MFG_ASSY_LINE, value); }
+
+        private string _PROCESS_OUTCOME;
+        /// <summary>
+        /// 结果
+        /// </summary>
+        public string PROCESS_OUTCOME { get => _PROCESS_OUTCOME; set => SetProperty(ref _PROCESS_OUTCOME, value); }
+
+        private string _PROCESS_MACHINE_ID;
+        /// <summary>
+        /// 设备ID
+        /// </summary>
+        public string PROCESS_MACHINE_ID { get => _PROCESS_MACHINE_ID; set => SetProperty(ref _PROCESS_MACHINE_ID, value); }
+
+        private string _CTQ_UNIT_OF_MEASURE;
+        /// <summary>
+        /// 单位
+        /// </summary>
+        public string CTQ_UNIT_OF_MEASURE { get => _CTQ_UNIT_OF_MEASURE; set => SetProperty(ref _CTQ_UNIT_OF_MEASURE, value); }
+
+        private string _ERROR_MESSAGE;
+        /// <summary>
+        /// 报错信息
+        /// </summary>
+        public string ERROR_MESSAGE { get => _ERROR_MESSAGE; set => SetProperty(ref _ERROR_MESSAGE, value); }
+
+    }
+}

+ 79 - 5
TeamAAS-VM/Models/DeviceInfo.cs

@@ -1,34 +1,53 @@
 using Prism.Mvvm;
 using Prism.Mvvm;
 using System;
 using System;
+using System.Windows;
 
 
 namespace TeamAAS_VP.Models
 namespace TeamAAS_VP.Models
 {
 {
     /// <summary>
     /// <summary>
-    /// 设备信息配置,用于保存线别/站别/机台号以及 MES 相关配置。
+    /// 璁惧�淇℃伅閰嶇疆锛岀敤浜庝繚瀛樼嚎鍒�/绔欑偣/鏈哄彴浠ュ強 MES 涓婁紶璁剧疆銆�
     /// </summary>
     /// </summary>
     public class DeviceInfo : BindableBase
     public class DeviceInfo : BindableBase
     {
     {
+        private int _deviceNo;
+        /// <summary>
+        /// 璁惧�缂栧彿锛屼粠0寮€濮�
+        /// </summary>
+        public int DeviceNo { get => _deviceNo; set => SetProperty(ref _deviceNo, value); }
+
+        private string _deviceName;
+        /// <summary>
+        /// 璁惧�鍚嶇О
+        /// </summary>
+        public string DeviceName { get => _deviceName; set => SetProperty(ref _deviceName, value); }
+
+        private string _deviceDesc;
+        /// <summary>
+        /// 璁惧�鎻忚堪
+        /// </summary>
+        public string DeviceDesc { get => _deviceDesc; set => SetProperty(ref _deviceDesc, value); }
+
         private string _line;
         private string _line;
         /// <summary>
         /// <summary>
-        /// 当前作业的线别
+        /// 褰撳墠浣滀笟鐨勭嚎鍒�
         /// </summary>
         /// </summary>
         public string Line { get => _line; set => SetProperty(ref _line, value); }
         public string Line { get => _line; set => SetProperty(ref _line, value); }
 
 
         private string _station;
         private string _station;
         /// <summary>
         /// <summary>
-        /// 当前作业的站别
+        /// 褰撳墠浣滀笟鐨勭珯鐐�
         /// </summary>
         /// </summary>
         public string Station { get => _station; set => SetProperty(ref _station, value); }
         public string Station { get => _station; set => SetProperty(ref _station, value); }
 
 
         private string _fixtureId;
         private string _fixtureId;
         /// <summary>
         /// <summary>
-        /// 当前作业的机台编号
+        /// 褰撳墠浣滀笟鐨勬満鍙扮紪鍙�
         /// </summary>
         /// </summary>
         public string FixtureId { get => _fixtureId; set => SetProperty(ref _fixtureId, value); }
         public string FixtureId { get => _fixtureId; set => SetProperty(ref _fixtureId, value); }
 
 
         private bool _enableMes;
         private bool _enableMes;
         /// <summary>
         /// <summary>
-        /// 是否启用 MES 通信功能
+        /// 鏄�惁鍚�敤 MES 閫氳�鍔熻兘
         /// </summary>
         /// </summary>
         public bool EnableMES { get => _enableMes; set => SetProperty(ref _enableMes, value); }
         public bool EnableMES { get => _enableMes; set => SetProperty(ref _enableMes, value); }
 
 
@@ -40,13 +59,47 @@ namespace TeamAAS_VP.Models
 
 
 
 
         private string _f;
         private string _f;
+        /// <summary>
+        /// 鍏ㄥ眬function鍙傛暟锛屼紶妯″潡锛岀粍瑁呯珯PQC妫€娴嬬粍瑁呯殑浼燩TL
+        /// f=PTL
+        /// </summary>
         public string F { get => _f; set => SetProperty(ref _f, value); }
         public string F { get => _f; set => SetProperty(ref _f, value); }
 
 
         private string _comp;
         private string _comp;
+        /// <summary>
+        /// 姝ゅ弬鏁板彧鏈夊寘瑁呯珯鏄�繀浼狅紝鍏朵粬缁勮�绔欎笉鐢ㄤ紶锛屾牸寮忔槸閮ㄤ欢鍚�:閮ㄤ欢缂栫爜锛屽�涓�椂鐢ㄨ嫳鏂囬€楀彿闅斿紑
+        /// comp=battery1:B00012345,battery2:B00022355
+        /// </summary>
         public string comp { get => _comp; set => SetProperty(ref _comp, value); }
         public string comp { get => _comp; set => SetProperty(ref _comp, value); }
 
 
+        private bool _saveCsv;
+        /// <summary>
+        /// 鏄�惁淇濆瓨CSV鏂囦欢锛岄粯璁や笉淇濆瓨
+        /// </summary>
+        public bool SaveCsv { get => _saveCsv; set => SetProperty(ref _saveCsv, value); }
+
+        private string _saveCsvPath;
+        /// <summary>
+        /// 淇濆瓨鐨凜SV鏂囦欢璺�緞
+        /// </summary>
+        public string SaveCsvPath { get => _saveCsvPath; set => SetProperty(ref _saveCsvPath, value); }
+
+        private bool _enableDoubleMes;
+        /// <summary>
+        /// 鏄�惁鍚�敤涓ゆ�浜у搧缂栧彿MES鑾峰彇锛岄粯璁や笉鍚�敤
+        /// </summary>
+        public bool EnableDoubleMes { get => _enableDoubleMes; set => SetProperty(ref _enableDoubleMes, value); }
+
+        private CTQ_Data _dataInfo = new CTQ_Data();
+        public CTQ_Data DataInfo
+        {
+            get { return _dataInfo; }
+            set { SetProperty(ref _dataInfo, value); }
+        }
+
         public DeviceInfo()
         public DeviceInfo()
         {
         {
+            DeviceNo = 0;
             Line = string.Empty;
             Line = string.Empty;
             Station = string.Empty;
             Station = string.Empty;
             FixtureId = string.Empty;
             FixtureId = string.Empty;
@@ -55,5 +108,26 @@ namespace TeamAAS_VP.Models
             MesUrl = string.Empty;
             MesUrl = string.Empty;
             EnableMES = false;
             EnableMES = false;
         }
         }
+
+        public DeviceInfo Copy()
+        {
+            return new DeviceInfo
+            {
+                DeviceNo = this.DeviceNo,
+                DeviceName = this.DeviceName,
+                DeviceDesc = this.DeviceDesc,
+                Line = this.Line,
+                Station = this.Station,
+                FixtureId = this.FixtureId,
+                F = this.F,
+                comp = this.comp,
+                MesUrl = this.MesUrl,
+                EnableMES = this.EnableMES,
+                SaveCsv = this.SaveCsv,
+                SaveCsvPath = this.SaveCsvPath,
+                EnableDoubleMes = this.EnableDoubleMes,
+                DataInfo = this.DataInfo.Copy()
+            };
+        }
     }
     }
 }
 }

+ 27 - 0
TeamAAS-VM/Models/PLC/PlcPoint.cs

@@ -361,6 +361,33 @@ namespace TeamAAS_VP.Models.PLC
             return await pLC.WriteNodesAsync(nodeValues);
             return await pLC.WriteNodesAsync(nodeValues);
         }
         }
 
 
+        /// <summary>
+        /// 将点位数据写入到PLC地址--移除OffsetX,OffsetY,OffsetU
+        /// </summary>
+        /// <param name="plcAddress"></param>
+        /// <param name="pLC"></param>
+        /// <returns></returns>
+        public async Task<bool> WriteToPlcAddressEx2(PlcPointAddress plcAddress, OpcUaClientPLC pLC)
+        {
+            Dictionary<string, object> nodeValues = new Dictionary<string, object>();
+            nodeValues.Add(string.Format(plcAddress.X_Position.Address, Number), X_Position);
+            nodeValues.Add(string.Format(plcAddress.X_Velocity.Address, Number), X_Velocity);
+            nodeValues.Add(string.Format(plcAddress.Y_Position.Address, Number), Y_Position);
+            nodeValues.Add(string.Format(plcAddress.Y_Velocity.Address, Number), Y_Velocity);
+            nodeValues.Add(string.Format(plcAddress.Z_Position_Start.Address, Number), Z_Position_Start + Z_Start_Offset);
+            nodeValues.Add(string.Format(plcAddress.Z_Velocity_Start.Address, Number), Z_Velocity_Start);
+            nodeValues.Add(string.Format(plcAddress.Z_Position_Stop.Address, Number), Z_Position_Stop + Z_Stop_Offset);
+            nodeValues.Add(string.Format(plcAddress.Z_Velocity_Stop.Address, Number), Z_Velocity_Stop);
+            nodeValues.Add(string.Format(plcAddress.U_Position.Address, Number), U_Position);
+            nodeValues.Add(string.Format(plcAddress.U_Velocity.Address, Number), U_Velocity);
+            nodeValues.Add(string.Format(plcAddress.R_Position.Address, Number), R_Position + R_Offset);
+            nodeValues.Add(string.Format(plcAddress.R_Velocity.Address, Number), R_Velocity);
+            nodeValues.Add(string.Format(plcAddress.Torque.Address, Number), Torque);
+            nodeValues.Add(string.Format(plcAddress.Feeder.Address, Number), Feeder);
+            nodeValues.Add(string.Format(plcAddress.ScrewProNum.Address, Number), ScrewProNum);
+            return await pLC.WriteNodesAsync(nodeValues);
+        }
+
         /// <summary>
         /// <summary>
         /// 将点位数据写入到PLC地址
         /// 将点位数据写入到PLC地址
         /// </summary>
         /// </summary>

+ 16 - 0
TeamAAS-VM/Models/PressureModel.cs

@@ -33,5 +33,21 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref _PressureNumMax, value); }
             set { SetProperty(ref _PressureNumMax, value); }
         }
         }
 
 
+        private float _PressureUpLimit = 0;
+
+        public float PressureUpLimit
+        {
+            get { return _PressureUpLimit; }
+            set { SetProperty(ref _PressureUpLimit, value); }
+        }
+
+        private float _PressureDownLimit = 0;
+
+        public float PressureDownLimit
+        {
+            get { return _PressureDownLimit; }
+            set { SetProperty(ref _PressureDownLimit, value); }
+        }
+
     }
     }
 }
 }

+ 12 - 0
TeamAAS-VM/Models/Product/ProcedureModel.cs

@@ -284,6 +284,17 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref _SavePath, value); }
             set { SetProperty(ref _SavePath, value); }
         }
         }
 
 
+        //用户定义的图片文件名格式,例如:{ProductSN}_Daisy_KB Screw _01 _{CameraName}-Locate_{ShotCount}_WhiteRingLight_{Result}_{DateTime:yyyy-MM-dd_HH-mm-ss}.png
+        private string _ImageFileNameFormat;
+        /// <summary>
+        /// 用户定义的图片文件名格式,例如:{ProductSN}_Daisy_KB Screw _01 _{CameraName}-Locate_{ShotCount}_WhiteRingLight_{Result}_{DateTime:yyyy-MM-dd_HH-mm-ss}.png
+        /// </summary>
+        public string ImageFileNameFormat
+        {
+            get { return _ImageFileNameFormat; }
+            set { SetProperty(ref _ImageFileNameFormat, value); }
+        }
+
         private bool _IsCompress;
         private bool _IsCompress;
         /// <summary>
         /// <summary>
         /// 是否压缩图片
         /// 是否压缩图片
@@ -408,6 +419,7 @@ namespace TeamAAS_VP.Models
                 SaveImageModel = this.SaveImageModel,
                 SaveImageModel = this.SaveImageModel,
                 SaveImagePathModel = this.SaveImagePathModel,
                 SaveImagePathModel = this.SaveImagePathModel,
                 SavePath = this.SavePath,
                 SavePath = this.SavePath,
+                ImageFileNameFormat=this.ImageFileNameFormat,
                 IsCompress = this.IsCompress,
                 IsCompress = this.IsCompress,
                 FeederFindFrequency = this.FeederFindFrequency?.Copy(),
                 FeederFindFrequency = this.FeederFindFrequency?.Copy(),
                 IsExcludeNearPoint=this.IsExcludeNearPoint,
                 IsExcludeNearPoint=this.IsExcludeNearPoint,

+ 11 - 11
TeamAAS-VM/Models/ShowRender.cs

@@ -101,6 +101,17 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref _SavePath, value); }
             set { SetProperty(ref _SavePath, value); }
         }
         }
 
 
+        //用户定义的图片文件名
+        private string _ImageFileName;
+        /// <summary>
+        /// 用户定义的图片文件名
+        /// </summary>
+        public string ImageFileName
+        {
+            get { return _ImageFileName; }
+            set { SetProperty(ref _ImageFileName, value); }
+        }
+
         private bool _IsCompress;
         private bool _IsCompress;
         /// <summary>
         /// <summary>
         /// 是否压缩图片
         /// 是否压缩图片
@@ -111,15 +122,6 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref _IsCompress, value); }
             set { SetProperty(ref _IsCompress, value); }
         }
         }
 
 
-        private ProductModel _CurrentProduct;
-
-        public ProductModel CurrentProduct
-        {
-            get { return _CurrentProduct; }
-            set { _CurrentProduct = value; }
-        }
-
-
         private string _ProceductName;
         private string _ProceductName;
 
 
         public string ProceductName
         public string ProceductName
@@ -127,7 +129,5 @@ namespace TeamAAS_VP.Models
             get { return _ProceductName; }
             get { return _ProceductName; }
             set { _ProceductName = value; }
             set { _ProceductName = value; }
         }
         }
-
-
     }
     }
 }
 }

+ 1 - 1
TeamAAS-VM/Properties/AssemblyInfo.cs

@@ -51,5 +51,5 @@ using System.Windows;
 //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
 //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
 //通过使用 "*",如下所示:
 //通过使用 "*",如下所示:
 // [assembly: AssemblyVersion("1.0.*")]
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.2.1.3")]
+[assembly: AssemblyVersion("1.2.1.5")]
 [assembly: AssemblyFileVersion("1.2.1.3")]
 [assembly: AssemblyFileVersion("1.2.1.3")]

+ 9 - 0
TeamAAS-VM/Resources/Languages/Lang.Designer.cs

@@ -8097,6 +8097,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
             }
         }
         }
         
         
+        /// <summary>
+        ///   查找类似 视觉静态精度分析 的本地化字符串。
+        /// </summary>
+        public static string 视觉静态精度分析 {
+            get {
+                return ResourceManager.GetString("视觉静态精度分析", resourceCulture);
+            }
+        }
+        
         /// <summary>
         /// <summary>
         ///   查找类似 触发命令 的本地化字符串。
         ///   查找类似 触发命令 的本地化字符串。
         /// </summary>
         /// </summary>

+ 1 - 0
TeamAAS-VM/Resources/Languages/Lang.resx

@@ -2134,6 +2134,7 @@
   </data>
   </data>
   <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" xml:space="preserve">
   <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" xml:space="preserve">
     <value>年月/日/配方名/产品SN/产品SN+时间</value>
     <value>年月/日/配方名/产品SN/产品SN+时间</value>
+    <comment>枚举</comment>
   </data>
   </data>
   <data name="独立移动相机校准" xml:space="preserve">
   <data name="独立移动相机校准" xml:space="preserve">
     <value>- 独立移动相机校准</value>
     <value>- 独立移动相机校准</value>

+ 27 - 0
TeamAAS-VM/Resources/Languages/Lang.zh-TW.resx

@@ -3156,4 +3156,31 @@
   <data name="修改相机" xml:space="preserve">
   <data name="修改相机" xml:space="preserve">
     <value>修改相機</value>
     <value>修改相機</value>
   </data>
   </data>
+  <data name="通过下相机获取P0" xml:space="preserve">
+    <value>上下相機對拍,下相機取得P0</value>
+  </data>
+  <data name="是否控制光源通道亮灭" xml:space="preserve">
+    <value>是否控制光源通道亮滅</value>
+  </data>
+  <data name="CameraBrand_opt" xml:space="preserve">
+    <value>奧普特(OPT Camera Viewer)</value>
+  </data>
+  <data name="相机焦距评价" xml:space="preserve">
+    <value>相機焦距評價</value>
+  </data>
+  <data name="螺丝供料器" xml:space="preserve">
+    <value>螺絲供料器</value>
+  </data>
+  <data name="通过移动至下相机拍照位置拍照计算P0" xml:space="preserve">
+    <value>透過移動至下相機拍照位置,拍照得到P0,然後放回原位</value>
+  </data>
+  <data name="视觉静态精度分析" xml:space="preserve">
+    <value>視覺靜態精度分析</value>
+  </data>
+  <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" xml:space="preserve">
+    <value>年月/日/配方名/產品SN/產品SN+時間</value>
+  </data>
+  <data name="CameraMount_MobileDownIndependentXYPlatform" xml:space="preserve">
+    <value>獨立XY移動相機</value>
+  </data>
 </root>
 </root>

+ 165 - 21
TeamAAS-VM/Services/ConfigService.cs

@@ -52,6 +52,8 @@ namespace TeamAAS_VP.Services
             public static readonly string ScrewFeedersConfigurationPath = "..//Config//ScrewFeedersConfiguration.cfg";
             public static readonly string ScrewFeedersConfigurationPath = "..//Config//ScrewFeedersConfiguration.cfg";
             // 刷卡器配置路径
             // 刷卡器配置路径
             public static readonly string CardReaderConfigurationPath = "..//Config//CardReaderConfiguration.cfg";
             public static readonly string CardReaderConfigurationPath = "..//Config//CardReaderConfiguration.cfg";
+            // 生产数据配置路径
+            public static readonly string DataConfigurationPath = "..//Config//DataConfiguration.cfg";
         }
         }
 
 
         private readonly object _sync = new object();
         private readonly object _sync = new object();
@@ -66,8 +68,8 @@ namespace TeamAAS_VP.Services
         private ObservableCollection<FeederClearWork> FeederClearanceTasks { get; set; }
         private ObservableCollection<FeederClearWork> FeederClearanceTasks { get; set; }
         // 光源控制器配置
         // 光源控制器配置
         private ObservableCollection<LightControllerConfig> LightControllers { get; set; }
         private ObservableCollection<LightControllerConfig> LightControllers { get; set; }
-        // Device info
-        private DeviceInfo _deviceInfo;
+        // Device info - 支持多设备
+        private List<DeviceInfo> _deviceInfoList;
 
 
         private PlcAddressConfig PlcAddressConfig { get; set; }
         private PlcAddressConfig PlcAddressConfig { get; set; }
         // 单个电批配置
         // 单个电批配置
@@ -220,13 +222,34 @@ namespace TeamAAS_VP.Services
                     FileHelper.WriteJsonFile(_screwDriverConfig, ConfigPaths.ScrewDriverConfigurationPath);
                     FileHelper.WriteJsonFile(_screwDriverConfig, ConfigPaths.ScrewDriverConfigurationPath);
                 }
                 }
 
 
-                // load device info
+                // load device info list (支持多设备)
                 if (File.Exists(ConfigPaths.DeviceInfoConfigurationPath))
                 if (File.Exists(ConfigPaths.DeviceInfoConfigurationPath))
-                    _deviceInfo = FileHelper.ReadJsonFile<DeviceInfo>(ConfigPaths.DeviceInfoConfigurationPath);
+                {
+                    try
+                    {
+                        // 尝试作为列表读取
+                        _deviceInfoList = FileHelper.ReadJsonFile<List<DeviceInfo>>(ConfigPaths.DeviceInfoConfigurationPath);
+                    }
+                    catch
+                    {
+                        // 兼容旧版单个 DeviceInfo,将其转换为列表
+                        var singleDevice = FileHelper.ReadJsonFile<DeviceInfo>(ConfigPaths.DeviceInfoConfigurationPath);
+                        if (singleDevice != null)
+                        {
+                            singleDevice.DeviceNo = 0;
+                            _deviceInfoList = new List<DeviceInfo> { singleDevice };
+                        }
+                        else
+                        {
+                            _deviceInfoList = new List<DeviceInfo> { new DeviceInfo { DeviceNo = 0 } };
+                        }
+                        FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
+                    }
+                }
                 else
                 else
                 {
                 {
-                    _deviceInfo = new DeviceInfo();
-                    FileHelper.WriteJsonFile(_deviceInfo, ConfigPaths.DeviceInfoConfigurationPath);
+                    _deviceInfoList = new List<DeviceInfo> { new DeviceInfo { DeviceNo = 0 } };
+                    FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
                 }
                 }
 
 
                 // load card reader configuration
                 // load card reader configuration
@@ -237,6 +260,7 @@ namespace TeamAAS_VP.Services
                     _cardReaderConfig = new SerialPortConfig();
                     _cardReaderConfig = new SerialPortConfig();
                     FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
                     FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
                 }
                 }
+
             }
             }
         }
         }
 
 
@@ -273,9 +297,9 @@ namespace TeamAAS_VP.Services
                     FileHelper.WriteJsonFile(ScrewFeeders, ConfigPaths.ScrewFeedersConfigurationPath);
                     FileHelper.WriteJsonFile(ScrewFeeders, ConfigPaths.ScrewFeedersConfigurationPath);
                 // save plc addresses
                 // save plc addresses
                 //FileHelper.WriteJsonFile(PlcAddressConfig, "..//Config//PlcAddressConfiguration.cfg");
                 //FileHelper.WriteJsonFile(PlcAddressConfig, "..//Config//PlcAddressConfiguration.cfg");
-                // save device info
-                if (_deviceInfo != null)
-                    FileHelper.WriteJsonFile(_deviceInfo, ConfigPaths.DeviceInfoConfigurationPath);
+                // save device info list (支持多设备)
+                if (_deviceInfoList != null)
+                    FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
                 // save card reader config
                 // save card reader config
                 if (_cardReaderConfig != null)
                 if (_cardReaderConfig != null)
                     FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
                     FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
@@ -383,38 +407,158 @@ namespace TeamAAS_VP.Services
 
 
         #region DeviceInfo
         #region DeviceInfo
         /// <summary>
         /// <summary>
-        /// 获取设备信息配置
+        /// 获取所有设备信息配置列表
         /// </summary>
         /// </summary>
-        /// <returns></returns>
-        public DeviceInfo GetDeviceInfo()
+        /// <returns>设备信息列表的只读集合</returns>
+        public IReadOnlyCollection<DeviceInfo> GetAllDeviceInfos()
         {
         {
             lock (_sync)
             lock (_sync)
             {
             {
-                if (_deviceInfo == null)
+                if (_deviceInfoList == null)
                 {
                 {
                     if (File.Exists(ConfigPaths.DeviceInfoConfigurationPath))
                     if (File.Exists(ConfigPaths.DeviceInfoConfigurationPath))
-                        _deviceInfo = FileHelper.ReadJsonFile<DeviceInfo>(ConfigPaths.DeviceInfoConfigurationPath);
+                    {
+                        try
+                        {
+                            _deviceInfoList = FileHelper.ReadJsonFile<List<DeviceInfo>>(ConfigPaths.DeviceInfoConfigurationPath);
+                        }
+                        catch
+                        {
+                            // 兼容旧版单个 DeviceInfo
+                            var singleDevice = FileHelper.ReadJsonFile<DeviceInfo>(ConfigPaths.DeviceInfoConfigurationPath);
+                            if (singleDevice != null)
+                            {
+                                singleDevice.DeviceNo = 0;
+                                _deviceInfoList = new List<DeviceInfo> { singleDevice };
+                            }
+                            else
+                            {
+                                _deviceInfoList = new List<DeviceInfo> { new DeviceInfo { DeviceNo = 0 } };
+                            }
+                            FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
+                        }
+                    }
                     else
                     else
                     {
                     {
-                        _deviceInfo = new DeviceInfo();
-                        FileHelper.WriteJsonFile(_deviceInfo, ConfigPaths.DeviceInfoConfigurationPath);
+                        _deviceInfoList = new List<DeviceInfo> { new DeviceInfo { DeviceNo = 0 } };
+                        FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
                     }
                     }
                 }
                 }
-                return _deviceInfo;
+                return _deviceInfoList.AsReadOnly();
+            }
+        }
+
+        /// <summary>
+        /// 根据设备编号获取设备信息(兼容旧API,返回第一个设备)
+        /// </summary>
+        /// <returns>设备信息,若不存在则创建默认设备</returns>
+        public DeviceInfo GetDeviceInfo()
+        {
+            return GetDeviceInfo(0);
+        }
+
+        /// <summary>
+        /// 根据设备编号获取设备信息
+        /// </summary>
+        /// <param name="deviceNo">设备编号</param>
+        /// <returns>设备信息,若不存在则返回 null</returns>
+        public DeviceInfo GetDeviceInfo(int deviceNo)
+        {
+            lock (_sync)
+            {
+                var allDevices = GetAllDeviceInfos();
+                return allDevices.FirstOrDefault(d => d.DeviceNo == deviceNo);
             }
             }
         }
         }
 
 
         /// <summary>
         /// <summary>
-        /// 保存设备信息
+        /// 添加或更新设备信息
         /// </summary>
         /// </summary>
-        /// <param name="deviceInfo"></param>
+        /// <param name="deviceInfo">设备信息对象</param>
         public void SaveDeviceInfo(DeviceInfo deviceInfo)
         public void SaveDeviceInfo(DeviceInfo deviceInfo)
         {
         {
             if (deviceInfo == null) return;
             if (deviceInfo == null) return;
             lock (_sync)
             lock (_sync)
             {
             {
-                _deviceInfo = deviceInfo;
-                FileHelper.WriteJsonFile(_deviceInfo, ConfigPaths.DeviceInfoConfigurationPath);
+                // 确保列表已初始化
+                if (_deviceInfoList == null)
+                {
+                    _deviceInfoList = new List<DeviceInfo>();
+                }
+
+                // 查找是否已存在相同设备编号的设备
+                var existing = _deviceInfoList.FirstOrDefault(d => d.DeviceNo == deviceInfo.DeviceNo);
+                if (existing != null)
+                {
+                    // 更新现有设备
+                    var index = _deviceInfoList.IndexOf(existing);
+                    _deviceInfoList[index] = deviceInfo;
+                }
+                else
+                {
+                    // 添加新设备
+                    _deviceInfoList.Add(deviceInfo);
+                }
+                // 按设备编号排序
+                _deviceInfoList = _deviceInfoList.OrderBy(d => d.DeviceNo).ToList();
+                FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
+            }
+        }
+
+        /// <summary>
+        /// 保存所有设备信息列表
+        /// </summary>
+        /// <param name="deviceInfoList">设备信息列表</param>
+        public void SaveAllDeviceInfos(IEnumerable<DeviceInfo> deviceInfoList)
+        {
+            if (deviceInfoList == null) return;
+            lock (_sync)
+            {
+                _deviceInfoList = deviceInfoList.OrderBy(d => d.DeviceNo).ToList();
+                FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
+            }
+        }
+
+        /// <summary>
+        /// 添加新设备
+        /// </summary>
+        /// <returns>新添加的设备</returns>
+        public DeviceInfo AddDeviceInfo()
+        {
+            lock (_sync)
+            {
+                if (_deviceInfoList == null)
+                {
+                    _deviceInfoList = new List<DeviceInfo>();
+                }
+
+                // 计算新设备编号
+                int newDeviceNo = _deviceInfoList.Count > 0 ? _deviceInfoList.Max(d => d.DeviceNo) + 1 : 0;
+                var newDevice = new DeviceInfo { DeviceNo = newDeviceNo };
+                _deviceInfoList.Add(newDevice);
+                FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
+                return newDevice;
+            }
+        }
+
+        /// <summary>
+        /// 删除设备
+        /// </summary>
+        /// <param name="deviceNo">设备编号</param>
+        /// <returns>是否删除成功</returns>
+        public bool RemoveDeviceInfo(int deviceNo)
+        {
+            lock (_sync)
+            {
+                if (_deviceInfoList == null) return false;
+                var device = _deviceInfoList.FirstOrDefault(d => d.DeviceNo == deviceNo);
+                if (device != null)
+                {
+                    _deviceInfoList.Remove(device);
+                    FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
+                    return true;
+                }
+                return false;
             }
             }
         }
         }
         #endregion
         #endregion

+ 206 - 37
TeamAAS-VM/Services/MesService.cs

@@ -2,6 +2,7 @@ using Prism.Events;
 using Prism.Ioc;
 using Prism.Ioc;
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
+using System.Linq;
 using System.Net.Http;
 using System.Net.Http;
 using System.Text;
 using System.Text;
 using System.Threading;
 using System.Threading;
@@ -76,12 +77,14 @@ namespace TeamAAS_VP.Services
         /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
         /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
         /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
         /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
         /// </remarks>
         /// </remarks>
-        public async Task<(bool IsSuccess, string Response)> StationGetAsync(int num, string sn, string comp, CancellationToken cancellationToken = default)
+        public async Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, CancellationToken cancellationToken = default)
         {
         {
             // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
             // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
             if (_disposed) throw new ObjectDisposedException(nameof(MesService));
             if (_disposed) throw new ObjectDisposedException(nameof(MesService));
 
 
-            var device = _configService.GetDeviceInfo();
+            var device = _configService.GetDeviceInfo(deviceNo);
+            if (device == null)
+                device = _configService.GetDeviceInfo();
             if (device == null || !device.EnableMES)
             if (device == null || !device.EnableMES)
             {
             {
                 return (true, "MES功能未启用!");
                 return (true, "MES功能未启用!");
@@ -97,25 +100,21 @@ namespace TeamAAS_VP.Services
             }
             }
 
 
             string url = "";
             string url = "";
-            string[] station = new string[3];
-            string[] fixtureId = new string[3];
-            station = device.Station.Split(',');
-            fixtureId = device.FixtureId.Split(',');
 
 
-            if (num == 0)//组装站
+            if (deviceNo == 0)//组装站
             {
             {
                 if (device.F == "PTL")
                 if (device.F == "PTL")
                 {
                 {
-                    url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&comp={device.comp}:{comp}&p=unit_process_check,message,model";
+                    url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&comp={device.comp}:{comp}&p=unit_process_check,message,model,sn,wo";
                 }
                 }
                 else
                 else
                 {
                 {
-                    url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&p=unit_process_check,message,model";
+                    url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=unit_process_check,message,model,sn,wo";
                 }
                 }
             }
             }
             else//保压站
             else//保压站
             {
             {
-                url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&p=unit_process_check,message,model";
+                url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=unit_process_check,message,model,sn,wo";
             }
             }
 
 
             LogHelper.WriteLogMes($"【询问URL】{url}");
             LogHelper.WriteLogMes($"【询问URL】{url}");
@@ -135,7 +134,7 @@ namespace TeamAAS_VP.Services
                         // "SFC_OK" 代表和 MES 连接成功
                         // "SFC_OK" 代表和 MES 连接成功
                         if (text.Contains("SFC_OK"))
                         if (text.Contains("SFC_OK"))
                         {
                         {
-                            if (text.Contains("unit_process_check=OK"))
+                            if (text.Contains("message=OK"))
                             {
                             {
                                 return (true, text);
                                 return (true, text);
                             }
                             }
@@ -161,11 +160,93 @@ namespace TeamAAS_VP.Services
         /// <param name="sn">序列号(SN)。</param>
         /// <param name="sn">序列号(SN)。</param>
         /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
         /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
         /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
         /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
-        public async Task<(bool IsSuccess, string Response)> StationGetAsync(int num, string sn, string comp, double timeoutInSeconds)
+        public async Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, double timeoutInSeconds)
         {
         {
             using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
             using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
             {
             {
-                return await StationGetAsync(num, sn, comp, cts.Token);
+                return await StationGetAsync(deviceNo, sn, comp, cts.Token);
+            }
+        }
+
+        /// <summary>
+        /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
+        /// </summary>
+        /// <param name="sn">要查询的序列号(SN)。</param>
+        /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
+        /// <returns>
+        /// 返回元组 (IsSuccess, Response):
+        /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
+        /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
+        /// </returns>
+        /// <remarks>
+        /// 行为说明:
+        /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
+        /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
+        /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
+        /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
+        /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
+        /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
+        /// </remarks>
+        public async Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, CancellationToken cancellationToken = default)
+        {
+            // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
+            if (_disposed) throw new ObjectDisposedException(nameof(MesService));
+
+            var device = _configService.GetDeviceInfo(deviceNo);
+            if (device == null)
+                device = _configService.GetDeviceInfo();
+            if (device == null || !device.EnableMES)
+            {
+                return (true, "MES功能未启用!");
+            }
+            if (string.IsNullOrWhiteSpace(device.MesUrl))
+                return (false, "Missing MES station URL");
+
+            string url = "";
+            url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=message,sn,wo";
+
+            LogHelper.WriteLogMes($"【询问URL】{url}");
+            SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
+            (bool IsSuccess, string Response) result = (false, string.Empty);
+
+            for (int i = 0; i < 3; i++)
+            {
+                try
+                {
+                    using (var rsp = await _httpClient.GetAsync(url))
+                    {
+                        var text = await rsp.Content.ReadAsStringAsync();
+                        LogHelper.WriteLogMes($"【HTTP接收】{text}");
+                        SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
+
+                        // "SFC_OK" 代表和 MES 连接成功
+                        if (text.Contains("SFC_OK"))
+                        {
+                            if (text.Contains("message=OK"))
+                            {
+                                return (true, text);
+                            }
+                        }
+                        result = (false, text);
+                    }
+                }
+                catch (OperationCanceledException)
+                {
+                    result = (false, "Canceled");
+                }
+                catch (Exception ex)
+                {
+                    result = (false, ex.Message);
+                }
+            }
+            return result;
+        }
+
+        public async Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, double timeoutInSeconds)
+        {
+            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
+            {
+                return await StationGetExAsync(deviceNo, sn, comp, cts.Token);
             }
             }
         }
         }
 
 
@@ -191,12 +272,14 @@ namespace TeamAAS_VP.Services
         /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
         /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
         /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
         /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
         /// </remarks>
         /// </remarks>
-        public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int num, string sn, string comp, string gap, string press, string presstime, string assypress, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
+        public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo, string sn, string comp, bool isSuccess, Dictionary<string, string> data, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
         {
         {
             // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
             // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
             if (_disposed) throw new ObjectDisposedException(nameof(MesService));
             if (_disposed) throw new ObjectDisposedException(nameof(MesService));
 
 
-            var device = _configService.GetDeviceInfo();
+            var device = _configService.GetDeviceInfo(deviceNo);
+            if (device == null)
+                device = _configService.GetDeviceInfo();
             if (device == null || !device.EnableMES)
             if (device == null || !device.EnableMES)
             {
             {
                 return (true, "MES功能未启用!");
                 return (true, "MES功能未启用!");
@@ -212,34 +295,50 @@ namespace TeamAAS_VP.Services
             }
             }
 
 
             string res = isSuccess ? "PASS" : "FAIL";
             string res = isSuccess ? "PASS" : "FAIL";
-            string url = "";
-            string[] station = new string[3];
-            string[] fixtureId = new string[3];
-            station = device.Station.Split(',');
-            fixtureId = device.FixtureId.Split(',');
-
-            if (num == 0)//组装站
+            StringBuilder sb = new StringBuilder();
+            if (device.F == "PTL")
             {
             {
-                if (device.F == "PTL")
-                {
-                    url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
-                    $"&gap={gap}&assy_pressure={assypress}" +
-                    $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
-                }
-                else
+                sb.Append($"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}");
+                foreach (var item in data)
                 {
                 {
-                    url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&f=PQC" +
-                  $"&gap={gap}&assy_pressure={assypress}" +
-                  $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
+                    sb.Append($"&{item.Key}={item.Value}");
                 }
                 }
+                sb.Append($"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}");
             }
             }
             else
             else
             {
             {
-                url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&f=PQC" +
-                  $"&pressure={press}&pressure_time={presstime}" +
-                  $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
+                sb.Append($"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC");
+                foreach (var item in data)
+                {
+                    sb.Append($"&{item.Key}={item.Value}");
+                }
+                sb.Append($"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}");
             }
             }
 
 
+            string url = sb.ToString();
+
+            //if (deviceNo == 0)//组装站
+            //{
+            //    if (device.F == "PTL")
+            //    {
+            //        url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[deviceNo]}&fixtureid={fixtureId[deviceNo]}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
+            //        $"&gap={gap}&assy_pressure={assypress}" +
+            //        $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
+            //    }
+            //    else
+            //    {
+            //        url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[deviceNo]}&fixtureid={fixtureId[deviceNo]}&sn={sn}&f=PQC" +
+            //      $"&gap={gap}&assy_pressure={assypress}" +
+            //      $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
+            //    }
+            //}
+            //else
+            //{
+            //    url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[deviceNo]}&fixtureid={fixtureId[deviceNo]}&sn={sn}&f=PQC" +
+            //      $"&pressure={press}&pressure_time={presstime}" +
+            //      $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
+            //}
+
             LogHelper.WriteLogMes($"【上传URL】{url}");
             LogHelper.WriteLogMes($"【上传URL】{url}");
             SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
             SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
             (bool IsSuccess, string Response) result = (false, string.Empty);
             (bool IsSuccess, string Response) result = (false, string.Empty);
@@ -287,12 +386,82 @@ namespace TeamAAS_VP.Services
         /// <param name="stop_time">结束时间。</param>
         /// <param name="stop_time">结束时间。</param>
         /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
         /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
         /// <returns>与 <see cref="SubmitGetAsync(string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
         /// <returns>与 <see cref="SubmitGetAsync(string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
-        public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int num, string sn, string comp, string gap, string press, string presstime, string assypress, bool isSuccess, DateTime start_time, DateTime stop_time, double timeoutInSeconds)
+        public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo, string sn, string comp, bool isSuccess, Dictionary<string, string> data, DateTime start_time, DateTime stop_time, double timeoutInSeconds)
         {
         {
             using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
             using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
             {
             {
-                return await SubmitGetAsync(num, sn, comp, gap, press, presstime, assypress, isSuccess, start_time, stop_time, cts.Token);
+                return await SubmitGetAsync(deviceNo, sn, comp, isSuccess, data, start_time, stop_time, cts.Token);
+            }
+        }
+
+        /// <summary>
+        /// 获取服务器当前时间
+        /// </summary>
+        /// <param name="sn"></param>
+        /// <param name="timeoutInSeconds"></param>
+        /// <returns></returns>
+        public async Task<(bool IsSuccess, DateTime Now)> GetServerTimeAsync(int deviceNo, string sn, double timeoutInSeconds)
+        {
+            // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
+            if (_disposed) throw new ObjectDisposedException(nameof(MesService));
+
+            var device = _configService.GetDeviceInfo(deviceNo);
+            if (device == null)
+                device = _configService.GetDeviceInfo();
+            if (device == null || !device.EnableMES)
+            {
+                return (true, DateTime.UtcNow);
+            }
+            if (string.IsNullOrWhiteSpace(device.MesUrl))
+                return (false, DateTime.UtcNow);
+
+            string url = "";
+            url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=mes_server_time";
+
+            LogHelper.WriteLogMes($"【询问URL】{url}");
+            SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
+            (bool IsSuccess, DateTime Now) result = (false, DateTime.UtcNow);
+
+            for (int i = 0; i < 3; i++)
+            {
+                try
+                {
+                    using (var rsp = await _httpClient.GetAsync(url))
+                    {
+                        var text = await rsp.Content.ReadAsStringAsync();
+                        LogHelper.WriteLogMes($"【HTTP接收】{text}");
+                        SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
+
+                        // "SFC_OK" 代表和 MES 连接成功
+                        if (text.Contains("SFC_OK"))
+                        {
+                            //按照分隔符'/n'分割字符串
+                            string[] lines = text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
+                            //通过linq查找是否包含"mes_server_time"的行
+                            var timeLine = lines.FirstOrDefault(l => l.Contains("mes_server_time"));
+                            if (timeLine != null)
+                            {
+                                // 提取时间字符串
+                                var timeString = timeLine.Split('=')[1].Trim();
+                                if (DateTime.TryParse(timeString, out DateTime serverTime))
+                                {
+                                    return (true, serverTime);
+                                }
+                            }
+                        }
+                        result = (false, DateTime.UtcNow);
+                    }
+                }
+                catch (OperationCanceledException)
+                {
+                    result = (false, DateTime.UtcNow);
+                }
+                catch (Exception ex)
+                {
+                    result = (false, DateTime.UtcNow);
+                }
             }
             }
+            return result;
         }
         }
 
 
         /// <summary>
         /// <summary>

+ 96 - 16
TeamAAS-VM/Services/RemoteCommandService.cs

@@ -1185,7 +1185,7 @@ namespace TeamAAS_VP.Services
                 SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
                 SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
 
 
                 // 1. 执行相机拍照并运行视觉工具
                 // 1. 执行相机拍照并运行视觉工具
-                bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
+                bool visionSucceed = ExecutePhoto(i + 1, procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
                 if (!visionSucceed)
                 if (!visionSucceed)
                 {
                 {
                     SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
                     SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
@@ -1374,7 +1374,7 @@ namespace TeamAAS_VP.Services
                     }
                     }
                     // 1. 执行相机拍照并运行视觉工具
                     // 1. 执行相机拍照并运行视觉工具
                     LogHelper.WriteLogInfo("开始执行相机拍照并运行视觉工具");
                     LogHelper.WriteLogInfo("开始执行相机拍照并运行视觉工具");
-                    bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
+                    bool visionSucceed = ExecutePhoto(i + 1, procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
                     if (!visionSucceed)
                     if (!visionSucceed)
                     {
                     {
                         SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
                         SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
@@ -1452,7 +1452,7 @@ namespace TeamAAS_VP.Services
         /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
         /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
         /// 该方法会发布 RenderUpdateNotification 以更新 UI。
         /// 该方法会发布 RenderUpdateNotification 以更新 UI。
         /// </summary>
         /// </summary>
-        public bool ExecutePhoto(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
+        public bool ExecutePhoto(int index, ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
         {
         {
             try
             try
             {
             {
@@ -1516,20 +1516,41 @@ namespace TeamAAS_VP.Services
                         if (item.Value is ICogRecord)
                         if (item.Value is ICogRecord)
                             record = item.Value as ICogRecord;
                             record = item.Value as ICogRecord;
                     }
                     }
+
+                    bool Found = (bool)(outputCollection["Found"].Value);
+                    //获取图片存储的图片文件名
+                    string imgName = string.Empty;
+                    if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
+                    {
+                        // 创建模板,使用 {变量名:格式} 语法
+                        var template = new FileNameTemplate(procedure.ImageFileNameFormat);
+
+                        // 注册变量
+                        template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
+                        template.RegisterVariable("CameraName", () => procedure.CameraName);
+                        template.RegisterVariable("ShotCount", () => index);
+                        template.RegisterVariable("Result", () => Found ? "OK" : "NG");
+                        template.RegisterVariable("DateTime", () => DateTime.Now);
+
+                        // 生成文件名
+                        imgName = template.Generate();
+                    }
+
                     _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
                     _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
                     {
                     {
                         Id = procedure.Id,
                         Id = procedure.Id,
                         Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
                         Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
                         Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
                         Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
                         Record = record,
                         Record = record,
-                        Result = (bool)(outputCollection["Found"].Value),
+                        Result = Found,
                         IsShow = true,
                         IsShow = true,
                         IsSaveImage = procedure.IsSaveImage,
                         IsSaveImage = procedure.IsSaveImage,
                         SaveImageModel = procedure.SaveImageModel,
                         SaveImageModel = procedure.SaveImageModel,
                         SaveImagePathModel = procedure.SaveImagePathModel,
                         SaveImagePathModel = procedure.SaveImagePathModel,
                         SavePath = procedure.SavePath,
                         SavePath = procedure.SavePath,
                         IsCompress = procedure.IsCompress,
                         IsCompress = procedure.IsCompress,
-                        ProceductName = procedure.Name
+                        ProceductName = procedure.Name,
+                        ImageFileName = imgName
                     });
                     });
                     return true;
                     return true;
                 }
                 }
@@ -1538,6 +1559,24 @@ namespace TeamAAS_VP.Services
                     SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
                     SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
                     SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
                     SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
                     outputCollection = null;
                     outputCollection = null;
+
+                    //获取图片存储的图片文件名
+                    string imgName = string.Empty;
+                    if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
+                    {
+                        // 创建模板,使用 {变量名:格式} 语法
+                        var template = new FileNameTemplate(procedure.ImageFileNameFormat);
+
+                        // 注册变量
+                        template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
+                        template.RegisterVariable("CameraName", () => procedure.CameraName);
+                        template.RegisterVariable("ShotCount", () => index);
+                        template.RegisterVariable("Result", () => "NG");
+                        template.RegisterVariable("DateTime", () => DateTime.Now);
+
+                        // 生成文件名
+                        imgName = template.Generate();
+                    }
                     _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
                     _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
                     {
                     {
                         Id = procedure.Id,
                         Id = procedure.Id,
@@ -1550,6 +1589,7 @@ namespace TeamAAS_VP.Services
                         SaveImagePathModel = procedure.SaveImagePathModel,
                         SaveImagePathModel = procedure.SaveImagePathModel,
                         SavePath = procedure.SavePath,
                         SavePath = procedure.SavePath,
                         ProceductName = procedure.Name,
                         ProceductName = procedure.Name,
+                        ImageFileName = imgName
                     });
                     });
                     return false;
                     return false;
                 }
                 }
@@ -1569,7 +1609,7 @@ namespace TeamAAS_VP.Services
         /// <param name="procedure"></param>
         /// <param name="procedure"></param>
         /// <param name="outputCollection"></param>
         /// <param name="outputCollection"></param>
         /// <returns></returns>
         /// <returns></returns>
-        public bool ExecutePhoto(ProcedureModel procedure, out CogToolBlockTerminalCollection outputCollection)
+        public bool ExecutePhoto(int index, ProcedureModel procedure, out CogToolBlockTerminalCollection outputCollection)
         {
         {
             try
             try
             {
             {
@@ -1614,20 +1654,41 @@ namespace TeamAAS_VP.Services
                         if (item.Value is ICogRecord)
                         if (item.Value is ICogRecord)
                             record = item.Value as ICogRecord;
                             record = item.Value as ICogRecord;
                     }
                     }
+
+                    bool Found = (bool)(outputCollection["Found"].Value);
+                    //获取图片存储的图片文件名
+                    string imgName = string.Empty;
+                    if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
+                    {
+                        // 创建模板,使用 {变量名:格式} 语法
+                        var template = new FileNameTemplate(procedure.ImageFileNameFormat);
+
+                        // 注册变量
+                        template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
+                        template.RegisterVariable("CameraName", () => procedure.CameraName);
+                        template.RegisterVariable("ShotCount", () => index);
+                        template.RegisterVariable("Result", () => Found ? "OK" : "NG");
+                        template.RegisterVariable("DateTime", () => DateTime.Now);
+
+                        // 生成文件名
+                        imgName = template.Generate();
+                    }
+
                     _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
                     _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
                     {
                     {
                         Id = procedure.Id,
                         Id = procedure.Id,
                         Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
                         Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
                         Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
                         Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
                         Record = record,
                         Record = record,
-                        Result = (bool)(outputCollection["Found"].Value),
+                        Result = Found,
                         IsShow = true,
                         IsShow = true,
                         IsSaveImage = procedure.IsSaveImage,
                         IsSaveImage = procedure.IsSaveImage,
                         SaveImageModel = procedure.SaveImageModel,
                         SaveImageModel = procedure.SaveImageModel,
                         SaveImagePathModel = procedure.SaveImagePathModel,
                         SaveImagePathModel = procedure.SaveImagePathModel,
                         SavePath = procedure.SavePath,
                         SavePath = procedure.SavePath,
                         IsCompress = procedure.IsCompress,
                         IsCompress = procedure.IsCompress,
-                        ProceductName = procedure.Name
+                        ProceductName = procedure.Name,
+                        ImageFileName = imgName
                     });
                     });
                     SendTaskMessage($"{procedure.CameraName},{procedure.CameraId}", MessageLevel.Info);
                     SendTaskMessage($"{procedure.CameraName},{procedure.CameraId}", MessageLevel.Info);
                     return true;
                     return true;
@@ -1637,6 +1698,24 @@ namespace TeamAAS_VP.Services
                     SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
                     SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
                     SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
                     SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
                     outputCollection = null;
                     outputCollection = null;
+
+                    //获取图片存储的图片文件名
+                    string imgName = string.Empty;
+                    if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
+                    {
+                        // 创建模板,使用 {变量名:格式} 语法
+                        var template = new FileNameTemplate(procedure.ImageFileNameFormat);
+
+                        // 注册变量
+                        template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
+                        template.RegisterVariable("CameraName", () => procedure.CameraName);
+                        template.RegisterVariable("ShotCount", () => index);
+                        template.RegisterVariable("Result", () => "NG");
+                        template.RegisterVariable("DateTime", () => DateTime.Now);
+
+                        // 生成文件名
+                        imgName = template.Generate();
+                    }
                     _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
                     _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
                     {
                     {
                         Id = procedure.Id,
                         Id = procedure.Id,
@@ -1649,6 +1728,7 @@ namespace TeamAAS_VP.Services
                         SaveImagePathModel = procedure.SaveImagePathModel,
                         SaveImagePathModel = procedure.SaveImagePathModel,
                         SavePath = procedure.SavePath,
                         SavePath = procedure.SavePath,
                         ProceductName = procedure.Name,
                         ProceductName = procedure.Name,
+                        ImageFileName = imgName
                     });
                     });
                     return false;
                     return false;
                 }
                 }
@@ -1671,13 +1751,13 @@ namespace TeamAAS_VP.Services
         /// <param name="outImage"></param>
         /// <param name="outImage"></param>
         /// <param name="outGraphicCollection"></param>
         /// <param name="outGraphicCollection"></param>
         /// <returns></returns>
         /// <returns></returns>
-        public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection,out ICogImage outImage,out CogGraphicCollection outGraphicCollection)
+        public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection, out ICogImage outImage, out CogGraphicCollection outGraphicCollection)
         {
         {
             outImage = null;
             outImage = null;
             outGraphicCollection = null;
             outGraphicCollection = null;
             try
             try
             {
             {
-                
+
                 // 1. 采集图像
                 // 1. 采集图像
                 var camera = _cameraService.GetCamera(procedure.CameraId);
                 var camera = _cameraService.GetCamera(procedure.CameraId);
                 bool succed = camera.SetExposureTime(procedure.ExposureTime);
                 bool succed = camera.SetExposureTime(procedure.ExposureTime);
@@ -1700,7 +1780,7 @@ namespace TeamAAS_VP.Services
                     outputCollection = null;
                     outputCollection = null;
                     return false;
                     return false;
                 }
                 }
-                outImage= image;
+                outImage = image;
                 procedure.ToolBlock.Inputs["InputImage"].Value = image;
                 procedure.ToolBlock.Inputs["InputImage"].Value = image;
                 LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
                 LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
 
 
@@ -1738,7 +1818,7 @@ namespace TeamAAS_VP.Services
                         if (item.Value is ICogRecord)
                         if (item.Value is ICogRecord)
                             record = item.Value as ICogRecord;
                             record = item.Value as ICogRecord;
                     }
                     }
-                    outGraphicCollection= outputCollection["Graphic"].Value as CogGraphicCollection;
+                    outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
                     return true;
                     return true;
                 }
                 }
                 else
                 else
@@ -1781,7 +1861,7 @@ namespace TeamAAS_VP.Services
                     SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
                     SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
 
 
                     // 1. 执行相机拍照并运行视觉工具
                     // 1. 执行相机拍照并运行视觉工具
-                    bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
+                    bool visionSucceed = ExecutePhoto(i + 1, procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
                     if (!visionSucceed)
                     if (!visionSucceed)
                     {
                     {
                         SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
                         SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
@@ -1881,7 +1961,7 @@ namespace TeamAAS_VP.Services
                     SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
                     SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
 
 
                     // 1. 执行相机拍照并运行视觉工具
                     // 1. 执行相机拍照并运行视觉工具
-                    bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
+                    bool visionSucceed = ExecutePhoto(i + 1, procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
                     if (!visionSucceed)
                     if (!visionSucceed)
                     {
                     {
                         SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
                         SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
@@ -2007,8 +2087,8 @@ namespace TeamAAS_VP.Services
         {
         {
             DateTime nowtime = DateTime.Now;
             DateTime nowtime = DateTime.Now;
             await SetLightBeforePhoto(procedure);
             await SetLightBeforePhoto(procedure);
-            ICogImage outImage=null;
-            CogGraphicCollection outGraphicCollection=null;
+            ICogImage outImage = null;
+            CogGraphicCollection outGraphicCollection = null;
             try
             try
             {
             {
                 //拍照失败时,需要多次拍照
                 //拍照失败时,需要多次拍照

+ 4 - 0
TeamAAS-VM/TeamAAS-VP.csproj

@@ -532,12 +532,15 @@
     <Compile Include="Controls\PlcRobotManual.xaml.cs">
     <Compile Include="Controls\PlcRobotManual.xaml.cs">
       <DependentUpon>PlcRobotManual.xaml</DependentUpon>
       <DependentUpon>PlcRobotManual.xaml</DependentUpon>
     </Compile>
     </Compile>
+    <Compile Include="Core\FileNameTemplate.cs" />
     <Compile Include="Core\RectangleCenterCalculator.cs" />
     <Compile Include="Core\RectangleCenterCalculator.cs" />
     <Compile Include="Core\StabilityAnalyzer.cs" />
     <Compile Include="Core\StabilityAnalyzer.cs" />
     <Compile Include="Core\VisionProFileHelper.cs" />
     <Compile Include="Core\VisionProFileHelper.cs" />
     <Compile Include="Events\MainTabSwitchNotification.cs" />
     <Compile Include="Events\MainTabSwitchNotification.cs" />
     <Compile Include="Interfaces\IMesService.cs" />
     <Compile Include="Interfaces\IMesService.cs" />
     <Compile Include="Models\AssemblyRecord.cs" />
     <Compile Include="Models\AssemblyRecord.cs" />
+    <Compile Include="Models\CTQ_Data.cs" />
+    <Compile Include="Models\DataFormCtq.cs" />
     <Compile Include="Models\DeviceInfo.cs" />
     <Compile Include="Models\DeviceInfo.cs" />
     <Compile Include="Models\Feeder\ScrewFeederInfo.cs" />
     <Compile Include="Models\Feeder\ScrewFeederInfo.cs" />
     <Compile Include="Models\PhotoCaptureRecord.cs" />
     <Compile Include="Models\PhotoCaptureRecord.cs" />
@@ -545,6 +548,7 @@
     <Compile Include="Models\ScrewFeederBatchRecord.cs" />
     <Compile Include="Models\ScrewFeederBatchRecord.cs" />
     <Compile Include="Services\MesService.cs" />
     <Compile Include="Services\MesService.cs" />
     <Compile Include="ValueConverter\CountToColumnsConverter.cs" />
     <Compile Include="ValueConverter\CountToColumnsConverter.cs" />
+    <Compile Include="ValueConverter\ImageFileNameFormatConverter.cs" />
     <Compile Include="ViewModels\Calibration\CalibrationDistortionViewModel.cs" />
     <Compile Include="ViewModels\Calibration\CalibrationDistortionViewModel.cs" />
     <Compile Include="ViewModels\Calibration\CalibIndependentCameraViewModel.cs" />
     <Compile Include="ViewModels\Calibration\CalibIndependentCameraViewModel.cs" />
     <Compile Include="ViewModels\DebugMod\PlcRobotManualStepViewModel.cs" />
     <Compile Include="ViewModels\DebugMod\PlcRobotManualStepViewModel.cs" />

+ 43 - 0
TeamAAS-VM/ValueConverter/ImageFileNameFormatConverter.cs

@@ -0,0 +1,43 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Data;
+using TeamAAS_VP.Core;
+
+namespace TeamAAS_VP.ValueConverter
+{
+    public class ImageFileNameFormatConverter : IValueConverter
+    {
+        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
+        {
+            try
+            {
+                if (value == null) return string.Empty;
+                // 创建模板,使用 {变量名:格式} 语法
+                var template = new FileNameTemplate(value.ToString());
+
+                // 注册变量
+                template.RegisterVariable("ProductSN", () => "SN12345");
+                template.RegisterVariable("CameraName", () => "MainCamera");
+                template.RegisterVariable("ShotCount", () => 3);
+                template.RegisterVariable("Result", () => "OK");
+                template.RegisterVariable("DateTime", () => DateTime.Now);
+
+                // 生成文件名
+                string fileName = template.Generate();
+                return fileName;
+            }
+            catch (Exception)
+            {
+                return value.ToString();
+            }
+        }
+
+        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 3 - 1
TeamAAS-VM/ViewModels/HomeViewModel.cs

@@ -336,7 +336,7 @@ namespace TeamAAS_VP.ViewModels
         {
         {
             try
             try
             {
             {
-                if (MessageQueue.Count >= 20)
+                if (MessageQueue.Count >= 200)
                 {
                 {
                     MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
                     MessageQueue.RemoveAt(0);// 从队列头部移除最早的消息
                 }
                 }
@@ -516,6 +516,8 @@ namespace TeamAAS_VP.ViewModels
                         double xValue = (dataPoint.Timestamp - xAxisStart).TotalSeconds;
                         double xValue = (dataPoint.Timestamp - xAxisStart).TotalSeconds;
                         series.Points.Add(new OxyPlot.DataPoint(xValue, dataPoint.Value));
                         series.Points.Add(new OxyPlot.DataPoint(xValue, dataPoint.Value));
                     }
                     }
+                    // 重置所有轴的范围以适应新数据
+                    model.ResetAllAxes();
                     model.InvalidatePlot(true);
                     model.InvalidatePlot(true);
                     if (!string.IsNullOrEmpty(tuple.SavePath))
                     if (!string.IsNullOrEmpty(tuple.SavePath))
                     {
                     {

+ 1 - 15
TeamAAS-VM/ViewModels/MainWindowViewModel.cs

@@ -1,7 +1,4 @@
-using Basler.Pylon;
-using CSScriptLib;
-using NPOI.SS.Formula.Functions;
-using NPOI.XSSF.Streaming.Values;
+using MathNet.Numerics.LinearAlgebra;
 using Prism.Commands;
 using Prism.Commands;
 using Prism.Events;
 using Prism.Events;
 using Prism.Ioc;
 using Prism.Ioc;
@@ -9,20 +6,13 @@ using Prism.Mvvm;
 using Prism.Regions;
 using Prism.Regions;
 using Prism.Services.Dialogs;
 using Prism.Services.Dialogs;
 using System;
 using System;
-using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Collections.ObjectModel;
-using System.Globalization;
 using System.Linq;
 using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using System.Windows;
 using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Controls.Primitives;
 using System.Windows.Media;
 using System.Windows.Media;
 using Team.FFFeederService.Interfaces;
 using Team.FFFeederService.Interfaces;
-using TeamAAS_VP;
 using TeamAAS_VP.Controls;
 using TeamAAS_VP.Controls;
 using TeamAAS_VP.Core;
 using TeamAAS_VP.Core;
 using TeamAAS_VP.Data;
 using TeamAAS_VP.Data;
@@ -31,11 +21,7 @@ using TeamAAS_VP.Events;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.Resources.Languages;
-using TeamAAS_VP.Services;
 using TeamAAS_VP.ViewModels.Home;
 using TeamAAS_VP.ViewModels.Home;
-using TeamAAS_VP.Views;
-using WPFLocalizeExtension.Engine;
-using static MaterialDesignThemes.Wpf.Theme.ToolBar;
 
 
 namespace TeamAAS_VP.ViewModels
 namespace TeamAAS_VP.ViewModels
 {
 {

+ 124 - 10
TeamAAS-VM/ViewModels/SettingViewModel.cs

@@ -328,11 +328,39 @@ namespace TeamAAS_VP.ViewModels
             set { SetProperty(ref _SelectLightController, value); }
             set { SetProperty(ref _SelectLightController, value); }
         }
         }
 
 
-        private DeviceInfo _DeviceInfo;
+        // 设备信息列表
+        private ObservableCollection<DeviceInfo> _DeviceInfoList;
+        public ObservableCollection<DeviceInfo> DeviceInfoList
+        {
+            get { return _DeviceInfoList; }
+            set { SetProperty(ref _DeviceInfoList, value); }
+        }
+
+        // 当前选中的设备信息
+        private DeviceInfo _SelectDeviceInfo;
+        public DeviceInfo SelectDeviceInfo
+        {
+            get { return _SelectDeviceInfo; }
+            set { SetProperty(ref _SelectDeviceInfo, value); }
+        }
+
+        // 兼容旧代码,DeviceInfo 指向当前选中的设备或第一个设备
         public DeviceInfo DeviceInfo
         public DeviceInfo DeviceInfo
         {
         {
-            get { return _DeviceInfo; }
-            set { SetProperty(ref _DeviceInfo, value); }
+            get { return _SelectDeviceInfo ?? DeviceInfoList?.FirstOrDefault(); }
+            set
+            {
+                if (value != null && DeviceInfoList != null)
+                {
+                    var existing = DeviceInfoList.FirstOrDefault(d => d.DeviceNo == value.DeviceNo);
+                    if (existing != null)
+                    {
+                        var index = DeviceInfoList.IndexOf(existing);
+                        DeviceInfoList[index] = value;
+                    }
+                }
+                RaisePropertyChanged();
+            }
         }
         }
 
 
         private SerialPortConfig _CardReaderConfig;
         private SerialPortConfig _CardReaderConfig;
@@ -446,6 +474,12 @@ namespace TeamAAS_VP.ViewModels
         public DelegateCommand SaveScrewFeedersCommand =>
         public DelegateCommand SaveScrewFeedersCommand =>
             _SaveScrewFeedersCommand ?? (_SaveScrewFeedersCommand = new DelegateCommand(ExecuteSaveScrewFeedersCommand));
             _SaveScrewFeedersCommand ?? (_SaveScrewFeedersCommand = new DelegateCommand(ExecuteSaveScrewFeedersCommand));
 
 
+        private DelegateCommand _AddDeviceInfoCommand;
+        public DelegateCommand AddDeviceInfoCommand => _AddDeviceInfoCommand ?? (_AddDeviceInfoCommand = new DelegateCommand(ExecuteAddDeviceInfoCommand));
+
+        private DelegateCommand _RemoveDeviceInfoCommand;
+        public DelegateCommand RemoveDeviceInfoCommand => _RemoveDeviceInfoCommand ?? (_RemoveDeviceInfoCommand = new DelegateCommand(ExecuteRemoveDeviceInfoCommand));
+
         private DelegateCommand _SaveDeviceInfoCommand;
         private DelegateCommand _SaveDeviceInfoCommand;
         public DelegateCommand SaveDeviceInfoCommand => _SaveDeviceInfoCommand ?? (_SaveDeviceInfoCommand = new DelegateCommand(ExecuteSaveDeviceInfoCommand));
         public DelegateCommand SaveDeviceInfoCommand => _SaveDeviceInfoCommand ?? (_SaveDeviceInfoCommand = new DelegateCommand(ExecuteSaveDeviceInfoCommand));
 
 
@@ -460,7 +494,6 @@ namespace TeamAAS_VP.ViewModels
         private DelegateCommand<object> _BrowsePressureCurvePathCommand;
         private DelegateCommand<object> _BrowsePressureCurvePathCommand;
         public DelegateCommand<object> BrowsePressureCurvePathCommand =>
         public DelegateCommand<object> BrowsePressureCurvePathCommand =>
             _BrowsePressureCurvePathCommand ?? (_BrowsePressureCurvePathCommand = new DelegateCommand<object>(ExecuteBrowsePressureCurvePathCommand));
             _BrowsePressureCurvePathCommand ?? (_BrowsePressureCurvePathCommand = new DelegateCommand<object>(ExecuteBrowsePressureCurvePathCommand));
-
         #endregion
         #endregion
 
 
         #region 事件
         #region 事件
@@ -1359,10 +1392,16 @@ namespace TeamAAS_VP.ViewModels
                 BgModbus = _configService.GetBgModbusTcp();
                 BgModbus = _configService.GetBgModbusTcp();
             }
             }
 
 
-            if (DeviceInfo == null)
+            if (DeviceInfoList == null || DeviceInfoList.Count == 0)
             {
             {
-                // load device info
-                DeviceInfo = _configService.GetDeviceInfo();
+                // load device info list (支持多设备)
+                var devices = _configService.GetAllDeviceInfos();
+                DeviceInfoList = new ObservableCollection<DeviceInfo>(devices);
+                // 默认选中第一个设备
+                if (DeviceInfoList.Count > 0)
+                {
+                    SelectDeviceInfo = DeviceInfoList[0];
+                }
             }
             }
 
 
             if (CardReaderConfig == null)
             if (CardReaderConfig == null)
@@ -1640,15 +1679,16 @@ namespace TeamAAS_VP.ViewModels
 
 
         #region 设备信息
         #region 设备信息
         /// <summary>
         /// <summary>
-        /// 保存设备信息
+        /// 保存当前选中的设备信息
         /// </summary>
         /// </summary>
         void ExecuteSaveDeviceInfoCommand()
         void ExecuteSaveDeviceInfoCommand()
         {
         {
             try
             try
             {
             {
-                if (DeviceInfo != null)
+                if (DeviceInfoList != null && DeviceInfoList.Count > 0)
                 {
                 {
-                    _configService.SaveDeviceInfo(DeviceInfo);
+                    // 保存所有设备信息
+                    _configService.SaveAllDeviceInfos(DeviceInfoList);
                     _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
                     _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
                 }
                 }
             }
             }
@@ -1657,6 +1697,80 @@ namespace TeamAAS_VP.ViewModels
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
             }
             }
         }
         }
+
+        /// <summary>
+        /// 添加新设备
+        /// </summary>
+        void ExecuteAddDeviceInfoCommand()
+        {
+            try
+            {
+                var newDevice = _configService.AddDeviceInfo();
+                if (DeviceInfoList == null)
+                {
+                    DeviceInfoList = new ObservableCollection<DeviceInfo>();
+                }
+                DeviceInfoList.Add(newDevice);
+                SelectDeviceInfo = newDevice;
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
+            }
+            catch (Exception ex)
+            {
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
+            }
+        }
+
+        /// <summary>
+        /// 删除当前选中的设备
+        /// </summary>
+        void ExecuteRemoveDeviceInfoCommand()
+        {
+            try
+            {
+                if (SelectDeviceInfo != null && DeviceInfoList != null && DeviceInfoList.Count > 1)
+                {
+                    var deviceNo = SelectDeviceInfo.DeviceNo;
+                    if (_configService.RemoveDeviceInfo(deviceNo))
+                    {
+                        DeviceInfoList.Remove(SelectDeviceInfo);
+                        SelectDeviceInfo = DeviceInfoList.FirstOrDefault();
+                        _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
+                    }
+                }
+                else
+                {
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = "至少保留一个设备", Duration = 2 });
+                }
+            }
+            catch (Exception ex)
+            {
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
+            }
+        }
+
+        /// <summary>
+        /// 选择CSV存储路径
+        /// </summary>
+        void ExecuteSelectSaveImagePathCommand()
+        {
+            if (SelectDeviceInfo == null)
+            {
+                return;
+            }
+            using (System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog())
+            {
+                // Optional: set the initial directory
+                //dialog.SelectedPath = @"C:\";
+
+                // Show the folder browser dialog
+                System.Windows.Forms.DialogResult result = dialog.ShowDialog();
+
+                if (result == System.Windows.Forms.DialogResult.OK)
+                {
+                    SelectDeviceInfo.SaveCsvPath = dialog.SelectedPath;
+                }
+            }
+        }
         #endregion
         #endregion
     }
     }
 }
 }

+ 273 - 67
TeamAAS-VM/Views/Home/ShowVisionRender.xaml.cs

@@ -6,6 +6,7 @@ using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Drawing;
 using System.Drawing;
 using System.IO;
 using System.IO;
+using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using System.Windows;
 using System.Windows;
 using System.Windows.Controls;
 using System.Windows.Controls;
@@ -35,6 +36,10 @@ namespace TeamAAS_VP.Views.Home
         private readonly ISystemDatabaseService _systemDatabaseService;
         private readonly ISystemDatabaseService _systemDatabaseService;
         private readonly IProductService _productService;
         private readonly IProductService _productService;
 
 
+        // ======================= 【新增】保存任务控制:防闪退/防资源泄露 =======================
+        private CancellationTokenSource _saveImageCts = new CancellationTokenSource();
+        private readonly SemaphoreSlim _saveSemaphore = new SemaphoreSlim(2, 2);
+
         public ShowVisionRender()
         public ShowVisionRender()
         {
         {
             InitializeComponent();
             InitializeComponent();
@@ -51,6 +56,19 @@ namespace TeamAAS_VP.Views.Home
             viewModel.UpdateLayout += ViewModel_UpdateLayout;
             viewModel.UpdateLayout += ViewModel_UpdateLayout;
             _eventAggregator.GetEvent<RenderUpdateNotification>().Subscribe(UpdateRenderModuleSource);
             _eventAggregator.GetEvent<RenderUpdateNotification>().Subscribe(UpdateRenderModuleSource);
             _eventAggregator.GetEvent<ProductChangedNotification>().Subscribe(ProductChanged);
             _eventAggregator.GetEvent<ProductChangedNotification>().Subscribe(ProductChanged);
+
+            // 【可选】控件卸载时取消所有保存任务,避免页面关闭后仍在截图/保存导致闪退
+            this.Unloaded += ShowVisionRender_Unloaded;
+        }
+
+        private void ShowVisionRender_Unloaded(object sender, RoutedEventArgs e)
+        {
+            try
+            {
+                _saveImageCts.Cancel();
+                _saveImageCts.Dispose();
+            }
+            catch { }
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -77,25 +95,9 @@ namespace TeamAAS_VP.Views.Home
                             if (render.Record != null)
                             if (render.Record != null)
                                 disp.Record = render.Record;
                                 disp.Record = render.Record;
 
 
-                            if (render.IsSaveImage)
-                            {
-                                // 注意:CreateContentBitmap 可能比较耗时,但你这里已经在 UI 线程里调用了;
-                                // 如果卡顿明显,建议把 bitmap 生成放到后台线程(需谨慎处理线程访问)
-                                App.Current.Dispatcher.BeginInvoke(new Action(() =>
-                                {
-                                    var bmp = (Bitmap)disp.CreateContentBitmap(Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
-
-                                    SaveImage(
-                                        render.SaveImageModel,
-                                        render.SaveImagePathModel,
-                                        render.SavePath,
-                                        render.Image,
-                                        bmp,
-                                        render.Result,
-                                        render.IsCompress
-                                    );
-                                }));
-                            }
+                            // ======================= 【关键优化】保存图像走安全入口 =======================
+                            RequestSaveImage(render, disp);
+
                             break;
                             break;
                         }
                         }
                     }
                     }
@@ -108,6 +110,15 @@ namespace TeamAAS_VP.Views.Home
         /// </summary>
         /// </summary>
         private async void ViewModel_UpdateLayout(System.Collections.ObjectModel.ObservableCollection<Models.ShowRender> obj)
         private async void ViewModel_UpdateLayout(System.Collections.ObjectModel.ObservableCollection<Models.ShowRender> obj)
         {
         {
+            // ======================= 【关键优化】布局刷新前先取消旧保存任务 =======================
+            try
+            {
+                _saveImageCts.Cancel();
+                _saveImageCts.Dispose();
+            }
+            catch { }
+            _saveImageCts = new CancellationTokenSource();
+
             System.Windows.Media.FontFamily font = Application.Current.Resources["DefaultFont"] as System.Windows.Media.FontFamily;
             System.Windows.Media.FontFamily font = Application.Current.Resources["DefaultFont"] as System.Windows.Media.FontFamily;
 
 
             // 1) 清理旧控件
             // 1) 清理旧控件
@@ -132,15 +143,7 @@ namespace TeamAAS_VP.Views.Home
             // 3) 限制最大 16(防止越界)
             // 3) 限制最大 16(防止越界)
             int count = Math.Min(obj.Count, 16);
             int count = Math.Min(obj.Count, 16);
 
 
-            // 4) 计算行列(1~16自动铺满:尽量接近正方形;最大 4*4)
-            //    1  -> 1*1
-            //    2  -> 1*2
-            //    3  -> 2*2
-            //    4  -> 2*2
-            //    5~6 -> 2*3
-            //    7~9 -> 3*3(9满)
-            //    10~12 -> 3*4(12满)
-            //    13~16 -> 4*4(16满)
+            // 4) 计算行列(最大 4*4)
             GetGridSize(count, out int rows, out int cols);
             GetGridSize(count, out int rows, out int cols);
 
 
             // 5) 创建主Grid的行列
             // 5) 创建主Grid的行列
@@ -158,13 +161,39 @@ namespace TeamAAS_VP.Views.Home
                 var sr = obj[i];
                 var sr = obj[i];
 
 
                 // (1) 创建显示控件(WindowsFormsHost + CogRecordDisplay)
                 // (1) 创建显示控件(WindowsFormsHost + CogRecordDisplay)
-                var host = new WindowsFormsHost()
+                var disp = new CogRecordDisplay()
                 {
                 {
                     Tag = sr.ProceductName,
                     Tag = sr.ProceductName,
-                    Child = new CogRecordDisplay()
+                };
+
+                disp.HandleCreated += (s, e) =>
+                {
+                    try
                     {
                     {
-                        Tag = sr.ProceductName,
+                        ConfigureCogDisplay(disp); // 句柄创建后再配置,最稳
+                        // 绑定 WinForms 双击事件
+                        //disp.MouseDoubleClick += (r, w) =>
+                        //{
+                        //    try
+                        //    {
+                        //        OnDisplayDoubleClick(disp);
+                        //    }
+                        //    catch (Exception ex)
+                        //    {
+                        //        LogHelper.WriteLogError("双击预览弹窗出错", ex);
+                        //    }
+                        //};
                     }
                     }
+                    catch (Exception ex)
+                    {
+                        LogHelper.WriteLogError("ConfigureCogDisplay 失败", ex);
+                    }
+                };
+
+                var host = new WindowsFormsHost()
+                {
+                    Tag = sr.ProceductName,
+                    Child = disp
                 };
                 };
                 vmRenders.Add(sr.Id, host);
                 vmRenders.Add(sr.Id, host);
 
 
@@ -209,7 +238,6 @@ namespace TeamAAS_VP.Views.Home
         /// </summary>
         /// </summary>
         private void GetGridSize(int count, out int rows, out int cols)
         private void GetGridSize(int count, out int rows, out int cols)
         {
         {
-            // 默认值
             rows = 1;
             rows = 1;
             cols = 1;
             cols = 1;
 
 
@@ -220,7 +248,6 @@ namespace TeamAAS_VP.Views.Home
             if (count <= 9) { rows = 3; cols = 3; return; }
             if (count <= 9) { rows = 3; cols = 3; return; }
             if (count <= 12) { rows = 3; cols = 4; return; }
             if (count <= 12) { rows = 3; cols = 4; return; }
 
 
-            // 13~16
             rows = 4;
             rows = 4;
             cols = 4;
             cols = 4;
         }
         }
@@ -233,19 +260,97 @@ namespace TeamAAS_VP.Views.Home
             disp.HorizontalScrollBar = false;
             disp.HorizontalScrollBar = false;
             disp.VerticalScrollBar = false;
             disp.VerticalScrollBar = false;
             disp.AutoFit = true;
             disp.AutoFit = true;
+            disp.AutoFitWithGraphics = true;
             disp.BackColor = System.Drawing.SystemColors.ActiveCaption;
             disp.BackColor = System.Drawing.SystemColors.ActiveCaption;
         }
         }
 
 
+        // ======================= 【新增】安全保存入口:解决闪退 =======================
+        private void RequestSaveImage(ShowRender render, CogRecordDisplay disp)
+        {
+            if (render == null) return;
+            if (disp == null) return;
+            if (!render.IsSaveImage) return;
+
+            // Original 模式不需要 CreateContentBitmap(你的 SaveImage 里 Original 只写 ICogImage)
+            bool needRecordedBitmap =
+                render.SaveImageModel == ProcedureSaveImageModel.Recorded ||
+                render.SaveImageModel == ProcedureSaveImageModel.OriginalAndRecorded;
+            _saveImageCts = new CancellationTokenSource();
+            var token = _saveImageCts.Token;
+
+            // 必须在控件的 UI 线程上执行 CreateContentBitmap
+            disp.BeginInvoke(new Action(() =>
+            {
+                Bitmap clonedBitmap = null;
+
+                try
+                {
+                    token.ThrowIfCancellationRequested();
+
+                    if (needRecordedBitmap)
+                    {
+                        // UI线程创建
+                        Bitmap uiBitmap = (Bitmap)disp.CreateContentBitmap(
+                            Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
+
+                        // 立刻 Clone,后台线程只用 Clone(防止控件刷新/释放导致崩溃)
+                        clonedBitmap = (Bitmap)uiBitmap.Clone();
+
+                        // UI线程立刻释放
+                        uiBitmap.Dispose();
+                    }
+
+                    // 后台保存(限并发,防止GDI/内存瞬时飙升)
+                    Task.Run(async () =>
+                    {
+                        await _saveSemaphore.WaitAsync(token);
+                        try
+                        {
+                            token.ThrowIfCancellationRequested();
+
+                            SaveImage(
+                                render.SaveImageModel,
+                                render.SaveImagePathModel,
+                                render.SavePath,
+                                render.Image,
+                                clonedBitmap,
+                                render.Result,
+                                render.IsCompress,
+                                render.ImageFileName
+                            );
+                        }
+                        catch (OperationCanceledException)
+                        {
+                            // 取消属于正常情况,不记录
+                        }
+                        catch (Exception ex)
+                        {
+                            LogHelper.WriteLogError("后台保存图像任务出错!", ex);
+                        }
+                        finally
+                        {
+                            // 确保释放 Clone 的 Bitmap,避免 GDI 泄漏导致闪退
+                            //try { clonedBitmap?.Dispose(); } catch { }
+                            _saveSemaphore.Release();
+                        }
+                    }, token);
+                }
+                catch (OperationCanceledException)
+                {
+                    //try { clonedBitmap?.Dispose(); } catch { }
+                }
+                catch (Exception ex)
+                {
+                    //try { clonedBitmap?.Dispose(); } catch { }
+                    LogHelper.WriteLogError("RequestSaveImage(UI截图阶段) 出错!", ex);
+                }
+            }));
+        }
+
         /// <summary>
         /// <summary>
-        /// 保存图像(保持你原有逻辑不变)
+        /// 保存图像(保持你原有逻辑不变,补充 Dispose 兜底,防止压缩分支不释放导致闪退)
         /// </summary>
         /// </summary>
-        private void SaveImage(ProcedureSaveImageModel saveImageModel,
-                               ProcedureSaveImagePathModel saveImagePathModel,
-                               string path,
-                               ICogImage image,
-                               Bitmap reimage,
-                               bool result,
-                               bool isCompress)
+        private void SaveImage(ProcedureSaveImageModel saveImageModel, ProcedureSaveImagePathModel saveImagePathModel, string path, ICogImage image, Bitmap reimage, bool result, bool isCompress,string imageFileName)
         {
         {
             if (string.IsNullOrEmpty(path) || string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path))
             if (string.IsNullOrEmpty(path) || string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path))
             {
             {
@@ -259,28 +364,34 @@ namespace TeamAAS_VP.Views.Home
                 try
                 try
                 {
                 {
                     DateTime now = DateTime.Now;
                     DateTime now = DateTime.Now;
+                    //图片名
+                    string imgName = now.ToString("yyyy-MM-dd HH_mm_ss");
+                    if (!string.IsNullOrEmpty(imageFileName))
+                    {
+                        imgName = imageFileName;
+                    }
 
 
                     if (saveImageModel == ProcedureSaveImageModel.Original)
                     if (saveImageModel == ProcedureSaveImageModel.Original)
                     {
                     {
-                        string Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                        string Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
 
 
                         if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
                         if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
                         {
                         {
                             Originalpath = result
                             Originalpath = result
-                                ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp"
-                                : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp"
+                                : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
                         }
                         }
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
                         {
                         {
                             if (result)
                             if (result)
-                                Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
                             else
                             else
                                 return;
                                 return;
                         }
                         }
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
                         {
                         {
                             if (!result)
                             if (!result)
-                                Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
                             else
                             else
                                 return;
                                 return;
                         }
                         }
@@ -297,7 +408,7 @@ namespace TeamAAS_VP.Views.Home
                                 productSN = productSN.Replace(c, '_');
                                 productSN = productSN.Replace(c, '_');
 
 
                             string resultStr = result ? "OK" : "NG";
                             string resultStr = result ? "OK" : "NG";
-                            Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
+                            Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
                         }
                         }
 
 
                         if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
                         if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
@@ -312,25 +423,25 @@ namespace TeamAAS_VP.Views.Home
                     }
                     }
                     else if (saveImageModel == ProcedureSaveImageModel.Recorded)
                     else if (saveImageModel == ProcedureSaveImageModel.Recorded)
                     {
                     {
-                        string Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                        string Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
 
 
                         if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
                         if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
                         {
                         {
                             Recordedpath = result
                             Recordedpath = result
-                                ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp"
-                                : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp"
+                                : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
                         }
                         }
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
                         {
                         {
                             if (result)
                             if (result)
-                                Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
                             else
                             else
                                 return;
                                 return;
                         }
                         }
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
                         {
                         {
                             if (!result)
                             if (!result)
-                                Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
                             else
                             else
                                 return;
                                 return;
                         }
                         }
@@ -345,7 +456,7 @@ namespace TeamAAS_VP.Views.Home
                                 productSN = productSN.Replace(c, '_');
                                 productSN = productSN.Replace(c, '_');
 
 
                             string resultStr = result ? "OK" : "NG";
                             string resultStr = result ? "OK" : "NG";
-                            Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
+                            Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
                         }
                         }
 
 
                         if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
                         if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
@@ -358,33 +469,32 @@ namespace TeamAAS_VP.Views.Home
                         else
                         else
                         {
                         {
                             reimage.Save(Recordedpath);
                             reimage.Save(Recordedpath);
-                            reimage.Dispose();
                         }
                         }
                     }
                     }
                     else if (saveImageModel == ProcedureSaveImageModel.OriginalAndRecorded)
                     else if (saveImageModel == ProcedureSaveImageModel.OriginalAndRecorded)
                     {
                     {
-                        string Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
-                        string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                        string Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
+                        string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
 
 
                         if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
                         if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
                         {
                         {
                             if (result)
                             if (result)
                             {
                             {
-                                Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
-                                Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
+                                Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
                             }
                             }
                             else
                             else
                             {
                             {
-                                Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
-                                Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
+                                Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
                             }
                             }
                         }
                         }
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
                         else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
                         {
                         {
                             if (result)
                             if (result)
                             {
                             {
-                                Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
-                                Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
+                                Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
                             }
                             }
                             else
                             else
                             {
                             {
@@ -395,8 +505,8 @@ namespace TeamAAS_VP.Views.Home
                         {
                         {
                             if (!result)
                             if (!result)
                             {
                             {
-                                Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
-                                Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
+                                Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
+                                Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
                             }
                             }
                             else
                             else
                             {
                             {
@@ -414,8 +524,8 @@ namespace TeamAAS_VP.Views.Home
                                 productSN = productSN.Replace(c, '_');
                                 productSN = productSN.Replace(c, '_');
 
 
                             string resultStr = result ? "OK" : "NG";
                             string resultStr = result ? "OK" : "NG";
-                            Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
-                            Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
+                            Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
+                            Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
                         }
                         }
 
 
                         if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
                         if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
@@ -438,7 +548,6 @@ namespace TeamAAS_VP.Views.Home
                         else
                         else
                         {
                         {
                             reimage.Save(Recordedpath);
                             reimage.Save(Recordedpath);
-                            reimage.Dispose();
                         }
                         }
                     }
                     }
                 }
                 }
@@ -446,6 +555,11 @@ namespace TeamAAS_VP.Views.Home
                 {
                 {
                     LogHelper.WriteLogError("保存流程运行结果的图片时出错!", ex);
                     LogHelper.WriteLogError("保存流程运行结果的图片时出错!", ex);
                 }
                 }
+                finally
+                {
+                    // ======================= 【关键修复】无论是否压缩都释放Bitmap =======================
+                    try { reimage?.Dispose(); } catch { }
+                }
             });
             });
         }
         }
 
 
@@ -478,5 +592,97 @@ namespace TeamAAS_VP.Views.Home
                 }
                 }
             }));
             }));
         }
         }
+        private void OnDisplayDoubleClick(CogRecordDisplay disp)
+        {
+            if (disp == null) return;
+
+            // 必须在 WinForms/ActiveX 线程截图
+            disp.BeginInvoke(new Action(() =>
+            {
+                Bitmap bmp = null;
+
+                try
+                {
+                    if (disp.IsDisposed || !disp.IsHandleCreated)
+                        return;
+
+                    // 优先使用显示内容截图(带图形/record叠加)
+                    try
+                    {
+                        var uiBmp = (Bitmap)disp.CreateContentBitmap(
+                            Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
+
+                        bmp = (Bitmap)uiBmp.Clone();
+                        uiBmp.Dispose();
+                    }
+                    catch
+                    {
+                        // 如果 ActiveX 状态不允许截图,退化:尝试从 Image 转 Bitmap
+                        bmp = TryConvertCogImageToBitmap(disp.Image);
+                    }
+
+                    if (bmp == null) return;
+
+                    // 回到 WPF UI 线程弹窗
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        //var win = new ImagePreviewWindow(bmp, $"预览:{disp.Tag ?? "Display"}");
+                        //win.Owner = Window.GetWindow(this); // 让弹窗归属当前窗口
+                        //win.Show();
+                    }));
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("OnDisplayDoubleClick 截图/弹窗出错", ex);
+                }
+                finally
+                {
+                    // 这里 bmp 不要 Dispose,因为传给窗口了
+                    // 窗口关闭时会释放
+                }
+            }));
+        }
+
+        /// <summary>
+        /// 将 VisionPro 的 ICogImage 尝试转换成 Bitmap(作为 CreateContentBitmap 失败时的兜底)
+        /// </summary>
+        private Bitmap TryConvertCogImageToBitmap(ICogImage cogImage)
+        {
+            try
+            {
+                if (cogImage == null) return null;
+
+                // VisionPro 常用转换:CogImage8Grey / CogImage24PlanarColor / CogImage24PackedColor 等
+                // 这里给通用兜底:用 CogImageFileBMP 落地到内存流,再读回 Bitmap
+                using (var ms = new MemoryStream())
+                {
+                    // 需要引用 Cognex.VisionPro.ImageFile
+                    using (var bmpFile = new CogImageFileBMP())
+                    {
+                        // CogImageFileBMP 只能写文件路径,不直接写流
+                        // 所以用临时文件方式最稳(如你不想落盘,可以另写转换器)
+                        var tmp = Path.Combine(Path.GetTempPath(), $"vp_preview_{Guid.NewGuid():N}.bmp");
+                        try
+                        {
+                            bmpFile.Open(tmp, CogImageFileModeConstants.Write);
+                            bmpFile.Append(cogImage);
+                            bmpFile.Close();
+
+                            var bitmap = (Bitmap)Bitmap.FromFile(tmp);
+                            return (Bitmap)bitmap.Clone();
+                        }
+                        finally
+                        {
+                            try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
+                        }
+                    }
+                }
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
     }
     }
 }
 }

+ 2 - 2
TeamAAS-VM/Views/HomeView.xaml

@@ -38,8 +38,8 @@
 
 
         <Grid Grid.Row="0">
         <Grid Grid.Row="0">
             <Grid.RowDefinitions>
             <Grid.RowDefinitions>
-                <RowDefinition Height="*" />
-                <RowDefinition Height="*" />
+                <RowDefinition Height="2*" />
+                <RowDefinition Height="1*" />
             </Grid.RowDefinitions>
             </Grid.RowDefinitions>
             <!--图像-->
             <!--图像-->
             <local:ShowVisionRender x:Name="visionRender"
             <local:ShowVisionRender x:Name="visionRender"

+ 47 - 10
TeamAAS-VM/Views/Product/ProcedureParams.xaml

@@ -20,7 +20,7 @@
              prism:ViewModelLocator.AutoWireViewModel="True"
              prism:ViewModelLocator.AutoWireViewModel="True"
              mc:Ignorable="d"
              mc:Ignorable="d"
              d:DataContext="{d:DesignInstance Type=vm:ProcedureParamsViewModel}"
              d:DataContext="{d:DesignInstance Type=vm:ProcedureParamsViewModel}"
-             d:Height="600"
+             d:Height="1080"
              d:Width="1024"
              d:Width="1024"
              d:Background="White"
              d:Background="White"
              FontFamily="{DynamicResource DefaultFont}">
              FontFamily="{DynamicResource DefaultFont}">
@@ -30,7 +30,7 @@
         </b:EventTrigger>
         </b:EventTrigger>
     </b:Interaction.Triggers>
     </b:Interaction.Triggers>
     <UserControl.Resources>
     <UserControl.Resources>
-
+        <valueConverter:ImageFileNameFormatConverter x:Key="ImageFileNameFormatConverter" />
     </UserControl.Resources>
     </UserControl.Resources>
     <Grid>
     <Grid>
         <Grid.RowDefinitions>
         <Grid.RowDefinitions>
@@ -107,7 +107,8 @@
             </Expander>
             </Expander>
             <ScrollViewer Grid.Column="1"
             <ScrollViewer Grid.Column="1"
                           IsEnabled="{Binding IsAllowEdit}">
                           IsEnabled="{Binding IsAllowEdit}">
-                <Grid Grid.Column="1"
+                <Grid x:Name="grid"
+                      Grid.Column="1"
                       Margin="10"
                       Margin="10"
                       IsEnabled="{Binding IsAllowEdit}"
                       IsEnabled="{Binding IsAllowEdit}"
                       HorizontalAlignment="Center"
                       HorizontalAlignment="Center"
@@ -132,6 +133,8 @@
                         <RowDefinition Height="auto" />
                         <RowDefinition Height="auto" />
                         <RowDefinition Height="auto" />
                         <RowDefinition Height="auto" />
                         <RowDefinition Height="auto" />
                         <RowDefinition Height="auto" />
+                        <RowDefinition Height="auto" />
+                        <RowDefinition Height="auto" />
                     </Grid.RowDefinitions>
                     </Grid.RowDefinitions>
                     <Grid.ColumnDefinitions>
                     <Grid.ColumnDefinitions>
                         <ColumnDefinition Width="auto" />
                         <ColumnDefinition Width="auto" />
@@ -428,8 +431,42 @@
                               Visibility="{Binding ElementName=chbSaveImage,Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"
                               Visibility="{Binding ElementName=chbSaveImage,Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"
                               IsChecked="{Binding SelectProcedure.IsCompress,Mode=TwoWay}"
                               IsChecked="{Binding SelectProcedure.IsCompress,Mode=TwoWay}"
                               Style="{StaticResource MaterialDesignLightCheckBox}" />
                               Style="{StaticResource MaterialDesignLightCheckBox}" />
+                    <!--图片名称格式-->
+                    <TextBlock Grid.Row="14"
+                               Grid.Column="0"
+                               Visibility="{Binding ElementName=chbSaveImage,Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"
+                               Text="图片名称格式:" />
+                    <TextBox Grid.Row="14"
+                             Grid.Column="1"
+                             HorizontalAlignment="Stretch"
+                             Visibility="{Binding ElementName=chbSaveImage,Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"
+                             Text="{Binding SelectProcedure.ImageFileNameFormat,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
+                    </TextBox>
+                    <!--示例-->
+                    <StackPanel Grid.Row="15"
+                                Grid.Column="0"
+                                Grid.ColumnSpan="2"
+                                Orientation="Vertical"
+                                Visibility="{Binding ElementName=chbSaveImage,Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}">
+                        <TextBlock Text="示例:{ProductSN}_Daisy_KB Screw _01 _{CameraName}-Locate_{ShotCount}_WhiteRingLight_{Result}_{DateTime:yyyy-MM-dd_HH-mm-ss}"
+                                   Foreground="LightGray"
+                                   FontSize="10"
+                                   TextTrimming="CharacterEllipsis"
+                                   TextWrapping="Wrap"
+                                   Width="{Binding Width, ElementName=grid}" />
+                        <TextBlock Text="转换后的名称:"
+                                   Foreground="Gray"
+                                   FontSize="10" />
+                        <TextBlock Text="{Binding SelectProcedure.ImageFileNameFormat,Converter={StaticResource ImageFileNameFormatConverter},Mode=TwoWay}"
+                                   Foreground="Gray"
+                                   FontSize="10"
+                                   TextTrimming="CharacterEllipsis"
+                                   TextWrapping="Wrap"
+                                   Width="{Binding Width, ElementName=grid}"  />
+                    </StackPanel>
+
                     <!--自定义参数-->
                     <!--自定义参数-->
-                    <GroupBox Grid.Row="14"
+                    <GroupBox Grid.Row="16"
                               Grid.Column="0"
                               Grid.Column="0"
                               Grid.ColumnSpan="2"
                               Grid.ColumnSpan="2"
                               HorizontalAlignment="Stretch"
                               HorizontalAlignment="Stretch"
@@ -440,12 +477,12 @@
                             <StackPanel DockPanel.Dock="Top"
                             <StackPanel DockPanel.Dock="Top"
                                         Orientation="Horizontal">
                                         Orientation="Horizontal">
                                 <Button Content="{materialDesign:PackIcon Kind=AddCircle}"
                                 <Button Content="{materialDesign:PackIcon Kind=AddCircle}"
-                                        Style="{StaticResource MahApps.Styles.Button.Flat}" 
-                                        Command="{Binding AddUserDefineParameterCommand}"/>
+                                        Style="{StaticResource MahApps.Styles.Button.Flat}"
+                                        Command="{Binding AddUserDefineParameterCommand}" />
                                 <Button Content="{materialDesign:PackIcon Kind=RemoveCircle}"
                                 <Button Content="{materialDesign:PackIcon Kind=RemoveCircle}"
                                         Style="{StaticResource MahApps.Styles.Button.Flat}"
                                         Style="{StaticResource MahApps.Styles.Button.Flat}"
-                                        Margin="5,0" 
-                                        Command="{Binding RemoveUserDefineParameterCommand}"/>
+                                        Margin="5,0"
+                                        Command="{Binding RemoveUserDefineParameterCommand}" />
                             </StackPanel>
                             </StackPanel>
                             <DataGrid HorizontalAlignment="Stretch"
                             <DataGrid HorizontalAlignment="Stretch"
                                       VerticalAlignment="Stretch"
                                       VerticalAlignment="Stretch"
@@ -499,10 +536,10 @@
                             </DataGrid>
                             </DataGrid>
                         </DockPanel>
                         </DockPanel>
                     </GroupBox>
                     </GroupBox>
-                    <TextBlock Grid.Row="15"
+                    <TextBlock Grid.Row="17"
                                Grid.Column="0"
                                Grid.Column="0"
                                Text="{lex:Loc 重写视觉处理逻辑}" />
                                Text="{lex:Loc 重写视觉处理逻辑}" />
-                    <Button Grid.Row="15"
+                    <Button Grid.Row="17"
                             Grid.Column="1"
                             Grid.Column="1"
                             Margin="0,2,0,0"
                             Margin="0,2,0,0"
                             Command="{Binding OverrideVisionTaskCommand}">
                             Command="{Binding OverrideVisionTaskCommand}">

+ 398 - 225
TeamAAS-VM/Views/SettingView.xaml

@@ -223,242 +223,365 @@
                                                  Kind="RouterNetwork" />
                                                  Kind="RouterNetwork" />
                         <TextBlock Style="{StaticResource TabHeaderTextBlockStyle}"
                         <TextBlock Style="{StaticResource TabHeaderTextBlockStyle}"
                                    FontSize="{DynamicResource Font.Size.Body2}"
                                    FontSize="{DynamicResource Font.Size.Body2}"
-                                   Text="设备信息"
+                                   Text="{lex:Loc 设备信息}"
                                    HorizontalAlignment="Stretch" />
                                    HorizontalAlignment="Stretch" />
                     </StackPanel>
                     </StackPanel>
                 </TabItem.Header>
                 </TabItem.Header>
 
 
-                <Grid>
+                <Grid Margin="16">
                     <Grid.RowDefinitions>
                     <Grid.RowDefinitions>
-                        <RowDefinition Height="auto"/>
-                        <RowDefinition Height="auto"/>
+                        <RowDefinition Height="50" />
+                        <RowDefinition Height="*" />
                     </Grid.RowDefinitions>
                     </Grid.RowDefinitions>
-                    <Grid Margin="16">
-                        <Grid.RowDefinitions>
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                        </Grid.RowDefinitions>
-                        <Grid.ColumnDefinitions>
-                            <ColumnDefinition Width="auto" />
-                            <ColumnDefinition Width="*" />
-                        </Grid.ColumnDefinitions>
-
-
-                        <TextBlock Grid.Row="0"
-         Grid.Column="0"
-         Text="Url:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-                        <TextBox Grid.Row="0"
-       Grid.Column="1"
-       Text="{Binding DeviceInfo.MesUrl, Mode=TwoWay}"
-       Margin="6" />
-
-                        <TextBlock Grid.Row="1"
-         Grid.Column="0"
-         Text="Line:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-                        <TextBox Grid.Row="1"
-       Grid.Column="1"
-       Text="{Binding DeviceInfo.Line, Mode=TwoWay}"
-       Margin="6" />
-
-                        <TextBlock Grid.Row="2"
-         Grid.Column="0"
-         Text="Station:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-                        <TextBox Grid.Row="2"
-       Grid.Column="1"
-       Text="{Binding DeviceInfo.Station, Mode=TwoWay}"
-       Margin="6" />
+                    <Grid.ColumnDefinitions>
+                        <ColumnDefinition Width="auto" />
+                        <ColumnDefinition Width="*" />
+                    </Grid.ColumnDefinitions>
 
 
-                        <TextBlock Grid.Row="3"
-         Grid.Column="0"
-         Text="FixtureId:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-                        <TextBox Grid.Row="3"
-       Grid.Column="1"
-       Text="{Binding DeviceInfo.FixtureId, Mode=TwoWay}"
-       Margin="6" />
+                    <!--增删改查按钮-->
+                    <StackPanel Grid.ColumnSpan="2"
+                                IsEnabled="{Binding IsAllowEdit}"
+                                Orientation="Horizontal">
+                        <Button Style="{StaticResource MaterialDesignFloatingActionMiniLightButton}"
+                                ToolTip="添加设备"
+                                Command="{Binding AddDeviceInfoCommand}">
+                            <materialDesign:PackIcon Kind="Plus" />
+                        </Button>
+                        <Button Style="{StaticResource MaterialDesignFloatingActionMiniDarkButton}"
+                                ToolTip="删除设备"
+                                Margin="20,0"
+                                Command="{Binding RemoveDeviceInfoCommand}">
+                            <materialDesign:PackIcon Kind="DeleteForeverOutline" />
+                        </Button>
+                        <Button Style="{StaticResource MaterialDesignFloatingActionMiniSecondaryDarkButton}"
+                                ToolTip="{lex:Loc 保存}"
+                                Command="{Binding SaveDeviceInfoCommand}">
+                            <materialDesign:PackIcon Kind="ContentSaveCheck" />
+                        </Button>
+                    </StackPanel>
 
 
-                        <TextBlock Grid.Row="4"
-         Grid.Column="0"
-         Text="f(组装站):"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-                        <TextBox Grid.Row="4"
-       Grid.Column="1"
-       Text="{Binding DeviceInfo.F, Mode=TwoWay}"
-       Margin="6" />
+                    <!--设备列表-->
+                    <TreeView Grid.Row="1"
+                              Grid.Column="0"
+                              SelectedItemChanged="TreeView_SelectedItemChanged">
+                        <TreeViewItem Header="设备列表"
+                                      FontSize="{DynamicResource Font.Size.Title4}"
+                                      FontWeight="Bold"
+                                      IsExpanded="True"
+                                      ItemsSource="{Binding DeviceInfoList}">
+                            <TreeViewItem.ItemTemplate>
+                                <HierarchicalDataTemplate>
+                                    <StackPanel Orientation="Vertical">
+                                        <TextBlock FontSize="{DynamicResource Font.Size.Title4}">
+                                            <TextBlock.Text>
+                                                <MultiBinding StringFormat="设备 {0}">
+                                                    <Binding Path="DeviceNo" />
+                                                </MultiBinding>
+                                            </TextBlock.Text>
+                                        </TextBlock>
+                                        <StackPanel Orientation="Horizontal">
+                                            <TextBlock Text="DeviceName: "
+                                                       Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                                                       FontSize="{DynamicResource Font.Size.Body3}" />
+                                            <TextBlock Text="{Binding DeviceName}"
+                                                       Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                                                       FontSize="{DynamicResource Font.Size.Body3}" />
+                                        </StackPanel>
+                                        <StackPanel Orientation="Horizontal">
+                                            <TextBlock Text="Line: "
+                                                       Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                                                       FontSize="{DynamicResource Font.Size.Body3}" />
+                                            <TextBlock Text="{Binding Line}"
+                                                       Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                                                       FontSize="{DynamicResource Font.Size.Body3}" />
+                                        </StackPanel>
+                                        <StackPanel Orientation="Horizontal">
+                                            <TextBlock Text="Station: "
+                                                       Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                                                       FontSize="{DynamicResource Font.Size.Body3}" />
+                                            <TextBlock Text="{Binding Station}"
+                                                       Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                                                       FontSize="{DynamicResource Font.Size.Body3}" />
+                                        </StackPanel>
+                                        <Border Height="2"
+                                                Margin="0"
+                                                BorderThickness="2"
+                                                BorderBrush="Green" />
+                                    </StackPanel>
+                                </HierarchicalDataTemplate>
+                            </TreeViewItem.ItemTemplate>
+                        </TreeViewItem>
+                    </TreeView>
 
 
-                        <TextBlock Grid.Row="5"
-         Grid.Column="0"
-         Text="comp:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-                        <TextBox Grid.Row="5"
-       Grid.Column="1"
-       Text="{Binding DeviceInfo.comp, Mode=TwoWay}"
-       Margin="6" />
+                    <!--参数详情-->
+                    <ScrollViewer Grid.Row="1"
+                                  Grid.Column="1"
+                                  IsEnabled="{Binding IsAllowEdit}"
+                                  Margin="20"
+                                  Visibility="{Binding SelectDeviceInfo,Converter={StaticResource ObjectToVisibilityConverter}}">
+                        <Grid>
+                            <Grid.RowDefinitions>
+                                <RowDefinition Height="auto" />
+                                <RowDefinition Height="auto" />
+                            </Grid.RowDefinitions>
 
 
-                        <TextBlock Grid.Row="6"
-         Grid.Column="0"
-         Text="启用 MES:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-                        <CheckBox Grid.Row="6"
-        Grid.Column="1"
-        IsChecked="{Binding DeviceInfo.EnableMES, Mode=TwoWay}"
-        Margin="6" />
-
-                        <StackPanel Orientation="Horizontal"
-          HorizontalAlignment="Right"
-          Grid.Row="7"
-          Grid.ColumnSpan="2"
-          Margin="6">
-                            <Button Style="{StaticResource MaterialDesignRaisedButton}"
-          Command="{Binding SaveDeviceInfoCommand}">保存</Button>
-                        </StackPanel>
-                    </Grid>
+                            <!--设备信息表单-->
+                            <Grid>
+                                <Grid.RowDefinitions>
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                </Grid.RowDefinitions>
+                                <Grid.ColumnDefinitions>
+                                    <ColumnDefinition Width="auto" />
+                                    <ColumnDefinition Width="*" />
+                                </Grid.ColumnDefinitions>
+
+                                <TextBlock Grid.Row="0"
+                                           Grid.Column="0"
+                                           Text="设备编号:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBlock Grid.Row="0"
+                                           Grid.Column="1"
+                                           Text="{Binding SelectDeviceInfo.DeviceNo}"
+                                           Margin="6,2"
+                                           VerticalAlignment="Center" />
 
 
-                    <!--<Grid Margin="16"
-Grid.Row="1">
-              <Grid.RowDefinitions>
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-                  <RowDefinition Height="Auto" />
-              </Grid.RowDefinitions>
-              <Grid.ColumnDefinitions>
-                  <ColumnDefinition Width="auto" />
-                  <ColumnDefinition Width="*" />
-              </Grid.ColumnDefinitions>
-
-              <TextBlock Grid.Row="0"
-         Grid.Column="0"
-         Text="PROCESS_NAME:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="0"
-       Grid.Column="1"
-       Text="{Binding DataInfo.PROCESS_NAME, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="1"
-         Grid.Column="0"
-         Text="CTQ_LSL(压力下限):"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="1"
-       Grid.Column="1"
-       Text="{Binding DataInfo.CTQ_LSL_Pressure, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="2"
-         Grid.Column="0"
-         Text="CTQ_USL(压力上限):"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="2"
-       Grid.Column="1"
-       Text="{Binding DataInfo.CTQ_USL_Pressure, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="3"
-         Grid.Column="0"
-         Text="SUPPLIER_NAME:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="3"
-       Grid.Column="1"
-       Text="{Binding DataInfo.SUPPLIER_NAME, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="4"
-         Grid.Column="0"
-         Text="COMMODITY_TYPE:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="4"
-       Grid.Column="1"
-       Text="{Binding DataInfo.COMMODITY_TYPE, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="5"
-         Grid.Column="0"
-         Text="REVISION:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="5"
-       Grid.Column="1"
-       Text="{Binding DataInfo.REVISION, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="6"
-         Grid.Column="0"
-         Text="WO#:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="6"
-       Grid.Column="1"
-       Text="{Binding DataInfo.WO, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="7"
-         Grid.Column="0"
-         Text="MFG_LOT#:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="7"
-       Grid.Column="1"
-       Text="{Binding DataInfo.MFG_LOT, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="8"
-         Grid.Column="0"
-         Text="MFG_ASSY_LINE:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="8"
-       Grid.Column="1"
-       Text="{Binding DataInfo.MFG_ASSY_LINE, Mode=TwoWay}"
-       Margin="6" />
-
-              <TextBlock Grid.Row="9"
-         Grid.Column="0"
-         Text="PROCESS_MACHINE_ID:"
-         HorizontalAlignment="Right"
-         VerticalAlignment="Center" />
-              <TextBox Grid.Row="9"
-       Grid.Column="1"
-       Text="{Binding DataInfo.PROCESS_MACHINE_ID, Mode=TwoWay}"
-       Margin="6" />
-
-              <StackPanel Orientation="Horizontal"
-          HorizontalAlignment="Right"
-          Grid.Row="10"
-          Grid.ColumnSpan="2"
-          Margin="6">
-                  <Button Style="{StaticResource MaterialDesignRaisedButton}"
-          Command="{Binding SaveDataInfoCommand}">保存</Button>
-              </StackPanel>
-          </Grid>-->
+                                <TextBlock Grid.Row="1"
+                                           Grid.Column="0"
+                                           Text="设备名称:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="1"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DeviceName, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="2"
+                                           Grid.Column="0"
+                                           Text="设备描述:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="2"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DeviceDesc, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="3"
+                                           Grid.Column="0"
+                                           Text="Url:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="3"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.MesUrl, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="4"
+                                           Grid.Column="0"
+                                           Text="Line:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="4"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.Line, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="5"
+                                           Grid.Column="0"
+                                           Text="Station:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="5"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.Station, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="6"
+                                           Grid.Column="0"
+                                           Text="FixtureId:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="6"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.FixtureId, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="7"
+                                           Grid.Column="0"
+                                           Text="f:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="7"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.F, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="8"
+                                           Grid.Column="0"
+                                           Text="comp:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="8"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.comp, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="9"
+                                           Grid.Column="0"
+                                           Text="启用 MES:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <CheckBox Grid.Row="9"
+                                          Grid.Column="1"
+                                          IsChecked="{Binding SelectDeviceInfo.EnableMES, Mode=TwoWay}"
+                                          Margin="6,2" />
+                                <CheckBox Grid.Row="10"
+                                          Grid.Column="1"
+                                          Content="是否启用两次产品编号"
+                                          IsChecked="{Binding SelectDeviceInfo.EnableDoubleMes, Mode=TwoWay}"
+                                          Margin="6,2" />
+                                <CheckBox Grid.Row="11"
+                                          Grid.Column="1"
+                                          Content="是否保存CSV文件"
+                                          IsChecked="{Binding SelectDeviceInfo.SaveCsv, Mode=TwoWay}"
+                                          Margin="6,2" />
+                                <TextBlock Grid.Row="12"
+                                           Grid.Column="0"
+                                           Text="保存的CSV文件路径:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <DockPanel HorizontalAlignment="Stretch"
+                                           Grid.Row="12"
+                                           Grid.Column="1"
+                                           Margin="6,2">
+                                    <Button DockPanel.Dock="Right"
+                                            HorizontalAlignment="Right"
+                                            ToolTip="{lex:Loc 选择路径}"
+                                            Command="{Binding SelectSaveImagePathCommand}">
+                                        <Button.Content>
+                                            <materialDesign:PackIcon Kind="FolderOpenOutline" />
+                                        </Button.Content>
+                                    </Button>
+                                    <TextBox  Text="{Binding SelectDeviceInfo.SaveCsvPath, Mode=TwoWay}" />
+
+                                </DockPanel>
+                                <!--CTQ 数据信息-->
+                                <TextBlock Grid.Row="13"
+                                           Grid.Column="0"
+                                           Text="PROCESS_NAME:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="13"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DataInfo.PROCESS_NAME, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <!--<TextBlock Grid.Row="14"
+                               Grid.Column="0"
+                               Text="CTQ_LSL(压力下限):"
+                               HorizontalAlignment="Right"
+                               VerticalAlignment="Center" />
+                    <TextBox Grid.Row="14"
+                             Grid.Column="1"
+                             Text="{Binding SelectDeviceInfo.DataInfo.CTQ_LSL_Pressure, Mode=TwoWay}"
+                             Margin="6,2" />
+
+                    <TextBlock Grid.Row="15"
+                               Grid.Column="0"
+                               Text="CTQ_USL(压力上限):"
+                               HorizontalAlignment="Right"
+                               VerticalAlignment="Center" />
+                    <TextBox Grid.Row="15"
+                             Grid.Column="1"
+                             Text="{Binding SelectDeviceInfo.DataInfo.CTQ_USL_Pressure, Mode=TwoWay}"
+                             Margin="6,2" />-->
+
+                                <TextBlock Grid.Row="16"
+                                           Grid.Column="0"
+                                           Text="SUPPLIER_NAME:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="16"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DataInfo.SUPPLIER_NAME, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="17"
+                                           Grid.Column="0"
+                                           Text="COMMODITY_TYPE:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="17"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DataInfo.COMMODITY_TYPE, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="18"
+                                           Grid.Column="0"
+                                           Text="REVISION:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="18"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DataInfo.REVISION, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="19"
+                                           Grid.Column="0"
+                                           Text="MFG_LOT#:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="19"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DataInfo.MFG_LOT, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="20"
+                                           Grid.Column="0"
+                                           Text="MFG_ASSY_LINE:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="20"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DataInfo.MFG_ASSY_LINE, Mode=TwoWay}"
+                                         Margin="6,2" />
+
+                                <TextBlock Grid.Row="21"
+                                           Grid.Column="0"
+                                           Text="PROCESS_MACHINE_ID:"
+                                           HorizontalAlignment="Right"
+                                           VerticalAlignment="Center" />
+                                <TextBox Grid.Row="21"
+                                         Grid.Column="1"
+                                         Text="{Binding SelectDeviceInfo.DataInfo.PROCESS_MACHINE_ID, Mode=TwoWay}"
+                                         Margin="6,2" />
+                            </Grid>
+                        </Grid>
+                    </ScrollViewer>
                 </Grid>
                 </Grid>
             </TabItem>
             </TabItem>
 
 
@@ -2745,6 +2868,7 @@ Grid.Row="1">
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
+                                        <RowDefinition Height="Auto" />
                                     </Grid.RowDefinitions>
                                     </Grid.RowDefinitions>
                                     <TextBlock Text="{lex:Loc 保压时间}"
                                     <TextBlock Text="{lex:Loc 保压时间}"
                                                Grid.Row="0"
                                                Grid.Row="0"
@@ -2782,6 +2906,30 @@ Grid.Row="1">
                                                Grid.Row="2"
                                                Grid.Row="2"
                                                Grid.Column="2"
                                                Grid.Column="2"
                                                HorizontalAlignment="Right" />
                                                HorizontalAlignment="Right" />
+                                    <TextBlock Text="保压上限:"
+                                               Grid.Row="3"
+                                               Grid.Column="0"
+                                               HorizontalAlignment="Right" />
+                                    <TextBox Text="{Binding AssemblyPressureConfig.PressureUpLimit,Mode=TwoWay}"
+                                             Grid.Row="3"
+                                             Grid.Column="1"
+                                             Margin="6,0" />
+                                    <TextBlock Text="kg"
+                                               Grid.Row="3"
+                                               Grid.Column="2"
+                                               HorizontalAlignment="Right" />
+                                    <TextBlock Text="保压下限:"
+                                               Grid.Row="4"
+                                               Grid.Column="0"
+                                               HorizontalAlignment="Right" />
+                                    <TextBox Text="{Binding AssemblyPressureConfig.PressureDownLimit,Mode=TwoWay}"
+                                             Grid.Row="4"
+                                             Grid.Column="1"
+                                             Margin="6,0" />
+                                    <TextBlock Text="kg"
+                                               Grid.Row="4"
+                                               Grid.Column="2"
+                                               HorizontalAlignment="Right" />
                                 </Grid>
                                 </Grid>
                             </GroupBox>
                             </GroupBox>
                             <GroupBox Header="{lex:Loc 后保压配置}"
                             <GroupBox Header="{lex:Loc 后保压配置}"
@@ -2799,6 +2947,7 @@ Grid.Row="1">
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
                                         <RowDefinition Height="Auto" />
+                                        <RowDefinition Height="Auto" />
                                     </Grid.RowDefinitions>
                                     </Grid.RowDefinitions>
                                     <TextBlock Text="{lex:Loc 保压时间}"
                                     <TextBlock Text="{lex:Loc 保压时间}"
                                                Grid.Row="0"
                                                Grid.Row="0"
@@ -2836,6 +2985,30 @@ Grid.Row="1">
                                                Grid.Row="2"
                                                Grid.Row="2"
                                                Grid.Column="2"
                                                Grid.Column="2"
                                                HorizontalAlignment="Right" />
                                                HorizontalAlignment="Right" />
+                                    <TextBlock Text="保压上限:"
+                                               Grid.Row="3"
+                                               Grid.Column="0"
+                                               HorizontalAlignment="Right" />
+                                    <TextBox Text="{Binding DownPressureConfig.PressureUpLimit,Mode=TwoWay}"
+                                             Grid.Row="3"
+                                             Grid.Column="1"
+                                             Margin="6,0" />
+                                    <TextBlock Text="kg"
+                                               Grid.Row="3"
+                                               Grid.Column="2"
+                                               HorizontalAlignment="Right" />
+                                    <TextBlock Text="保压下限:"
+                                               Grid.Row="4"
+                                               Grid.Column="0"
+                                               HorizontalAlignment="Right" />
+                                    <TextBox Text="{Binding DownPressureConfig.PressureDownLimit,Mode=TwoWay}"
+                                             Grid.Row="4"
+                                             Grid.Column="1"
+                                             Margin="6,0" />
+                                    <TextBlock Text="kg"
+                                               Grid.Row="4"
+                                               Grid.Column="2"
+                                               HorizontalAlignment="Right" />
                                 </Grid>
                                 </Grid>
                             </GroupBox>
                             </GroupBox>
                         </StackPanel>
                         </StackPanel>

+ 4 - 0
TeamAAS-VM/Views/SettingView.xaml.cs

@@ -51,6 +51,10 @@ namespace TeamAAS_VP.Views
                 {
                 {
                     viewModel.SelectScrewFeeder = e.NewValue as ScrewFeederInfo;
                     viewModel.SelectScrewFeeder = e.NewValue as ScrewFeederInfo;
                 }
                 }
+                else if (e.NewValue is DeviceInfo)
+                {
+                    viewModel.SelectDeviceInfo = e.NewValue as DeviceInfo;
+                }
             }
             }
             catch (Exception)
             catch (Exception)
             {
             {