浏览代码

多设备配置、MES上传与图片命名功能增强

本次更新实现了以下主要改进:

- 支持多设备信息配置与管理,DeviceInfo/ConfigService/SettingView等全面适配,支持设备增删查改、独立CTQ参数、CSV路径等。
- MES接口与数据上传流程优化,支持双MES验证、服务器时间同步、主SN/工单号自动填充,数据上传参数更灵活。
- CTQ数据结构优化,字段字符串化,便于扩展与CSV存储。
- 视觉图片保存支持自定义文件名模板,新增FileNameTemplate与XAML预览,图片管理更灵活。
- 界面交互优化,设备信息页重构,支持设备树、表单编辑、路径选择等。
- 兼容旧配置文件,增强异常处理,版本号升级为1.2.1.5。
徐孝锋 9 月之前
父节点
当前提交
680cc3fe6d

+ 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);
+
+            // 可以在这里添加更多内置变量
+        }
+    }
+}

+ 359 - 123
TeamAAS-VM/Core/Management.cs

@@ -1131,6 +1131,14 @@ 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 = "";
@@ -1156,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>
@@ -1180,13 +1188,13 @@ 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);
@@ -2359,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"))
                             {
                             {
@@ -2416,55 +2424,154 @@ namespace TeamAAS_VP.Core
                                 //询问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);
+                                        SendTaskMessage($"收到{i}:{stationConfig.DeviceName}过站检查请求(当站是否生产)(当前不需要双MES验证)...", MessageLevel.Debug);
 
 
-                                        LogHelper.WriteLogMes($"询问mes失败");
-                                        SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
+                                        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;
@@ -2482,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 = "";
@@ -2526,6 +2633,9 @@ 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)
                                     {
                                     {
@@ -2547,49 +2657,60 @@ namespace TeamAAS_VP.Core
                                             assypress = "0";
                                             assypress = "0";
                                             resultIndex = 2;
                                             resultIndex = 2;
                                         }
                                         }
+                                        data.Add("gap", gap);
+                                        data.Add("assy_pressure", assypress);
                                         SendTaskMessage($"gap:{gap},组装压力:{assypress}", MessageLevel.Info);
                                         SendTaskMessage($"gap:{gap},组装压力:{assypress}", MessageLevel.Info);
-                                        try
+                                        #region 数据
+                                        bool assyPresRes;
+                                        if (currentPressure[0] >= p1.PressureDownLimit && currentPressure[0] <= p1.PressureUpLimit)
                                         {
                                         {
-                                            #region 数据
-                                            var cdata = _configService.GetCTQDataInfo();//获取ctq数据参数
-                                            bool assyPresRes;
-                                            if (currentPressure[0] >= p1.PressureDownLimit && currentPressure[0] <= p1.PressureUpLimit)
-                                            {
-                                                assyPresRes = true;
-                                            }
-                                            else assyPresRes = false;
-                                            DFC.Clear();
-                                            DFC.Add(new DataFormCtq
-                                            {
-                                                PPID = code,
-                                                PROCESS_NAME = cdata.PROCESS_NAME,
-                                                PROCESS_START_TIME = StartCtqTime[i].ToString(),
-                                                CTQ_NAME = "Assy_Pressure",
-                                                CTQ_VALUE = double.Parse(assypress),
-                                                CTQ_LSL = p1.PressureDownLimit,
-                                                CTQ_USL = p1.PressureUpLimit,
-                                                PROCESS_END_TIME = DateTime.Now.ToString(),
-                                                SUPPLIER_NAME = cdata.SUPPLIER_NAME,
-                                                COMMODITY_TYPE = cdata.COMMODITY_TYPE,
-                                                REVISION = cdata.REVISION,
-                                                WO = cdata.WO,
-                                                MFG_LOT = cdata.MFG_LOT,
-                                                MFG_ASSY_LINE = cdata.MFG_ASSY_LINE,
-                                                PROCESS_OUTCOME = assyPresRes ? "PASS" : "FAIL",
-                                                PROCESS_MACHINE_ID = cdata.PROCESS_MACHINE_ID,
-                                                CTQ_UNIT_OF_MEASURE = "kg",
-                                                ERROR_MESSAGE = assyPresRes ? "" : "Assy_Pressure OOS"
-                                            });
-                                            foreach (var item in DFC)
-                                            {
-                                                FileHelper.WriteDataToCSV(item);
-                                            }
-                                            #endregion
+                                            assyPresRes = true;
                                         }
                                         }
-                                        catch (Exception ex)
+                                        else assyPresRes = false;
+                                        DFC.Clear();
+                                        DFC.Add(new DataFormCtq
                                         {
                                         {
-                                            SendTaskMessage("CTQ数据存储时出错" + ex.Message, MessageLevel.Error);
-                                        }
+                                            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)
                                     {
                                     {
@@ -2611,52 +2732,63 @@ namespace TeamAAS_VP.Core
                                             resultIndex = 2;
                                             resultIndex = 2;
                                         }
                                         }
                                         presstime = p2.PressureTime.ToString();
                                         presstime = p2.PressureTime.ToString();
+                                        data.Add("pressure", press);
+                                        data.Add("pressure_time", presstime);
                                         SendTaskMessage($"保压压力:{press},保压时间:{presstime}", MessageLevel.Info);
                                         SendTaskMessage($"保压压力:{press},保压时间:{presstime}", MessageLevel.Info);
-                                        try
+                                        #region 数据
+                                        bool presRes;
+                                        if (currentPressure[1] >= p2.PressureDownLimit && currentPressure[1] <= p2.PressureUpLimit)
                                         {
                                         {
-                                            #region 数据
-                                            var cdata = _configService.GetCTQDataInfo();//获取ctq数据参数
-                                            bool presRes;
-                                            if (currentPressure[1] >= p2.PressureDownLimit && currentPressure[1] <= p2.PressureUpLimit)
-                                            {
-                                                presRes = true;
-                                            }
-                                            else presRes = false;
-                                            DFC.Clear();
-                                            DFC.Add(new DataFormCtq
-                                            {
-                                                PPID = code,
-                                                PROCESS_NAME = cdata.PROCESS_NAME,
-                                                PROCESS_START_TIME = StartCtqTime[i].ToString(),
-                                                CTQ_NAME = "Pressure",
-                                                CTQ_VALUE = double.Parse(press),
-                                                CTQ_LSL = p2.PressureDownLimit,
-                                                CTQ_USL = p2.PressureUpLimit,
-                                                PROCESS_END_TIME = DateTime.Now.ToString(),
-                                                SUPPLIER_NAME = cdata.SUPPLIER_NAME,
-                                                COMMODITY_TYPE = cdata.COMMODITY_TYPE,
-                                                REVISION = cdata.REVISION,
-                                                WO = cdata.WO,
-                                                MFG_LOT = cdata.MFG_LOT,
-                                                MFG_ASSY_LINE = cdata.MFG_ASSY_LINE,
-                                                PROCESS_OUTCOME = presRes ? "PASS" : "FAIL",
-                                                PROCESS_MACHINE_ID = cdata.PROCESS_MACHINE_ID,
-                                                CTQ_UNIT_OF_MEASURE = "kg",
-                                                ERROR_MESSAGE = presRes ? "" : "Assy_Pressure OOS"
-                                            });
-                                            foreach (var item in DFC)
-                                            {
-                                                FileHelper.WriteDataToCSV(item);
-                                            }
-                                            #endregion
+                                            presRes = true;
                                         }
                                         }
-                                        catch (Exception ex)
+                                        else presRes = false;
+                                        DFC.Clear();
+                                        DFC.Add(new DataFormCtq
                                         {
                                         {
-                                            SendTaskMessage("CTQ数据存储时出错" + ex.Message, MessageLevel.Error);
-                                        }
+                                            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成功");
@@ -2668,6 +2800,32 @@ 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);
 
 
@@ -2713,11 +2871,8 @@ namespace TeamAAS_VP.Core
                                 }
                                 }
                             }
                             }
                         }
                         }
-                    }
-                    //开始/停止 组装/锁附
-                    for (int i = 0; i < 7; i++)
-                    {
-                        if (string.Format(addressConfig.In_WorkDone.Address, i).Contains(tuple.nodeId))
+                        //停止组装
+                        else if (string.Format(addressConfig.In_WorkDone.Address, i).Contains(tuple.nodeId))
                         {
                         {
                             if (tuple.value is Int16 state)
                             if (tuple.value is Int16 state)
                             {
                             {
@@ -3053,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
     }
     }
 }
 }

+ 34 - 6
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>
         /// 获取刷卡器配置
         /// 获取刷卡器配置
@@ -502,8 +533,5 @@ namespace TeamAAS_VP.Interfaces
         /// </summary>
         /// </summary>
         /// <param name="config"></param>
         /// <param name="config"></param>
         void SaveCardReaderConfig(SerialPortConfig config);
         void SaveCardReaderConfig(SerialPortConfig config);
-
-        CTQ_Data GetCTQDataInfo();
-        void SaveCTQDataInfo(CTQ_Data cd);
     }
     }
 }
 }

+ 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>

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

@@ -129,5 +129,52 @@ namespace TeamAAS_VP.Models
         /// </summary>
         /// </summary>
         public string ERROR_MESSAGE { get => _ERROR_MESSAGE; set => SetProperty(ref _ERROR_MESSAGE, value); }
         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
+            };
+        }
+
     }
     }
 }
 }

+ 6 - 6
TeamAAS-VM/Models/DataFormCtq.cs

@@ -33,23 +33,23 @@ namespace TeamAAS_VP.Models
         /// </summary>
         /// </summary>
         public string CTQ_NAME { get => _CTQ_NAME; set => SetProperty(ref _CTQ_NAME, value); }
         public string CTQ_NAME { get => _CTQ_NAME; set => SetProperty(ref _CTQ_NAME, value); }
 
 
-        private double _CTQ_VALUE;
+        private string _CTQ_VALUE;
         /// <summary>
         /// <summary>
         /// 检测值
         /// 检测值
         /// </summary>
         /// </summary>
-        public double CTQ_VALUE { get => _CTQ_VALUE; set => SetProperty(ref _CTQ_VALUE, value); }
+        public string CTQ_VALUE { get => _CTQ_VALUE; set => SetProperty(ref _CTQ_VALUE, value); }
 
 
-        private double _CTQ_LSL;
+        private string _CTQ_LSL;
         /// <summary>
         /// <summary>
         /// 下限
         /// 下限
         /// </summary>
         /// </summary>
-        public double CTQ_LSL { get => _CTQ_LSL; set => SetProperty(ref _CTQ_LSL, value); }
+        public string CTQ_LSL { get => _CTQ_LSL; set => SetProperty(ref _CTQ_LSL, value); }
 
 
-        private double _CTQ_USL;
+        private string _CTQ_USL;
         /// <summary>
         /// <summary>
         /// 上限
         /// 上限
         /// </summary>
         /// </summary>
-        public double CTQ_USL { get => _CTQ_USL; set => SetProperty(ref _CTQ_USL, value); }
+        public string CTQ_USL { get => _CTQ_USL; set => SetProperty(ref _CTQ_USL, value); }
 
 
         private string _PROCESS_END_TIME;
         private string _PROCESS_END_TIME;
         /// <summary>
         /// <summary>

+ 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()
+            };
+        }
     }
     }
 }
 }

+ 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")]

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

@@ -2016,4 +2016,31 @@
   <data name="请选择要启用的光源通道" xml:space="preserve">
   <data name="请选择要启用的光源通道" xml:space="preserve">
     <value>Please select a light channel to enable</value>
     <value>Please select a light channel to enable</value>
   </data>
   </data>
+  <data name="通过下相机获取P0" xml:space="preserve">
+    <value>The upper and lower cameras take pictures together, and the lower camera obtains P0</value>
+  </data>
+  <data name="是否控制光源通道亮灭" xml:space="preserve">
+    <value>Whether to control the light source channel to turn on or off</value>
+  </data>
+  <data name="CameraBrand_opt" xml:space="preserve">
+    <value>OPT Camera Viewer</value>
+  </data>
+  <data name="相机焦距评价" xml:space="preserve">
+    <value>Camera focal length evaluation</value>
+  </data>
+  <data name="螺丝供料器" xml:space="preserve">
+    <value>Screw feeder</value>
+  </data>
+  <data name="通过移动至下相机拍照位置拍照计算P0" xml:space="preserve">
+    <value>By moving to the lower camera taking position, take a picture to get P0, and then put it back to the original position</value>
+  </data>
+  <data name="视觉静态精度分析" xml:space="preserve">
+    <value>Visual static accuracy analysis</value>
+  </data>
+  <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" xml:space="preserve">
+    <value>Year, month/day/recipe name/product SN/product SN+time</value>
+  </data>
+  <data name="CameraMount_MobileDownIndependentXYPlatform" xml:space="preserve">
+    <value>Independent XY mobile camera</value>
+  </data>
 </root>
 </root>

+ 27 - 0
TeamAAS-VM/Resources/Languages/Lang.ja-JP.resx

@@ -2016,4 +2016,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カメラビューア</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>

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

@@ -2016,4 +2016,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>

+ 145 - 49
TeamAAS-VM/Services/ConfigService.cs

@@ -68,9 +68,9 @@ 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;
-        public CTQ_Data CtqData { get; set; }
+        // Device info - 支持多设备
+        private List<DeviceInfo> _deviceInfoList;
+
         private PlcAddressConfig PlcAddressConfig { get; set; }
         private PlcAddressConfig PlcAddressConfig { get; set; }
         // 单个电批配置
         // 单个电批配置
         private TeamAAS_VP.Models.ScrewDriver.ScrewDriverConfig _screwDriverConfig;
         private TeamAAS_VP.Models.ScrewDriver.ScrewDriverConfig _screwDriverConfig;
@@ -222,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
@@ -240,13 +261,6 @@ namespace TeamAAS_VP.Services
                     FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
                     FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
                 }
                 }
 
 
-                if (File.Exists(ConfigPaths.DataConfigurationPath))
-                    CtqData = FileHelper.ReadJsonFile<CTQ_Data>(ConfigPaths.DataConfigurationPath);
-                else
-                {
-                    CtqData = new CTQ_Data();
-                    FileHelper.WriteJsonFile(CtqData, ConfigPaths.DataConfigurationPath);
-                }
             }
             }
         }
         }
 
 
@@ -283,14 +297,12 @@ 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);
-                if (CtqData != null)
-                    FileHelper.WriteJsonFile(CtqData, ConfigPaths.DataConfigurationPath);
             }
             }
         }
         }
 
 
@@ -395,74 +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);
             }
             }
         }
         }
-        #endregion
 
 
-        #region CTQData
         /// <summary>
         /// <summary>
-        /// 获取CTQ信息配置
+        /// 保存所有设备信息列表
         /// </summary>
         /// </summary>
-        public CTQ_Data GetCTQDataInfo()
+        /// <param name="deviceInfoList">设备信息列表</param>
+        public void SaveAllDeviceInfos(IEnumerable<DeviceInfo> deviceInfoList)
         {
         {
+            if (deviceInfoList == null) return;
             lock (_sync)
             lock (_sync)
             {
             {
-                if (CtqData == null)
+                _deviceInfoList = deviceInfoList.OrderBy(d => d.DeviceNo).ToList();
+                FileHelper.WriteJsonFile(_deviceInfoList, ConfigPaths.DeviceInfoConfigurationPath);
+            }
+        }
+
+        /// <summary>
+        /// 添加新设备
+        /// </summary>
+        /// <returns>新添加的设备</returns>
+        public DeviceInfo AddDeviceInfo()
+        {
+            lock (_sync)
+            {
+                if (_deviceInfoList == null)
                 {
                 {
-                    if (File.Exists(ConfigPaths.DataConfigurationPath))
-                        CtqData = FileHelper.ReadJsonFile<CTQ_Data>(ConfigPaths.DataConfigurationPath);
-                    else
-                    {
-                        CtqData = new CTQ_Data();
-                        FileHelper.WriteJsonFile(CtqData, ConfigPaths.DataConfigurationPath);
-                    }
+                    _deviceInfoList = new List<DeviceInfo>();
                 }
                 }
-                return CtqData;
+
+                // 计算新设备编号
+                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>
-        /// 保存CTQ信息
+        /// 删除设备
         /// </summary>
         /// </summary>
-        public void SaveCTQDataInfo(CTQ_Data cd)
+        /// <param name="deviceNo">设备编号</param>
+        /// <returns>是否删除成功</returns>
+        public bool RemoveDeviceInfo(int deviceNo)
         {
         {
-            if (cd == null) return;
             lock (_sync)
             lock (_sync)
             {
             {
-                CtqData = cd;
-                FileHelper.WriteJsonFile(CtqData, ConfigPaths.DataConfigurationPath);
+                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

+ 201 - 33
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,7 +77,7 @@ 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));
@@ -104,27 +105,27 @@ namespace TeamAAS_VP.Services
 
 
             try
             try
             {
             {
-                string str = station[num];
+                string str = station[deviceNo];
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
                 return (false, "本机应该有多站,station应该有多个值");
                 return (false, "本机应该有多站,station应该有多个值");
             }
             }
 
 
-            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={station[deviceNo]}&fixtureid={fixtureId[deviceNo]}&sn={sn}&comp={device.comp}:{comp}&p=unit_process_check,message,model";
                 }
                 }
                 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={station[deviceNo]}&fixtureid={fixtureId[deviceNo]}&sn={sn}&p=unit_process_check,message,model";
                 }
                 }
             }
             }
             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={station[deviceNo]}&fixtureid={fixtureId[deviceNo]}&sn={sn}&p=unit_process_check,message,model";
             }
             }
 
 
             LogHelper.WriteLogMes($"【询问URL】{url}");
             LogHelper.WriteLogMes($"【询问URL】{url}");
@@ -170,11 +171,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=sn,message";
+
+            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);
             }
             }
         }
         }
 
 
@@ -200,7 +283,7 @@ 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));
@@ -220,36 +303,51 @@ namespace TeamAAS_VP.Services
                 }
                 }
             }
             }
 
 
-            //string res = isSuccess ? "PASS" : "FAIL";
-            string res = "PASS";
-            string url = "";
-            string[] station = new string[3];
-            string[] fixtureId = new string[3];
-            station = device.Station.Split(',');
-            fixtureId = device.FixtureId.Split(',');
-
-            if (num == 0)//组装站
+            string res = isSuccess ? "PASS" : "FAIL";
+            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);
@@ -297,12 +395,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
             {
             {
                 //拍照失败时,需要多次拍照
                 //拍照失败时,需要多次拍照

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

@@ -532,6 +532,7 @@
     <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" />
@@ -547,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();
+        }
+    }
+}

+ 110 - 21
TeamAAS-VM/ViewModels/SettingViewModel.cs

@@ -328,18 +328,39 @@ namespace TeamAAS_VP.ViewModels
             set { SetProperty(ref _SelectLightController, value); }
             set { SetProperty(ref _SelectLightController, value); }
         }
         }
 
 
-        private DeviceInfo _DeviceInfo;
-        public DeviceInfo DeviceInfo
+        // 设备信息列表
+        private ObservableCollection<DeviceInfo> _DeviceInfoList;
+        public ObservableCollection<DeviceInfo> DeviceInfoList
         {
         {
-            get { return _DeviceInfo; }
-            set { SetProperty(ref _DeviceInfo, value); }
+            get { return _DeviceInfoList; }
+            set { SetProperty(ref _DeviceInfoList, value); }
         }
         }
 
 
-        private CTQ_Data _dataInfo;
-        public CTQ_Data DataInfo
+        // 当前选中的设备信息
+        private DeviceInfo _SelectDeviceInfo;
+        public DeviceInfo SelectDeviceInfo
         {
         {
-            get { return _dataInfo; }
-            set { SetProperty(ref _dataInfo, value); }
+            get { return _SelectDeviceInfo; }
+            set { SetProperty(ref _SelectDeviceInfo, value); }
+        }
+
+        // 兼容旧代码,DeviceInfo 指向当前选中的设备或第一个设备
+        public DeviceInfo DeviceInfo
+        {
+            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;
@@ -453,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));
 
 
@@ -467,9 +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));
-
-        private DelegateCommand _SaveDataInfoCommand;
-        public DelegateCommand SaveDataInfoCommand => _SaveDataInfoCommand ?? (_SaveDataInfoCommand = new DelegateCommand(ExecuteSaveDataInfoCommand));
         #endregion
         #endregion
 
 
         #region 事件
         #region 事件
@@ -1374,10 +1398,16 @@ namespace TeamAAS_VP.ViewModels
                 DeviceInfo = _configService.GetDeviceInfo();
                 DeviceInfo = _configService.GetDeviceInfo();
             }
             }
 
 
-            if (DataInfo == null)
+            if (DeviceInfoList == null || DeviceInfoList.Count == 0)
             {
             {
-                // load device info
-                DataInfo = _configService.GetCTQDataInfo();
+                // 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)
@@ -1655,15 +1685,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 });
                 }
                 }
             }
             }
@@ -1673,14 +1704,48 @@ namespace TeamAAS_VP.ViewModels
             }
             }
         }
         }
 
 
-        private void ExecuteSaveDataInfoCommand()
+        /// <summary>
+        /// 添加新设备
+        /// </summary>
+        void ExecuteAddDeviceInfoCommand()
         {
         {
             try
             try
             {
             {
-                if (DataInfo != null)
+                var newDevice = _configService.AddDeviceInfo();
+                if (DeviceInfoList == null)
                 {
                 {
-                    _configService.SaveCTQDataInfo(DataInfo);
-                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
+                    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)
             catch (Exception ex)
@@ -1688,6 +1753,30 @@ 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>
+        /// 选择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
     }
     }
 }
 }

+ 33 - 32
TeamAAS-VM/Views/Home/ShowVisionRender.xaml.cs

@@ -315,7 +315,8 @@ namespace TeamAAS_VP.Views.Home
                                 render.Image,
                                 render.Image,
                                 clonedBitmap,
                                 clonedBitmap,
                                 render.Result,
                                 render.Result,
-                                render.IsCompress
+                                render.IsCompress,
+                                render.ImageFileName
                             );
                             );
                         }
                         }
                         catch (OperationCanceledException)
                         catch (OperationCanceledException)
@@ -349,13 +350,7 @@ namespace TeamAAS_VP.Views.Home
         /// <summary>
         /// <summary>
         /// 保存图像(保持你原有逻辑不变,补充 Dispose 兜底,防止压缩分支不释放导致闪退)
         /// 保存图像(保持你原有逻辑不变,补充 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))
             {
             {
@@ -369,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;
                         }
                         }
@@ -407,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)))
@@ -422,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;
                         }
                         }
@@ -455,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)))
@@ -472,28 +473,28 @@ namespace TeamAAS_VP.Views.Home
                     }
                     }
                     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
                             {
                             {
@@ -504,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
                             {
                             {
@@ -523,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)))

+ 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}">

+ 348 - 205
TeamAAS-VM/Views/SettingView.xaml

@@ -223,222 +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="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>
 
 

+ 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)
             {
             {