Просмотр исходного кода

Merge branch 'master' of http://49.235.130.76/XXF_1122/DaisyNPILine

wanghan 9 месяцев назад
Родитель
Сommit
84da534fd2
39 измененных файлов с 3186 добавлено и 227 удалено
  1. 1 0
      TeamAAS-VM/App.xaml.cs
  2. 139 79
      TeamAAS-VM/Core/Cameras/OptCamera.cs
  3. 794 53
      TeamAAS-VM/Core/FileHelper.cs
  4. 4 2
      TeamAAS-VM/Core/FilePath.cs
  5. 45 7
      TeamAAS-VM/Core/Management.cs
  6. 687 0
      TeamAAS-VM/Core/VisionProFileHelper.cs
  7. 3 1
      TeamAAS-VM/Interfaces/IRemoteCommandService.cs
  8. 5 0
      TeamAAS-VM/Models/PhotoCaptureRecord.cs
  9. 74 0
      TeamAAS-VM/Models/Torque/PickDynamicTestResult.cs
  10. 32 0
      TeamAAS-VM/Models/Torque/PickScrewAccuracyAnalyzerrConfigModel.cs
  11. 0 3
      TeamAAS-VM/Models/Torque/PlcPoint_Torque.cs
  12. 2 2
      TeamAAS-VM/Properties/AssemblyInfo.cs
  13. 6 6
      TeamAAS-VM/Services/CalibrationService.cs
  14. 2 1
      TeamAAS-VM/Services/ConfigService.cs
  15. 8 8
      TeamAAS-VM/Services/ProductService.cs
  16. 17 7
      TeamAAS-VM/Services/RemoteCommandService.cs
  17. 2 2
      TeamAAS-VM/Services/TorqueService.cs
  18. 14 1
      TeamAAS-VM/TeamAAS-VP.csproj
  19. 3 3
      TeamAAS-VM/ViewModels/Calibration/CalibrationCameraParamsViewModel.cs
  20. 1 1
      TeamAAS-VM/ViewModels/Calibration/CalibrationHomeViewModel.cs
  21. 3 3
      TeamAAS-VM/ViewModels/Calibration/FixedUpCameraFindP0ViewModel.cs
  22. 451 0
      TeamAAS-VM/ViewModels/Home/PickScrewAccuracyAnalyzerViewModel.cs
  23. 32 7
      TeamAAS-VM/ViewModels/Home/TorqueCheckViewModel.cs
  24. 1 1
      TeamAAS-VM/ViewModels/HomeViewModel.cs
  25. 1 1
      TeamAAS-VM/ViewModels/MainWindowViewModel.cs
  26. 12 10
      TeamAAS-VM/ViewModels/Product/AdvancedProcedureViewModel.cs
  27. 203 0
      TeamAAS-VM/ViewModels/Product/PlcPointParamsViewModel.cs
  28. 3 3
      TeamAAS-VM/ViewModels/Product/ProcessBasicsViewModel.cs
  29. 2 2
      TeamAAS-VM/ViewModels/Product/ProductProcessManageViewModel.cs
  30. 27 2
      TeamAAS-VM/ViewModels/Statistics/PhotoCaptureQueryViewModel.cs
  31. 28 8
      TeamAAS-VM/ViewModels/Statistics/ProductionRecordQueryViewModel.cs
  32. 471 0
      TeamAAS-VM/Views/Home/PickScrewAccuracyAnalyzer.xaml
  33. 28 0
      TeamAAS-VM/Views/Home/PickScrewAccuracyAnalyzer.xaml.cs
  34. 4 4
      TeamAAS-VM/Views/Home/TorqueCheck.xaml
  35. 11 0
      TeamAAS-VM/Views/Product/PlcPointParams.xaml
  36. 1 1
      TeamAAS-VM/Views/Product/PlcPointParams.xaml.cs
  37. 2 2
      TeamAAS-VM/Views/SettingView.xaml
  38. 58 7
      TeamAAS-VM/Views/Statistics/PhotoCaptureQuery.xaml
  39. 9 0
      TeamAAS-VM/Views/Statistics/ProductionRecordQuery.xaml

+ 1 - 0
TeamAAS-VM/App.xaml.cs

@@ -214,6 +214,7 @@ namespace TeamAAS_VP
             containerRegistry.RegisterDialog<ChangeHeader>();
             containerRegistry.RegisterDialog<ChangeNozzle>();
             containerRegistry.RegisterDialog<PlcPointOffserParams>();
+            containerRegistry.RegisterDialog<PickScrewAccuracyAnalyzer>();
             //**************************************************************************************
 
             // 注册 SQLSugar 客户端(单例模式)

+ 139 - 79
TeamAAS-VM/Core/Cameras/OptCamera.cs

@@ -1,6 +1,8 @@
 using Cognex.VisionPro;
 using Microsoft.Win32;
+using netDxf.Entities;
 using NPOI.POIFS.Crypt.Dsig;
+using NPOI.SS.Formula;
 using NPOI.SS.Formula.Eval;
 using SciCamera.Net;
 using System;
@@ -15,6 +17,7 @@ using System.Runtime.InteropServices;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
+using System.Web.Configuration;
 using TeamAAS_VP.Enums;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
@@ -29,6 +32,7 @@ namespace TeamAAS_VP.Core.Cameras
         //private readonly SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
         // 用于保护状态变量(例如 IsGrabbing)的并发访问
         private readonly object _stateLock = new object();
+        private TaskCompletionSource<ICogImage> _tcs;
         #endregion
 
         #region 属性
@@ -352,7 +356,7 @@ namespace TeamAAS_VP.Core.Cameras
                 // ch:打开设备 | en:Open device
                 nReVal = mvCameraAcq.OpenDevice();
                 // ch:设置触发模式为off | en:Set trigger mode as off
-                nReVal = mvCameraAcq.SetEnumValueByStringEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerMode", "Off");
+                nReVal = mvCameraAcq.SetEnumValueByStringEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerMode", "On");
                 nReVal = mvCameraAcq.SetEnumValueByString("TriggerSource", "Software");
                 // ch:注册事件回调 | en:Register event callback
                 //nReVal = mvCameraAcq.RegisterPayloadCallBack(new SciCam.fnOnPayloadDelegate(ImageCallBack), IntPtr.Zero, true);
@@ -366,7 +370,7 @@ namespace TeamAAS_VP.Core.Cameras
                 {
                     CameraConnectChangedEvent?.Invoke(ID, true);
                 }
-                mvCameraAcq.SetGrabTimeout(2000);
+                mvCameraAcq.SetGrabTimeout(5000);
                 IsConnected = mvCameraAcq.IsDeviceOpen();
                 if (IsConnected)
                 {
@@ -401,8 +405,9 @@ namespace TeamAAS_VP.Core.Cameras
             //_operationSemaphore.Wait();
             try
             {
-                mvCameraAcq.StopGrabbing();
-                mvCameraAcq.CloseDevice();
+                mvCameraAcq?.StopGrabbing();
+                mvCameraAcq?.CloseDevice();
+                mvCameraAcq?.DeleteDevice();
             }
             finally
             {
@@ -432,43 +437,39 @@ namespace TeamAAS_VP.Core.Cameras
                             OpenDevice();
                         }
 
-                        //如果仅仅采集最后一帧,则清空缓存
-                        if (lastImageOnly)
+                        // 重置TaskCompletionSource
+                        //_tcs?.TrySetCanceled();
+                        //_tcs = new TaskCompletionSource<ICogImage>();
+
+                        // 注册取消令牌
+                        //CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(2000000); // 2秒超时
+                        //cancellationTokenSource.Token.Register(() => _tcs.TrySetCanceled());
+
+                        // 触发图像采集
+                        // ch:发送软触发命令 | en:Send Trigger Software command
+                        nReVal = mvCameraAcq.SetCommandValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerSoftware");
+                        if (nReVal == SciCam.SCI_CAMERA_OK)
                         {
-                            //判断当前的模式是否为最新模式,如果不是则设置为最新模式
-                            if (CurrentGrabStrategy != SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Upcoming)
+                            nReVal = mvCameraAcq.Grab(ref payload);
+                            if (nReVal == SciCam.SCI_CAMERA_OK)
                             {
-                                CurrentGrabStrategy = SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Upcoming;
-                                nReVal = mvCameraAcq.SetGrabStrategy(CurrentGrabStrategy);
+                                Image = GetConvertedInfo(payload);
+                                mvCameraAcq.FreePayload(payload);
+                                //nReVal = mvCameraAcq.StopGrabbing();
+                                TotalTime = sw.Elapsed;
+                                ErrorMessage = $"{i + 1}";
+                                return Image;
                             }
-                        }
-                        else
-                        {
-                            //判断当前的模式是否为顺序模式,如果不是则设置为顺序模式
-                            if (CurrentGrabStrategy != SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Latest)
+                            else
                             {
-                                CurrentGrabStrategy = SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Latest;
-                                nReVal = mvCameraAcq.SetGrabStrategy(CurrentGrabStrategy);
+                                //nReVal = mvCameraAcq.FreePayload(payload);
+                                //nReVal = mvCameraAcq.StopGrabbing();
+                                //_operationSemaphore.Release();
+                                CloseDevice();
+                                OpenDevice();
+                                ErrorMessage = "图像采集失败!";
                             }
                         }
-                        //if (!mvCameraAcq.IsGrabbing())
-                        //{
-                        //    mvCameraAcq.StartGrabbing();
-                        //}
-                        //nReVal = mvCameraAcq.StartGrabbing();
-                        //mvCameraAcq.ClearPayloadBuffer();
-                        // ch:发送软触发命令 | en:Send Trigger Software command
-                        //nReVal = mvCameraAcq.SetCommandValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerSoftware");
-                        nReVal = mvCameraAcq.Grab(ref payload);
-                        if (nReVal == SciCam.SCI_CAMERA_OK)
-                        {
-                            Image = GetConvertedInfo(payload);
-                            mvCameraAcq.FreePayload(payload);
-                            //nReVal = mvCameraAcq.StopGrabbing();
-                            TotalTime = sw.Elapsed;
-                            ErrorMessage = $"{i + 1}";
-                            return Image;
-                        }
                         else
                         {
                             //nReVal = mvCameraAcq.FreePayload(payload);
@@ -476,7 +477,7 @@ namespace TeamAAS_VP.Core.Cameras
                             //_operationSemaphore.Release();
                             CloseDevice();
                             OpenDevice();
-                            ErrorMessage = "图像采集失败!";
+                            ErrorMessage = "软触发失败!";
                         }
                     }
                     catch (Exception ex)
@@ -503,21 +504,31 @@ namespace TeamAAS_VP.Core.Cameras
         // ch:采集回调接口 | en:Grab Callback interface     
         void ImageCallBack(IntPtr payload, IntPtr tag)
         {
-            if (payload == IntPtr.Zero) return;
-            uint nReVal = SciCam.SCI_CAMERA_OK;
-
-            SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE attribute = new SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE();
-            nReVal = SciCam.PayloadGetAttribute(payload, ref attribute);
-            if (nReVal != SciCam.SCI_CAMERA_OK || !attribute.isComplete)
+            try
             {
-                Console.WriteLine("Failed to get image attributes or frame is incomplete! nRet:{0}", nReVal);
+                if (payload == IntPtr.Zero) return;
+                uint nReVal = SciCam.SCI_CAMERA_OK;
+
+                SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE attribute = new SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE();
+                nReVal = SciCam.PayloadGetAttribute(payload, ref attribute);
+                if (nReVal != SciCam.SCI_CAMERA_OK || !attribute.isComplete)
+                {
+                    Console.WriteLine("Failed to get image attributes or frame is incomplete! nRet:{0}", nReVal);
+                    _tcs?.TrySetException(new Exception($"Failed to get image attributes or frame is incomplete! nRet: {nReVal}"));
+                }
+                else
+                {
+                    Image = GetConvertedInfo(payload);
+                    //ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+                    //Console.WriteLine("Get One Frame: Width[{0}], Height[{1}], nFrameNum[{2}]",
+                    //attribute.imgAttr.width, attribute.imgAttr.height, attribute.frameID);
+                    // 收到图像时完成任务
+                    _tcs?.TrySetResult(Image);
+                }
             }
-            else
+            catch (Exception ex)
             {
-                Image = GetConvertedInfo(payload);
-                ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
-                //Console.WriteLine("Get One Frame: Width[{0}], Height[{1}], nFrameNum[{2}]",
-                //attribute.imgAttr.width, attribute.imgAttr.height, attribute.frameID);
+                _tcs?.TrySetException(new Exception($"相机采集错误: {ex.Message}"));
             }
         }
 
@@ -566,16 +577,37 @@ namespace TeamAAS_VP.Core.Cameras
         /// <returns></returns>
         public bool SetExposureTime(float ExposureTime)
         {
-            //_operationSemaphore.Wait();
             try
             {
                 if (!mvCameraAcq.IsDeviceOpen())
                     return false;
+                string[] nodeName = new string[]{
+                "ExposureTime",
+                "ExposureTimeAbs",
+                "ExposureTimeRaw"};
+
                 uint nReVal = SciCam.SCI_CAMERA_OK;
-                nReVal = mvCameraAcq.SetIntValue("ExposureTime", (int)ExposureTime);
+                for (int i = 0; i < nodeName.Count(); i++)
+                {
+                    nReVal = mvCameraAcq.SetIntValue(nodeName[i], (int)ExposureTime);
+
+                    if (nReVal != SciCam.SCI_CAMERA_OK)
+                    {
+                        nReVal = mvCameraAcq.SetFloatValue(nodeName[i], ExposureTime);
+                        if (nReVal == SciCam.SCI_CAMERA_OK)
+                        {
+                            break;
+                        }
+                    }
+                    else
+                    {
+                        break;
+                    }
+                }
+
                 if (nReVal != SciCam.SCI_CAMERA_OK)
                 {
-                    mvCameraAcq.SetFloatValue("ExposureTime", ExposureTime);
+                    return false;
                 }
                 return true;
             }
@@ -598,25 +630,31 @@ namespace TeamAAS_VP.Core.Cameras
                     return 0;
 
                 uint nReVal = SciCam.SCI_CAMERA_OK;
-                SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
-                nReVal = mvCameraAcq.GetIntValue("ExposureTime", ref iNodeVal);
-                if (nReVal != SciCam.SCI_CAMERA_OK)
+                string[] nodeName = new string[]
+            {
+                "ExposureTime",
+                "ExposureTimeAbs",
+                "ExposureTimeRaw"
+            };
+                for (int i = 0; i < nodeName.Count(); i++)
                 {
-                    SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
-                    nReVal = mvCameraAcq.GetFloatValue("ExposureTime", ref fNodeVal);
-                    if (nReVal == SciCam.SCI_CAMERA_OK)
+                    SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
+                    nReVal = mvCameraAcq.GetIntValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], ref iNodeVal);
+                    if (nReVal != SciCam.SCI_CAMERA_OK)
                     {
-                        return (float)fNodeVal.dVal;
+                        SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
+                        nReVal = mvCameraAcq.GetFloatValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], ref fNodeVal);
+                        if (nReVal == SciCam.SCI_CAMERA_OK)
+                        {
+                            return Convert.ToSingle(fNodeVal.dVal);
+                        }
                     }
                     else
                     {
-                        return 0;
+                        return Convert.ToSingle(iNodeVal.nVal);
                     }
                 }
-                else
-                {
-                    return (float)iNodeVal.nVal;
-                }
+                return 0;
             }
             finally
             {
@@ -637,12 +675,29 @@ namespace TeamAAS_VP.Core.Cameras
                 if (!mvCameraAcq.IsDeviceOpen())
                     return false;
                 uint nReVal = SciCam.SCI_CAMERA_OK;
-                nReVal = mvCameraAcq.SetIntValue("Gain", (int)Gain);
-                if (nReVal != SciCam.SCI_CAMERA_OK)
+                string[] nodeName = new string[]
+            {
+                "Gain",
+                "GainRaw"
+            };
+                for (int i = 0; i < nodeName.Count(); i++)
                 {
-                    mvCameraAcq.SetFloatValue("Gain", Gain);
+                    nReVal = mvCameraAcq.SetIntValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], (int)Gain);
+                    if (nReVal != SciCam.SCI_CAMERA_OK)
+                    {
+                        nReVal = mvCameraAcq.SetFloatValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], Gain);
+                        if (nReVal == SciCam.SCI_CAMERA_OK)
+                        {
+                            return true;
+                        }
+                    }
+                    else
+                    {
+                        return true;
+
+                    }
                 }
-                return true;
+                return false;
             }
             finally
             {
@@ -662,25 +717,30 @@ namespace TeamAAS_VP.Core.Cameras
                 if (!mvCameraAcq.IsDeviceOpen())
                     return 0;
                 uint nReVal = SciCam.SCI_CAMERA_OK;
-                SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
-                nReVal = mvCameraAcq.GetIntValue("Gain", ref iNodeVal);
-                if (nReVal != SciCam.SCI_CAMERA_OK)
+                string[] nodeName = new string[]
+            {
+                "Gain",
+                "GainRaw"
+            };
+                for (int i = 0; i < nodeName.Count(); i++)
                 {
-                    SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
-                    nReVal = mvCameraAcq.GetFloatValue("Gain", ref fNodeVal);
-                    if (nReVal == SciCam.SCI_CAMERA_OK)
+                    SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
+                    nReVal = mvCameraAcq.GetIntValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], ref iNodeVal);
+                    if (nReVal != SciCam.SCI_CAMERA_OK)
                     {
-                        return (float)fNodeVal.dVal;
+                        SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
+                        nReVal = mvCameraAcq.GetFloatValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], ref fNodeVal);
+                        if (nReVal == SciCam.SCI_CAMERA_OK)
+                        {
+                            return Convert.ToSingle(fNodeVal.dVal);
+                        }
                     }
                     else
                     {
-                        return 0;
+                        return Convert.ToSingle(iNodeVal.nVal);
                     }
                 }
-                else
-                {
-                    return (float)iNodeVal.nVal;
-                }
+                return 0;
             }
             finally
             {

+ 794 - 53
TeamAAS-VM/Core/FileHelper.cs

@@ -1,5 +1,7 @@
 using ControlzEx.Standard;
 using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using NPOI.Util;
 using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
@@ -11,116 +13,855 @@ using System.Threading.Tasks;
 using TeamAAS_VP;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Resources.Languages;
-using static Org.BouncyCastle.Math.EC.ECCurve;
 
 namespace TeamAAS_VP.Core
 {
+    /// <summary>
+    /// 提供文件读写、备份与恢复相关的静态辅助方法。
+    /// 功能包括:安全写入(临时文件 + 原子替换)、JSON 读写(含格式校验)、备份版本管理、临时/备份清理与恢复等。
+    /// 该类内部包含可配置的选项,通过 <see cref="Configure"/> 进行设置。
+    /// </summary>
     public static class FileHelper
     {
+        #region 配置选项
         /// <summary>
-        /// 写入Json文件
+        /// 文件操作辅助类的配置项集合。
+        /// 可通过 <see cref="Configure"/> 修改。
         /// </summary>
-        /// <param name="obj">对象</param>
-        /// <param name="path">文件路径</param>
+        public class FileHelperOptions
+        {
+            /// <summary>
+            /// 是否启用自动恢复(读取失败时尝试从备份恢复)。默认值:true。
+            /// </summary>
+            public bool EnableAutoRecovery { get; set; } = true;
+
+            /// <summary>
+            /// 是否保留每次写入时生成的 .bak 备份文件。默认值:false。
+            /// </summary>
+            public bool KeepBackupFiles { get; set; } = false;
+
+            /// <summary>
+            /// 保留的版本化备份最大数量(超过会清理)。默认值:3。
+            /// </summary>
+            public int MaxBackupVersions { get; set; } = 3;
+
+            /// <summary>
+            /// 是否启用内部日志记录(通过 LogHelper)。默认值:false。
+            /// </summary>
+            public bool EnableLogging { get; set; } = false;
+
+            /// <summary>
+            /// 版本化备份存放目录名称(相对于原文件目录)。默认值:"Backups"。
+            /// </summary>
+            public string BackupDirectory { get; set; } = "Backups";
+
+            /// <summary>
+            /// 文件读写所使用的编码。默认值:UTF8。
+            /// </summary>
+            public Encoding FileEncoding { get; set; } = Encoding.UTF8;
+        }
+
+        private static FileHelperOptions _options = new FileHelperOptions();
+
+        /// <summary>
+        /// 配置 FileHelper 的运行时选项。
+        /// </summary>
+        /// <param name="configure">接收并修改 <see cref="FileHelperOptions"/> 的委托;如果为 null 则保持默认配置。</param>
+        public static void Configure(Action<FileHelperOptions> configure)
+        {
+            configure?.Invoke(_options);
+        }
+        #endregion
+
+        #region Json文件操作
+        /// <summary>
+        /// 将对象序列化为格式化 JSON 并安全写入指定路径。
+        /// 写入使用临时文件 + 原子替换以减少损坏风险,并根据配置创建版本化备份。
+        /// </summary>
+        /// <param name="obj">要序列化并写入的对象。</param>
+        /// <param name="path">目标文件完整路径。</param>
         public static void WriteJsonFile(object obj, string path)
         {
-            if (!Directory.Exists(Path.GetDirectoryName(path)))
+            ValidatePath(path);
+            string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
+            WriteFileInternal(json, path);
+        }
+
+        /// <summary>
+        /// 读取 JSON 文件并反序列化为指定类型,支持自动从备份恢复。
+        /// 如果读取失败且启用了自动恢复,将尝试从 .bak 或版本化备份恢复。
+        /// </summary>
+        /// <typeparam name="T">反序列化的目标类型。</typeparam>
+        /// <param name="path">JSON 文件路径。</param>
+        /// <param name="autoRecover">可选:覆盖默认的自动恢复行为(null 表示使用配置项)。</param>
+        /// <returns>反序列化后的对象。</returns>
+        /// <exception cref="FileNotFoundException">当文件不存在且无法恢复时抛出。</exception>
+        public static T ReadJsonFile<T>(string path, bool? autoRecover = null)
+        {
+            ValidatePath(path);
+
+            bool shouldRecover = autoRecover ?? _options.EnableAutoRecovery;
+
+            // 检查并清理临时文件
+            CheckAndCleanTempFile(path);
+
+            // 尝试读取主文件
+            Exception lastException = null;
+
+            try
             {
-                Directory.CreateDirectory(Path.GetDirectoryName(path));
+                if (File.Exists(path))
+                {
+                    string json = ReadAndValidateJsonFile(path);
+                    return JsonConvert.DeserializeObject<T>(json);
+                }
             }
-            using (StreamWriter sw = new StreamWriter(path))
+            catch (Exception ex)
             {
-                string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
-                sw.Write(JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented));
+                lastException = ex;
+                Log($"读取主文件失败: {ex.Message}");
+
+                if (shouldRecover)
+                {
+                    try
+                    {
+                        // 尝试从备份恢复
+                        T recovered = TryRecoverJsonFile<T>(path);
+                        if (recovered != null)
+                            return recovered;
+                    }
+                    catch (Exception recoveryEx)
+                    {
+                        Log($"恢复尝试失败: {recoveryEx.Message}");
+                    }
+                }
             }
+
+            // 如果文件不存在且允许恢复,尝试从默认备份位置恢复
+            if (shouldRecover && !File.Exists(path))
+            {
+                T recovered = TryFindAndRecoverJsonFile<T>(path);
+                if (recovered != null)
+                    return recovered;
+            }
+
+            throw new FileNotFoundException($"文件 {path} 不存在且无法恢复", lastException);
         }
+        #endregion
 
+        #region 普通文件操作
         /// <summary>
-        /// 读取Json文件
+        /// 安全写入文本文件(支持目录创建、临时写入、原子替换与可选版本化备份)。
         /// </summary>
-        /// <typeparam name="T">对象</typeparam>
-        /// <param name="path">文件路径</param>
-        /// <returns></returns>
-        /// <exception cref="Exception"></exception>
-        public static T ReadJsonFile<T>(string path)
+        /// <param name="content">要写入的文本内容。</param>
+        /// <param name="path">目标文件完整路径。</param>
+        public static void WriteFile(string content, string path)
         {
-            if (File.Exists(path))
+            ValidatePath(path);
+            WriteFileInternal(content, path);
+        }
+
+        /// <summary>
+        /// 读取文本文件,支持自动恢复(从 .bak 或版本化备份恢复)。
+        /// </summary>
+        /// <param name="path">文件路径。</param>
+        /// <param name="autoRecover">可选:覆盖默认的自动恢复行为(null 表示使用配置项)。</param>
+        /// <returns>文件内容字符串。</returns>
+        /// <exception cref="FileNotFoundException">当文件不存在且无法恢复时抛出。</exception>
+        public static string ReadFile(string path, bool? autoRecover = null)
+        {
+            ValidatePath(path);
+
+            bool shouldRecover = autoRecover ?? _options.EnableAutoRecovery;
+
+            // 检查并清理临时文件
+            CheckAndCleanTempFile(path);
+
+            // 尝试读取主文件
+            Exception lastException = null;
+
+            try
             {
-                string buffer;
-                using (StreamReader sr = new StreamReader(path))
+                if (File.Exists(path))
                 {
-                    buffer = sr.ReadToEnd();
+                    return ReadFileWithValidation(path);
                 }
-                return JsonConvert.DeserializeObject<T>(buffer);
             }
-            else
+            catch (Exception ex)
             {
-                throw new Exception(string.Format(Lang.文件不存在0, path));
+                lastException = ex;
+                Log($"读取主文件失败: {ex.Message}");
+
+                if (shouldRecover)
+                {
+                    try
+                    {
+                        // 尝试从备份恢复
+                        string recovered = TryRecoverFile(path);
+                        if (recovered != null)
+                            return recovered;
+                    }
+                    catch (Exception recoveryEx)
+                    {
+                        Log($"恢复尝试失败: {recoveryEx.Message}");
+                    }
+                }
             }
+
+            // 如果文件不存在且允许恢复,尝试从默认备份位置恢复
+            if (shouldRecover && !File.Exists(path))
+            {
+                string recovered = TryFindAndRecoverFile(path);
+                if (recovered != null)
+                    return recovered;
+            }
+
+            throw new FileNotFoundException($"文件 {path} 不存在且无法恢复", lastException);
         }
 
         /// <summary>
-        /// 写入文件
+        /// 在不抛出异常的情况下安全读取文件内容,失败时返回提供的默认值。
         /// </summary>
-        /// <param name="content">对象</param>
-        /// <param name="path">文件路径</param>
-        public static void WriteFile(string content, string path)
+        /// <param name="path">文件路径。</param>
+        /// <param name="defaultValue">读取失败时返回的默认值(可为 null)。</param>
+        /// <returns>文件内容或默认值。</returns>
+        public static string SafeReadFile(string path, string defaultValue = null)
         {
-            if (!Directory.Exists(Path.GetDirectoryName(path)))
+            try
             {
-                Directory.CreateDirectory(Path.GetDirectoryName(path));
+                return ReadFile(path, true);
             }
-            using (StreamWriter sw = new StreamWriter(path))
+            catch
             {
-                sw.Write(content);
+                return defaultValue;
             }
         }
+        #endregion
 
+        #region 文件恢复相关
         /// <summary>
-        /// 读取文件
+        /// 检查并修复指定目录下的所有相关临时文件与备份文件。
+        /// - 恢复或清理 .tmp 文件
+        /// - 清理孤立或过旧的 .bak 文件
+        /// - 清理版本化备份超过保留数量的旧版本
         /// </summary>
-        /// <param name="path"></param>
-        /// <returns></returns>
-        /// <exception cref="Exception"></exception>
-        public static string ReadFile(string path)
+        /// <param name="directoryPath">要检查的目录路径。</param>
+        public static void CheckAndRepairDirectory(string directoryPath)
         {
-            if (File.Exists(path))
+            if (!Directory.Exists(directoryPath))
+                return;
+
+            // 处理临时文件
+            var tempFiles = Directory.GetFiles(directoryPath, "*.tmp", SearchOption.AllDirectories);
+            foreach (var tempFile in tempFiles)
             {
-                string buffer;
-                using (StreamReader sr = new StreamReader(path))
+                TryRecoverFromTempFile(tempFile);
+            }
+
+            // 处理备份文件
+            var backupFiles = Directory.GetFiles(directoryPath, "*.bak", SearchOption.AllDirectories);
+            foreach (var backupFile in backupFiles)
+            {
+                TryCleanOrphanedBackup(backupFile);
+            }
+
+            // 处理版本化备份
+            CleanupOldBackupVersions(directoryPath);
+        }
+
+        /// <summary>
+        /// 强制从备份恢复主文件。优先使用直接的 .bak,其次尝试版本化备份目录中的最新文件。
+        /// </summary>
+        /// <param name="originalPath">原文件路径。</param>
+        /// <returns>成功返回 true,失败返回 false。</returns>
+        public static bool ForceRecoverFile(string originalPath)
+        {
+            try
+            {
+                // 尝试从直接备份恢复
+                string backupPath = originalPath + ".bak";
+                if (File.Exists(backupPath))
+                {
+                    File.Copy(backupPath, originalPath, true);
+                    Log($"从备份强制恢复: {originalPath}");
+                    return true;
+                }
+
+                // 尝试从版本化备份恢复
+                var recovered = TryFindLatestBackup(originalPath);
+                if (recovered != null)
                 {
-                    buffer = sr.ReadToEnd();
+                    File.Copy(recovered, originalPath, true);
+                    Log($"从版本备份强制恢复: {originalPath}");
+                    return true;
                 }
-                return buffer;
+
+                return false;
             }
-            else
+            catch (Exception ex)
             {
-                throw new Exception(string.Format(Lang.文件不存在0, path));
+                Log($"强制恢复失败: {ex.Message}");
+                return false;
             }
         }
+        #endregion
 
+        #region 辅助方法
         /// <summary>
-        /// 检测文件名是否合规
+        /// 检测给定的文件名是否合规(不包含 Windows 文件名禁止字符)。
         /// </summary>
-        /// <param name="filename"></param>
-        /// <returns></returns>
+        /// <param name="filename">仅文件名部分(不含路径)。</param>
+        /// <returns>文件名合法返回 true,否则返回 false。</returns>
         public static bool CheckFileName(string filename)
         {
-            //
+            if (string.IsNullOrWhiteSpace(filename))
+                return false;
+
             // 定义文件名合法性的正则表达式
-            string pattern = @"^[^-\\/:*?""<>|\x00-\x1F]*$"; // 匹配不包含非法字符的文件名
+            string pattern = @"^[^\\/:*?""<>|\x00-\x1F]*$";
+            return Regex.IsMatch(filename, pattern);
+        }
 
-            // 使用正则表达式进行匹配
-            if (Regex.IsMatch(filename, pattern))
+        /// <summary>
+        /// 检查文件是否存在且有效(可读且长度大于 0)。
+        /// </summary>
+        /// <param name="path">文件完整路径。</param>
+        /// <returns>文件存在且有效返回 true,否则返回 false。</returns>
+        public static bool IsFileValid(string path)
+        {
+            try
             {
-                //Console.WriteLine("输入的名称符合文件名命名规则,并且不包含非法字符。");
-                return true;
+                if (!File.Exists(path))
+                    return false;
+
+                // 尝试读取一小部分内容来验证文件可访问性
+                using (var fs = File.OpenRead(path))
+                {
+                    return fs.CanRead && fs.Length > 0;
+                }
             }
-            else
+            catch
             {
-                //Console.WriteLine("输入的名称不符合文件名命名规则,或者包含非法字符。");
                 return false;
             }
         }
+
+        /// <summary>
+        /// 为给定原始路径生成一个安全的临时文件路径(放在系统临时目录),包含随机 GUID 前缀。
+        /// </summary>
+        /// <param name="originalPath">原文件完整路径,用于生成可识别的临时文件名。</param>
+        /// <returns>生成的临时文件完整路径。</returns>
+        public static string GetTempFilePath(string originalPath)
+        {
+            // 尝试放在目标目录(确保同一卷)
+            string dir = Path.GetDirectoryName(originalPath);
+            try
+            {
+                if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir))
+                {
+                    string safeName = Path.GetFileName(originalPath).Replace(" ", "_").Replace(":", "_");
+                    return Path.Combine(dir, $"{Guid.NewGuid():N}_{safeName}.tmp");
+                }
+            }
+            catch
+            {
+                // 忽略并回退到系统临时目录
+            }
+
+            // 回退(极少用到)
+            string tempDir = Path.GetTempPath();
+            string fallbackName = Path.GetFileName(originalPath).Replace(" ", "_").Replace(":", "_");
+            return Path.Combine(tempDir, $"{Guid.NewGuid():N}_{fallbackName}.tmp");
+        }
+        #endregion
+
+        #region 私有实现方法
+        /// <summary>
+        /// 验证路径与文件名合法性(非空且文件名不包含非法字符)。
+        /// </summary>
+        /// <param name="path">要验证的文件路径。</param>
+        private static void ValidatePath(string path)
+        {
+            if (string.IsNullOrWhiteSpace(path))
+                throw new ArgumentException("路径不能为空", nameof(path));
+
+            string fileName = Path.GetFileName(path);
+            if (!CheckFileName(fileName))
+                throw new ArgumentException($"文件名 '{fileName}' 包含非法字符", nameof(path));
+        }
+
+        /// <summary>
+        /// 内部写文件实现:创建目录、可选创建版本化备份、写入临时文件并以原子方式替换目标文件。
+        /// 发生异常时会尝试清理临时文件。
+        /// </summary>
+        /// <param name="content">要写入的文本内容。</param>
+        /// <param name="path">目标文件完整路径。</param>
+        private static void WriteFileInternal(string content, string path)
+        {
+            // 创建目录
+            string directory = Path.GetDirectoryName(path);
+            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
+            {
+                Directory.CreateDirectory(directory);
+            }
+
+            // 创建版本化备份
+            if (_options.KeepBackupFiles && File.Exists(path))
+            {
+                CreateVersionedBackup(path);
+            }
+
+            // 临时文件路径
+            string tempPath = path + ".tmp"; //GetTempFilePath(path);
+
+            try
+            {
+                // 写入临时文件
+                using (var fs = new FileStream(tempPath,
+                    FileMode.Create,
+                    FileAccess.Write,
+                    FileShare.None,
+                    bufferSize: 4096,
+                    useAsync: false))
+                using (var sw = new StreamWriter(fs, _options.FileEncoding))
+                {
+                    sw.Write(content);
+                    sw.Flush();
+                    fs.Flush(true); // 强制刷新到磁盘
+                }
+
+                // 原子性替换
+                if (File.Exists(path))
+                {
+                    string backupPath = path + ".bak";
+                    File.Replace(tempPath, path, backupPath, true);
+
+                    // 如果不保留备份文件,删除它
+                    if (!_options.KeepBackupFiles && File.Exists(backupPath))
+                    {
+                        try { File.Delete(backupPath); } catch { }
+                    }
+                }
+                else
+                {
+                    File.Move(tempPath, path);
+                }
+            }
+            catch
+            {
+                // 清理临时文件
+                SafeDelete(tempPath);
+                throw;
+            }
+            finally
+            {
+                // 确保临时文件被清理
+                SafeDelete(tempPath);
+            }
+        }
+
+        /// <summary>
+        /// 创建版本化备份:将原文件复制到同目录下的备份目录,并带时间戳后缀。
+        /// 发生异常时仅记录日志,不抛出。
+        /// </summary>
+        /// <param name="originalPath">要备份的原文件路径。</param>
+        private static void CreateVersionedBackup(string originalPath)
+        {
+            try
+            {
+                string backupDir = Path.Combine(Path.GetDirectoryName(originalPath), _options.BackupDirectory);
+                if (!Directory.Exists(backupDir))
+                    Directory.CreateDirectory(backupDir);
+
+                string fileName = Path.GetFileNameWithoutExtension(originalPath);
+                string extension = Path.GetExtension(originalPath);
+                string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
+                string backupName = $"{fileName}_{timestamp}{extension}";
+                string backupPath = Path.Combine(backupDir, backupName);
+
+                File.Copy(originalPath, backupPath, true);
+                Log($"创建版本备份: {backupPath}");
+            }
+            catch (Exception ex)
+            {
+                Log($"创建版本备份失败: {ex.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 检查并清理与原文件同名的临时文件(使用 .tmp 后缀的临时文件),并在可能的情况下记录发现的信息。
+        /// </summary>
+        /// <param name="originalPath">原文件完整路径。</param>
+        private static void CheckAndCleanTempFile(string originalPath)
+        {
+            string tempPath = originalPath + ".tmp";
+            if (File.Exists(tempPath))
+            {
+                try
+                {
+                    // 检查临时文件是否较新(可能是中断的写入)
+                    if (File.Exists(originalPath))
+                    {
+                        var originalTime = File.GetLastWriteTime(originalPath);
+                        var tempTime = File.GetLastWriteTime(tempPath);
+
+                        if (tempTime > originalTime)
+                        {
+                            Log($"发现较新的临时文件,可能上次写入未完成: {tempPath}");
+                        }
+                    }
+
+                    File.Delete(tempPath);
+                    Log($"清理临时文件: {tempPath}");
+                }
+                catch (Exception ex)
+                {
+                    Log($"清理临时文件失败: {ex.Message}");
+                }
+            }
+        }
+
+        /// <summary>
+        /// 尝试从直接的 .bak 文件恢复 JSON 文件并返回反序列化的对象;恢复成功后尝试覆盖主文件。
+        /// </summary>
+        /// <typeparam name="T">目标类型。</typeparam>
+        /// <param name="originalPath">原 JSON 文件路径。</param>
+        /// <returns>恢复并反序列化后的对象,失败返回 default(T)。</returns>
+        private static T TryRecoverJsonFile<T>(string originalPath)
+        {
+            // 尝试从直接备份恢复
+            string backupPath = originalPath + ".bak";
+            if (File.Exists(backupPath))
+            {
+                try
+                {
+                    string json = ReadAndValidateJsonFile(backupPath);
+                    T result = JsonConvert.DeserializeObject<T>(json);
+
+                    // 尝试恢复主文件
+                    TryRestoreMainFile(backupPath, originalPath);
+
+                    Log($"从备份恢复Json文件: {originalPath}");
+                    return result;
+                }
+                catch (Exception ex)
+                {
+                    Log($"从备份恢复Json文件失败: {ex.Message}");
+                }
+            }
+
+            return default;
+        }
+
+        /// <summary>
+        /// 尝试从直接的 .bak 文件恢复文本文件并返回内容;恢复成功后尝试覆盖主文件。
+        /// </summary>
+        /// <param name="originalPath">原文件路径。</param>
+        /// <returns>恢复后的内容,失败返回 null。</returns>
+        private static string TryRecoverFile(string originalPath)
+        {
+            // 尝试从直接备份恢复
+            string backupPath = originalPath + ".bak";
+            if (File.Exists(backupPath))
+            {
+                try
+                {
+                    string content = ReadFileWithValidation(backupPath);
+
+                    // 尝试恢复主文件
+                    TryRestoreMainFile(backupPath, originalPath);
+
+                    Log($"从备份恢复文件: {originalPath}");
+                    return content;
+                }
+                catch (Exception ex)
+                {
+                    Log($"从备份恢复文件失败: {ex.Message}");
+                }
+            }
+
+            return null;
+        }
+
+        /// <summary>
+        /// 在版本化备份目录中查找最新的备份并尝试恢复 JSON 文件,成功返回反序列化对象并复制到主文件。
+        /// </summary>
+        /// <typeparam name="T">目标类型。</typeparam>
+        /// <param name="originalPath">原 JSON 文件路径。</param>
+        /// <returns>恢复并反序列化后的对象,失败返回 default(T)。</returns>
+        private static T TryFindAndRecoverJsonFile<T>(string originalPath)
+        {
+            string backup = TryFindLatestBackup(originalPath);
+            if (backup != null)
+            {
+                try
+                {
+                    string json = ReadAndValidateJsonFile(backup);
+                    T result = JsonConvert.DeserializeObject<T>(json);
+
+                    File.Copy(backup, originalPath, true);
+                    Log($"从版本备份恢复Json文件: {originalPath}");
+                    return result;
+                }
+                catch (Exception ex)
+                {
+                    Log($"从版本备份恢复Json文件失败: {ex.Message}");
+                }
+            }
+
+            return default;
+        }
+
+        /// <summary>
+        /// 在版本化备份目录中查找最新的备份并尝试恢复文本文件,成功后复制到主文件并返回内容。
+        /// </summary>
+        /// <param name="originalPath">原文件路径。</param>
+        /// <returns>恢复后的内容,失败返回 null。</returns>
+        private static string TryFindAndRecoverFile(string originalPath)
+        {
+            string backup = TryFindLatestBackup(originalPath);
+            if (backup != null)
+            {
+                try
+                {
+                    string content = ReadFileWithValidation(backup);
+                    File.Copy(backup, originalPath, true);
+                    Log($"从版本备份恢复文件: {originalPath}");
+                    return content;
+                }
+                catch (Exception ex)
+                {
+                    Log($"从版本备份恢复文件失败: {ex.Message}");
+                }
+            }
+
+            return null;
+        }
+
+        /// <summary>
+        /// 查找最新的版本化备份文件路径。优先检查指定的备份目录,其次检查原目录下同名带时间戳的文件。
+        /// </summary>
+        /// <param name="originalPath">原始文件路径。</param>
+        /// <returns>最新备份文件的完整路径或 null(未找到)。</returns>
+        private static string TryFindLatestBackup(string originalPath)
+        {
+            string directory = Path.GetDirectoryName(originalPath);
+            string fileName = Path.GetFileNameWithoutExtension(originalPath);
+            string extension = Path.GetExtension(originalPath);
+
+            if (!Directory.Exists(directory))
+                return null;
+
+            // 检查备份目录
+            string backupDir = Path.Combine(directory, _options.BackupDirectory);
+            if (Directory.Exists(backupDir))
+            {
+                var backups = Directory.GetFiles(backupDir, $"{fileName}_*{extension}")
+                    .OrderByDescending(f => f)
+                    .ToList();
+
+                if (backups.Any())
+                    return backups.First();
+            }
+
+            // 检查当前目录的备份文件
+            var localBackups = Directory.GetFiles(directory, $"{fileName}_*{extension}")
+                .OrderByDescending(f => f)
+                .ToList();
+
+            if (localBackups.Any())
+                return localBackups.First();
+
+            return null;
+        }
+
+        /// <summary>
+        /// 读取文件并在读取后进行 JSON 格式校验(适用于 JSON 文件)。如果格式无效则抛出异常。
+        /// </summary>
+        /// <param name="filePath">文件路径。</param>
+        /// <returns>文件文本内容。</returns>
+        /// <exception cref="InvalidDataException">当 JSON 格式无效时抛出。</exception>
+        private static string ReadAndValidateJsonFile(string filePath)
+        {
+            string json = ReadFileWithValidation(filePath);
+
+            // 验证JSON格式
+            if (!string.IsNullOrWhiteSpace(json))
+            {
+                try
+                {
+                    JToken.Parse(json);
+                }
+                catch (JsonException ex)
+                {
+                    throw new InvalidDataException($"文件 {filePath} 包含无效的JSON格式: {ex.Message}", ex);
+                }
+            }
+
+            return json;
+        }
+
+        /// <summary>
+        /// 读取文件并进行基本验证(文件存在且读取结果非 null)。
+        /// </summary>
+        /// <param name="filePath">文件路径。</param>
+        /// <returns>文件内容字符串。</returns>
+        /// <exception cref="FileNotFoundException">文件不存在时抛出。</exception>
+        /// <exception cref="InvalidDataException">读取结果为 null 时抛出。</exception>
+        private static string ReadFileWithValidation(string filePath)
+        {
+            if (!File.Exists(filePath))
+                throw new FileNotFoundException($"文件不存在: {filePath}");
+
+            string content = File.ReadAllText(filePath, _options.FileEncoding);
+
+            if (content == null)
+                throw new InvalidDataException($"文件 {filePath} 内容为null");
+
+            return content;
+        }
+
+        /// <summary>
+        /// 将备份文件复制回主文件路径以进行恢复,失败时记录日志但不抛出。
+        /// </summary>
+        /// <param name="backupPath">备份文件路径。</param>
+        /// <param name="originalPath">目标主文件路径。</param>
+        private static void TryRestoreMainFile(string backupPath, string originalPath)
+        {
+            try
+            {
+                File.Copy(backupPath, originalPath, true);
+                Log($"恢复主文件: {originalPath}");
+            }
+            catch (Exception ex)
+            {
+                Log($"恢复主文件失败: {ex.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 尝试根据 .tmp 临时文件恢复原文件:如果临时文件较新或原文件不存在则移动临时文件覆盖原文件,否则删除临时文件。
+        /// 出错时尝试安全删除临时文件。
+        /// </summary>
+        /// <param name="tempPath">临时文件路径。</param>
+        private static void TryRecoverFromTempFile(string tempPath)
+        {
+            try
+            {
+                // 获取原文件路径(假设临时文件是 .tmp 扩展名)
+                string originalPath = tempPath.EndsWith(".tmp")
+                    ? tempPath.Substring(0, tempPath.Length - 4)
+                    : tempPath;
+
+                // 如果原文件不存在或临时文件更新,则恢复
+                if (!File.Exists(originalPath) ||
+                    File.GetLastWriteTime(tempPath) > File.GetLastWriteTime(originalPath))
+                {
+                    File.Move(tempPath, originalPath);
+                    Log($"从临时文件恢复: {originalPath}");
+                }
+                else
+                {
+                    File.Delete(tempPath);
+                }
+            }
+            catch
+            {
+                SafeDelete(tempPath);
+            }
+        }
+
+        /// <summary>
+        /// 清理孤立或过旧的 .bak 备份:如果主文件存在且备份比主文件早超过一定时间,则删除备份。
+        /// </summary>
+        /// <param name="backupPath">备份文件路径(通常以 .bak 结尾)。</param>
+        private static void TryCleanOrphanedBackup(string backupPath)
+        {
+            try
+            {
+                string originalPath = backupPath.EndsWith(".bak")
+                    ? backupPath.Substring(0, backupPath.Length - 4)
+                    : backupPath;
+
+                // 如果主文件存在且备份较旧,删除备份
+                if (File.Exists(originalPath))
+                {
+                    var originalTime = File.GetLastWriteTime(originalPath);
+                    var backupTime = File.GetLastWriteTime(backupPath);
+
+                    if (originalTime > backupTime.AddMinutes(5))
+                    {
+                        File.Delete(backupPath);
+                        Log($"清理旧备份: {backupPath}");
+                    }
+                }
+            }
+            catch
+            {
+                // 忽略错误
+            }
+        }
+
+        /// <summary>
+        /// 清理版本化备份目录中超过保留数量的旧版本(按名称分组并按字符串降序保留最新的若干个)。
+        /// </summary>
+        /// <param name="directory">原文件所在目录,该目录下可能包含版本化备份子目录。</param>
+        private static void CleanupOldBackupVersions(string directory)
+        {
+            try
+            {
+                string backupDir = Path.Combine(directory, _options.BackupDirectory);
+                if (!Directory.Exists(backupDir))
+                    return;
+
+                var fileGroups = Directory.GetFiles(backupDir)
+                    .GroupBy(f => Path.GetFileNameWithoutExtension(f).Split('_')[0])
+                    .ToList();
+
+                foreach (var group in fileGroups)
+                {
+                    var backups = group.OrderByDescending(f => f).ToList();
+                    for (int i = _options.MaxBackupVersions; i < backups.Count; i++)
+                    {
+                        SafeDelete(backups[i]);
+                    }
+                }
+            }
+            catch
+            {
+                // 忽略错误
+            }
+        }
+
+        /// <summary>
+        /// 尝试安全删除指定文件,删除失败则忽略异常。
+        /// </summary>
+        /// <param name="filePath">要删除的文件路径。</param>
+        private static void SafeDelete(string filePath)
+        {
+            try
+            {
+                if (File.Exists(filePath))
+                    File.Delete(filePath);
+            }
+            catch
+            {
+                // 忽略删除错误
+            }
+        }
+
+        /// <summary>
+        /// 内部日志方法,只有在配置启用时才会调用 LogHelper 记录调试日志。
+        /// </summary>
+        /// <param name="message">日志消息正文。</param>
+        private static void Log(string message)
+        {
+            if (_options.EnableLogging)
+            {
+                //Console.WriteLine($"[FileHelper] {DateTime.Now:HH:mm:ss} - {message}");
+                LogHelper.WriteLogDebug($"[FileHelper] {DateTime.Now:HH:mm:ss} - {message}");
+            }
+        }
+        #endregion
     }
 }

+ 4 - 2
TeamAAS-VM/Core/FilePath.cs

@@ -71,9 +71,11 @@ namespace TeamAAS_VP.Core
         /// 生产排班参数路径
         /// </summary>
 
-        public static readonly string WorkShiftParamPath = "..//Log//WorkShiftParam.cfg";
+        public static string WorkShiftParamPath = "..//Log//WorkShiftParam.cfg";
 
         // 电批配置路径
-        public static readonly string TorqueReaderConfigurationPath = "..//Config//TorqueReaderConfiguration.cfg";
+        public static string TorqueReaderConfigurationPath = "..//Config//TorqueReaderConfiguration.cfg";
+
+        public static string PickScrewAccuracyAnalyzerrConfigurationPath = "..//Config//PickScrewAccuracyAnalyzerrConfiguration.cfg";
     }
 }

+ 45 - 7
TeamAAS-VM/Core/Management.cs

@@ -960,7 +960,7 @@ namespace TeamAAS_VP.Core
         /// </summary>
         /// <param name="plc"></param>
         /// <param name="isconnected"></param>
-        private void Management_PlcConnectChangedEvent(object sender, bool isconnected)
+        private async void Management_PlcConnectChangedEvent(object sender, bool isconnected)
         {
             IPlc plc = sender as IPlc;
             var sta = Status.FirstOrDefault(s => s.ID == plc.Id);
@@ -974,6 +974,15 @@ namespace TeamAAS_VP.Core
                              sta.Message = $"{plc.Name}{Lang.已连接}";
                              sta.Background = new SolidColorBrush(Colors.Green);
                          }));
+                try
+                {
+                    await WriteSystemParameterToPlcAsync(_configService.GetSystemConfiguration());
+                    await WritePositionToPlcAsync();
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("PLC连接成功时,写入系统参数和点位信息时出错!", ex);
+                }
             }
             else
             {
@@ -1328,7 +1337,7 @@ namespace TeamAAS_VP.Core
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token, null);
+                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token, cameraIndex, null);
                             if (visionResult.IsSucceed)
                             {
                                 //披头偏差
@@ -1395,7 +1404,7 @@ namespace TeamAAS_VP.Core
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token, null);
+                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token, cameraIndex, null);
                             if (visionResult.IsSucceed)
                             {
                                 //披头偏差
@@ -1502,7 +1511,7 @@ namespace TeamAAS_VP.Core
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, null);
+                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, cameraIndex, null);
                             if (visionResult.IsSucceed)
                             {
                                 //是拍一个锁一个还是拍两个点锁所有
@@ -1548,11 +1557,40 @@ namespace TeamAAS_VP.Core
                         {
                             SendTaskMessage(Lang.触发上相机检测拍照, MessageLevel.Debug);
                             //相机的编号
-                            //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.Out_UPCameracheckNum.Address);
+                            Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.Out_UPCameracheckNum.Address);
+                            SendTaskMessage(string.Format(Lang.编号0, cameraIndex), MessageLevel.Info);
 
+                            //视觉流程ID
+                            Guid procedureId = Guid.Empty;
+                            //获取锁付拍照的点位
+                            var pos = currentProduct.CheckCameraPoints.FirstOrDefault(p => p.Number == cameraIndex);
+                            if (pos != null)
+                            {
+                                procedureId = pos.VisionProcessID;
+                            }
 
+                            // 获取流程
+                            var process = _productService.GetCurrentProductProcedureModelById(procedureId);
+                            if (process == null)
+                            {
+                                SendTaskMessage(string.Format("未找到点位:{0}的视觉流程:{1}", cameraIndex, procedureId), MessageLevel.Alarm);
+                                await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)2);
+                                return;
+                            }
 
-                            await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)1);
+                            // 执行视觉任务
+                            var _cts = new CancellationTokenSource();
+                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token, cameraIndex, null);
+                            if (visionResult.IsSucceed)
+                            {
+                                await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)1);
+                                SendTaskMessage($"点位{cameraIndex}检测OK", MessageLevel.Debug);
+                            }
+                            else
+                            {
+                                await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)2);
+                                SendTaskMessage($"点位{cameraIndex}检测NG", MessageLevel.Error);
+                            }
                         }
                         else
                         {
@@ -1967,7 +2005,7 @@ namespace TeamAAS_VP.Core
                                 //plc启用的模式
                                 bool models = plc.ReadNode<bool>(addressConfig.Cam_code_mode.Address);
 
-                                if (models)
+                                if (models && state == 1)
                                 {
                                     //拍照读码
                                     SendTaskMessage(Lang.触发上相机锁附组装拍照, MessageLevel.Debug);

+ 687 - 0
TeamAAS-VM/Core/VisionProFileHelper.cs

@@ -0,0 +1,687 @@
+using Cognex.VisionPro;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core
+{
+    /// <summary>
+    /// VisionPro 文件操作辅助类:提供安全保存、加载、备份、恢复与验证等功能。
+    /// 该类旨在通过临时文件、备份与验证机制减少文件损坏风险并支持自动恢复。
+    /// </summary>
+    public static class VisionProFileHelper
+    {
+        #region 配置选项
+        /// <summary>
+        /// VisionPro 文件处理的配置项。
+        /// - EnableBackup: 是否启用备份机制
+        /// - KeepBackupFiles: 是否保留版本化备份文件(否则仅保留 .bak 临时备份)
+        /// - MaxBackupVersions: 保留的最大版本备份数量(超过则删除最旧)
+        /// - BackupDirectory: 存放版本备份的目录名(相对于原文件所在目录)
+        /// - ValidateAfterSave: 保存后是否验证文件完整性
+        /// </summary>
+        public class VisionProOptions
+        {
+            public bool EnableBackup { get; set; } = true;
+            public bool KeepBackupFiles { get; set; } = false;
+            public int MaxBackupVersions { get; set; } = 3;
+            public string BackupDirectory { get; set; } = "VisionProBackups";
+            public bool ValidateAfterSave { get; set; } = true;
+        }
+
+        private static VisionProOptions _options = new VisionProOptions();
+
+        /// <summary>
+        /// 配置 VisionPro 文件处理选项。
+        /// </summary>
+        /// <param name="configure">用于配置 VisionProOptions 的委托(可为 null)</param>
+        public static void Configure(Action<VisionProOptions> configure)
+        {
+            configure?.Invoke(_options);
+        }
+        #endregion
+
+        #region 安全保存方法
+        /// <summary>
+        /// 安全保存 VisionPro 对象到指定文件路径。
+        /// 实现要点:
+        /// - 支持在保存前根据配置创建版本化备份或 .bak 备份
+        /// - 先保存到临时文件,再进行原子替换(File.Replace 或 File.Move)
+        /// - 可选的保存后验证,验证失败会抛出异常并尝试从备份恢复
+        /// </summary>
+        /// <param name="obj">要保存的 VisionPro 对象(不能为空)</param>
+        /// <param name="filePath">目标文件路径(不能为空或空白)</param>
+        /// <param name="backupEnabled">可选:覆盖全局备份配置</param>
+        /// <returns>成功返回 true,如发生异常会抛出 IOException</returns>
+        public static bool SaveObjectToFileSafe(object obj, string filePath, bool? backupEnabled = null)
+        {
+            if (obj == null)
+                throw new ArgumentNullException(nameof(obj));
+            if (string.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentException("文件路径不能为空", nameof(filePath));
+
+            bool useBackup = backupEnabled ?? _options.EnableBackup;
+
+            // 创建目录(若不存在)
+            string directory = Path.GetDirectoryName(filePath);
+            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
+            {
+                Directory.CreateDirectory(directory);
+            }
+
+            // 生成临时文件路径用于先写入
+            string tempFilePath = GetVisionProTempFilePath(filePath);
+
+            try
+            {
+                // 如果启用备份且目标文件已存在,则创建备份(版本化或延续 .bak 机制)
+                if (useBackup && File.Exists(filePath))
+                {
+                    CreateVisionProBackup(filePath);
+                }
+
+                // 将对象保存到临时文件
+                CogSerializer.SaveObjectToFile(obj, tempFilePath);
+
+                // 可选:验证临时文件的完整性
+                if (_options.ValidateAfterSave && !ValidateVisionProFile(tempFilePath))
+                {
+                    throw new InvalidOperationException("保存的VisionPro文件验证失败");
+                }
+
+                // 原子性替换:如果目标存在使用 File.Replace(可生成 .bak),否则直接移动临时文件
+                if (File.Exists(filePath))
+                {
+                    string backupPath = filePath + ".bak";
+                    File.Replace(tempFilePath, filePath, backupPath, true);
+
+                    // 若配置不保留备份,删除 .bak 文件
+                    if (!_options.KeepBackupFiles && File.Exists(backupPath))
+                    {
+                        SafeDelete(backupPath);
+                    }
+                }
+                else
+                {
+                    File.Move(tempFilePath, filePath);
+                }
+
+                Log($"成功保存VisionPro对象到: {filePath}");
+                return true;
+            }
+            catch (Exception ex)
+            {
+                Log($"保存VisionPro对象失败: {ex.Message}");
+
+                // 尝试从备份恢复(若启用了备份)
+                if (useBackup)
+                {
+                    Log("尝试从备份恢复...");
+                    TryRestoreVisionProFile(filePath);
+                }
+
+                throw new IOException($"保存VisionPro文件失败: {ex.Message}", ex);
+            }
+            finally
+            {
+                // 无论成功与否,尝试清理临时文件
+                SafeDelete(tempFilePath);
+            }
+        }
+
+        /// <summary>
+        /// 安全加载 VisionPro 对象(带自动恢复机制)。
+        /// 尝试加载主文件,若失败并且允许自动恢复则尝试从 .bak 或版本备份恢复。
+        /// </summary>
+        /// <typeparam name="T">目标对象类型</typeparam>
+        /// <param name="filePath">文件路径</param>
+        /// <param name="autoRecover">是否启用自动恢复</param>
+        /// <returns>加载得到的对象(成功),否则抛出 FileNotFoundException</returns>
+        public static T LoadObjectFromFileSafe<T>(string filePath, bool autoRecover = true) where T : class
+        {
+            if (string.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentException("文件路径不能为空", nameof(filePath));
+
+            // 清理可能残留的临时文件
+            CleanVisionProTempFile(filePath);
+
+            // 记录最后一次异常用于抛出上下文
+            Exception lastException = null;
+
+            try
+            {
+                if (File.Exists(filePath))
+                {
+                    var obj = CogSerializer.LoadObjectFromFile(filePath) as T;
+                    if (obj == null)
+                        throw new InvalidCastException($"文件 {filePath} 不是有效的 {typeof(T).Name} 类型");
+
+                    return obj;
+                }
+            }
+            catch (Exception ex)
+            {
+                lastException = ex;
+                Log($"加载主文件失败: {ex.Message}");
+
+                if (autoRecover)
+                {
+                    try
+                    {
+                        // 尝试从 .bak 或其他备份恢复并返回对象
+                        T recovered = TryRecoverVisionProFile<T>(filePath);
+                        if (recovered != null)
+                            return recovered;
+                    }
+                    catch (Exception recoveryEx)
+                    {
+                        Log($"恢复尝试失败: {recoveryEx.Message}");
+                    }
+                }
+            }
+
+            // 如果主文件不存在且允许恢复,尝试查找版本化备份进行恢复
+            if (autoRecover && !File.Exists(filePath))
+            {
+                T recovered = TryFindAndRecoverVisionProFile<T>(filePath);
+                if (recovered != null)
+                    return recovered;
+            }
+
+            throw new FileNotFoundException($"VisionPro文件 {filePath} 不存在且无法恢复", lastException);
+        }
+
+        /// <summary>
+        /// 简化版安全加载:遇到任何异常时返回提供的默认值(不抛出)。
+        /// </summary>
+        public static T SafeLoadObjectFromFile<T>(string filePath, T defaultValue = null) where T : class
+        {
+            try
+            {
+                return LoadObjectFromFileSafe<T>(filePath, true);
+            }
+            catch
+            {
+                return defaultValue;
+            }
+        }
+        #endregion
+
+        #region 恢复和验证方法
+        /// <summary>
+        /// 检查并修复单个 VisionPro 文件:
+        /// - 检查并尝试从临时文件恢复
+        /// - 检查 .bak 备份并在合理时恢复
+        /// - 检查版本化备份并恢复最新的可用版本
+        /// </summary>
+        /// <param name="filePath">要检查的文件路径</param>
+        /// <returns>如果执行了恢复操作返回 true,否则返回 false</returns>
+        public static bool CheckAndRepairVisionProFile(string filePath)
+        {
+            try
+            {
+                // 检查临时文件并尝试恢复
+                string tempPath = filePath + ".vp_tmp";
+                if (File.Exists(tempPath))
+                {
+                    TryRecoverFromVisionProTemp(tempPath);
+                }
+
+                // 检查 .bak 备份(File.Replace 可能产生)
+                string backupPath = filePath + ".bak";
+                if (File.Exists(backupPath))
+                {
+                    // 验证备份文件并在主文件不存在或备份更新时恢复
+                    if (ValidateVisionProFile(backupPath))
+                    {
+                        if (!File.Exists(filePath) ||
+                            File.GetLastWriteTime(backupPath) > File.GetLastWriteTime(filePath))
+                        {
+                            File.Copy(backupPath, filePath, true);
+                            Log($"从备份恢复VisionPro文件: {filePath}");
+                            return true;
+                        }
+                    }
+                }
+
+                // 查找并恢复版本化备份(BackupDirectory 或其他模式)
+                var latestBackup = FindLatestVisionProBackup(filePath);
+                if (latestBackup != null)
+                {
+                    File.Copy(latestBackup, filePath, true);
+                    Log($"从版本备份恢复VisionPro文件: {filePath}");
+                    return true;
+                }
+
+                return false;
+            }
+            catch (Exception ex)
+            {
+                Log($"修复VisionPro文件失败: {ex.Message}");
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// 强制从备份恢复(优先 .bak,然后版本化备份)。
+        /// </summary>
+        /// <param name="filePath">目标文件路径</param>
+        /// <returns>恢复成功返回 true,否则 false</returns>
+        public static bool ForceRecoverVisionProFile(string filePath)
+        {
+            try
+            {
+                // 优先使用 .bak 恢复(如存在且验证通过)
+                string backupPath = filePath + ".bak";
+                if (File.Exists(backupPath) && ValidateVisionProFile(backupPath))
+                {
+                    File.Copy(backupPath, filePath, true);
+                    Log($"强制从备份恢复: {filePath}");
+                    return true;
+                }
+
+                // 否则查找版本化备份并恢复最新可用的
+                var latestBackup = FindLatestVisionProBackup(filePath);
+                if (latestBackup != null)
+                {
+                    File.Copy(latestBackup, filePath, true);
+                    Log($"强制从版本备份恢复: {filePath}");
+                    return true;
+                }
+
+                return false;
+            }
+            catch (Exception ex)
+            {
+                Log($"强制恢复失败: {ex.Message}");
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// 尝试从已知备份恢复主文件(单参数便捷版本)。
+        /// 会检查 .bak 与版本化备份并在找到有效备份时覆盖主文件。
+        /// </summary>
+        private static bool TryRestoreVisionProFile(string filePath)
+        {
+            try
+            {
+                string backupPath = filePath + ".bak";
+                if (File.Exists(backupPath) && ValidateVisionProFile(backupPath))
+                {
+                    File.Copy(backupPath, filePath, true);
+                    Log($"从备份恢复文件: {filePath}");
+                    return true;
+                }
+
+                // 若 .bak 不可用,尝试版本化备份
+                var latestBackup = FindLatestVisionProBackup(filePath);
+                if (latestBackup != null)
+                {
+                    File.Copy(latestBackup, filePath, true);
+                    Log($"从版本备份恢复文件: {filePath}");
+                    return true;
+                }
+
+                return false;
+            }
+            catch (Exception ex)
+            {
+                Log($"恢复文件失败: {ex.Message}");
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// 批量检查并修复目录下所有 .vpp 文件。
+        /// </summary>
+        /// <param name="directoryPath">根目录路径</param>
+        public static void CheckAndRepairDirectory(string directoryPath)
+        {
+            if (!Directory.Exists(directoryPath))
+                return;
+
+            // 查找所有 .vpp 文件(包含子目录)
+            var vppFiles = Directory.GetFiles(directoryPath, "*.vpp", SearchOption.AllDirectories);
+            Log($"开始检查和修复 {vppFiles.Length} 个VisionPro文件...");
+
+            int repairedCount = 0;
+            foreach (var file in vppFiles)
+            {
+                if (CheckAndRepairVisionProFile(file))
+                {
+                    repairedCount++;
+                }
+            }
+
+            Log($"完成检查和修复,共修复 {repairedCount} 个文件");
+        }
+        #endregion
+
+        #region 私有实现方法
+        /// <summary>
+        /// 根据配置创建备份:
+        /// - 若 KeepBackupFiles 为 true,则在指定 BackupDirectory 中创建带时间戳的版本备份并清理旧版本;
+        /// - 若为 false,则不在此方法中处理 .bak(.bak 由 File.Replace 在保存时产生)。
+        /// </summary>
+        /// <param name="originalPath">原文件路径</param>
+        private static void CreateVisionProBackup(string originalPath)
+        {
+            try
+            {
+                if (_options.KeepBackupFiles)
+                {
+                    // 在原文件目录下创建 backupDir(如果不存在)
+                    string backupDir = Path.Combine(Path.GetDirectoryName(originalPath), _options.BackupDirectory);
+                    if (!Directory.Exists(backupDir))
+                        Directory.CreateDirectory(backupDir);
+
+                    string fileName = Path.GetFileNameWithoutExtension(originalPath);
+                    string extension = Path.GetExtension(originalPath);
+                    string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
+                    string backupName = $"{fileName}_{timestamp}{extension}";
+                    string backupPath = Path.Combine(backupDir, backupName);
+
+                    File.Copy(originalPath, backupPath, true);
+                    Log($"创建VisionPro版本备份: {backupPath}");
+
+                    // 清理超过 MaxBackupVersions 的旧备份
+                    CleanupOldVisionProBackups(backupDir, fileName);
+                }
+            }
+            catch (Exception ex)
+            {
+                Log($"创建VisionPro备份失败: {ex.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 生成一个用于临时保存的唯一文件路径(位于系统临时目录)。
+        /// </summary>
+        /// <param name="originalPath">与原文件关联的文件名(用于可读性)</param>
+        /// <returns>临时文件路径</returns>
+        private static string GetVisionProTempFilePath(string originalPath)
+        {
+            return originalPath + ".tmp";
+            //string tempDir = Path.GetTempPath();
+            //string safeName = Path.GetFileName(originalPath)
+            //    .Replace(" ", "_")
+            //    .Replace(":", "_");
+            //return Path.Combine(tempDir, $"vp_{Guid.NewGuid():N}_{safeName}");
+        }
+
+        /// <summary>
+        /// 尝试通过加载文件来验证 VisionPro 文件的完整性(加载失败视为无效)。
+        /// </summary>
+        /// <param name="filePath">要验证的文件路径</param>
+        /// <returns>若能成功加载返回 true,否则 false</returns>
+        private static bool ValidateVisionProFile(string filePath)
+        {
+            try
+            {
+                // 使用 Cognex 的序列化加载验证完整性
+                var obj = CogSerializer.LoadObjectFromFile(filePath);
+                return obj != null;
+            }
+            catch
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// 尝试从 .bak 备份恢复并返回加载的对象(泛型)。
+        /// 若恢复成功同时尝试将备份复制回主文件以保持一致性。
+        /// </summary>
+        private static T TryRecoverVisionProFile<T>(string originalPath) where T : class
+        {
+            string backupPath = originalPath + ".bak";
+            if (File.Exists(backupPath))
+            {
+                try
+                {
+                    var obj = CogSerializer.LoadObjectFromFile(backupPath) as T;
+                    if (obj != null)
+                    {
+                        // 当备份可用时,尝试恢复主文件
+                        TryRestoreVisionProFile(originalPath);
+                        Log($"从备份恢复VisionPro对象: {originalPath}");
+                        return obj;
+                    }
+                }
+                catch (Exception ex)
+                {
+                    Log($"从备份恢复VisionPro对象失败: {ex.Message}");
+                }
+            }
+
+            return default;
+        }
+
+        /// <summary>
+        /// 查找版本化备份并尝试恢复为指定类型,成功时会将备份复制为主文件并返回对象。
+        /// </summary>
+        private static T TryFindAndRecoverVisionProFile<T>(string originalPath) where T : class
+        {
+            var backup = FindLatestVisionProBackup(originalPath);
+            if (backup != null)
+            {
+                try
+                {
+                    var obj = CogSerializer.LoadObjectFromFile(backup) as T;
+                    if (obj != null)
+                    {
+                        File.Copy(backup, originalPath, true);
+                        Log($"从版本备份恢复VisionPro对象: {originalPath}");
+                        return obj;
+                    }
+                }
+                catch (Exception ex)
+                {
+                    Log($"从版本备份恢复VisionPro对象失败: {ex.Message}");
+                }
+            }
+
+            return default;
+        }
+
+        /// <summary>
+        /// 在备份目录和当前目录下查找与原文件对应的最新备份文件路径(按写入时间排序)。
+        /// 支持多种命名模式以提高鲁棒性。
+        /// </summary>
+        private static string FindLatestVisionProBackup(string originalPath)
+        {
+            string directory = Path.GetDirectoryName(originalPath);
+            string fileName = Path.GetFileNameWithoutExtension(originalPath);
+            string extension = Path.GetExtension(originalPath);
+
+            if (!Directory.Exists(directory))
+                return null;
+
+            // 优先检查专用备份目录
+            string backupDir = Path.Combine(directory, _options.BackupDirectory);
+            if (Directory.Exists(backupDir))
+            {
+                var backups = Directory.GetFiles(backupDir, $"{fileName}_*{extension}")
+                    .OrderByDescending(f => File.GetLastWriteTime(f))
+                    .ToList();
+
+                if (backups.Any())
+                    return backups.First();
+            }
+
+            // 检查当前目录中常见的备份命名模式
+            var backupPatterns = new[]
+            {
+                $"{fileName}.*.bak",
+                $"{fileName}_*{extension}",
+                $"{fileName}.backup.*"
+            };
+
+            foreach (var pattern in backupPatterns)
+            {
+                try
+                {
+                    var backups = Directory.GetFiles(directory, pattern)
+                        .OrderByDescending(f => File.GetLastWriteTime(f))
+                        .ToList();
+
+                    if (backups.Any())
+                        return backups.First();
+                }
+                catch
+                {
+                    continue;
+                }
+            }
+
+            return null;
+        }
+
+        /// <summary>
+        /// 恢复主文件的重载版本(从指定备份路径复制到原文件路径)。
+        /// </summary>
+        private static void TryRestoreVisionProFile(string backupPath, string originalPath)
+        {
+            try
+            {
+                File.Copy(backupPath, originalPath, true);
+                Log($"恢复VisionPro主文件: {originalPath}");
+            }
+            catch (Exception ex)
+            {
+                Log($"恢复VisionPro主文件失败: {ex.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 清理与指定原文件可能残留的各种临时文件(本进程或其他异常中断时产生)。
+        /// 支持单个文件名与通配符模式(在系统临时目录下)。
+        /// </summary>
+        /// <param name="originalPath">原文件路径</param>
+        private static void CleanVisionProTempFile(string originalPath)
+        {
+            // 可能的临时文件模式集合
+            var tempPatterns = new[]
+            {
+                originalPath + ".vp_tmp",
+                originalPath + ".tmp",
+                Path.GetTempPath() + $"vp_*_{Path.GetFileName(originalPath)}"
+            };
+
+            foreach (var pattern in tempPatterns)
+            {
+                try
+                {
+                    if (File.Exists(pattern))
+                    {
+                        File.Delete(pattern);
+                        Log($"清理VisionPro临时文件: {pattern}");
+                    }
+                    else if (pattern.Contains("*"))
+                    {
+                        // 通配符处理:删除系统临时目录下匹配的文件
+                        var files = Directory.GetFiles(Path.GetTempPath(), $"vp_*_{Path.GetFileName(originalPath)}");
+                        foreach (var file in files)
+                        {
+                            File.Delete(file);
+                            Log($"清理VisionPro临时文件: {file}");
+                        }
+                    }
+                }
+                catch (Exception ex)
+                {
+                    Log($"清理VisionPro临时文件失败: {ex.Message}");
+                }
+            }
+        }
+
+        /// <summary>
+        /// 尝试从临时文件恢复到主文件(当临时文件完整且主文件缺失或临时文件更可靠时)。
+        /// 若临时文件无效则删除该临时文件。
+        /// </summary>
+        /// <param name="tempPath">临时文件路径(通常以 .vp_tmp 结尾)</param>
+        private static void TryRecoverFromVisionProTemp(string tempPath)
+        {
+            try
+            {
+                string originalPath = tempPath.Replace(".vp_tmp", "");
+
+                // 当主文件不存在或者临时文件验证通过时,尝试恢复
+                if (!File.Exists(originalPath) || ValidateVisionProFile(tempPath))
+                {
+                    if (ValidateVisionProFile(tempPath))
+                    {
+                        File.Move(tempPath, originalPath);
+                        Log($"从临时文件恢复VisionPro文件: {originalPath}");
+                    }
+                    else
+                    {
+                        File.Delete(tempPath);
+                    }
+                }
+            }
+            catch
+            {
+                SafeDelete(tempPath);
+            }
+        }
+
+        /// <summary>
+        /// 清理备份目录中过多的旧版本,保留最新的 _options.MaxBackupVersions 个版本。
+        /// </summary>
+        private static void CleanupOldVisionProBackups(string backupDir, string baseName)
+        {
+            try
+            {
+                var files = Directory.GetFiles(backupDir)
+                    .Where(f => Path.GetFileName(f).StartsWith(baseName + "_"))
+                    .OrderByDescending(f => File.GetLastWriteTime(f))
+                    .ToList();
+
+                for (int i = _options.MaxBackupVersions; i < files.Count; i++)
+                {
+                    SafeDelete(files[i]);
+                }
+            }
+            catch
+            {
+                // 忽略清理错误以避免影响主流程
+            }
+        }
+
+        /// <summary>
+        /// 安全删除文件(吞掉异常),用于清理临时/备份文件时保证不抛出影响主逻辑的异常。
+        /// </summary>
+        private static void SafeDelete(string filePath)
+        {
+            try
+            {
+                if (File.Exists(filePath))
+                    File.Delete(filePath);
+            }
+            catch
+            {
+                // 忽略删除错误
+            }
+        }
+
+        /// <summary>
+        /// 日志记录适配器(当前使用 LogHelper.WriteLogDebug)。
+        /// 可根据项目替换为其它日志实现。
+        /// </summary>
+        /// <param name="message">日志消息</param>
+        private static void Log(string message)
+        {
+            // 这里可以使用你喜欢的日志系统
+            //Console.WriteLine($"[VisionProFileHelper] {DateTime.Now:HH:mm:ss} - {message}");
+            LogHelper.WriteLogDebug($"[VisionProFileHelper] {DateTime.Now:HH:mm:ss} - {message}");
+            // 或者使用:Debug.WriteLine(message);
+            // 或者使用:Logger.Log(message);
+        }
+        #endregion
+    }
+}

+ 3 - 1
TeamAAS-VM/Interfaces/IRemoteCommandService.cs

@@ -255,8 +255,10 @@ namespace TeamAAS_VP.Interfaces
         /// <param name="InputTerminal"></param>
         /// <param name="robotCoord"></param>
         /// <param name="cancellationToken"></param>
+        /// <param name="positionIndex"></param>
+        /// <param name="remark"></param>
         /// <returns></returns>
-        Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken, string remark);
+        Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken, int positionIndex, string remark);
 
         /// <summary>
         /// 执行相机拍照获取单个点位结果,并且返回图像和图形

+ 5 - 0
TeamAAS-VM/Models/PhotoCaptureRecord.cs

@@ -38,6 +38,11 @@ namespace TeamAAS_VP.Models
         [SugarColumn(Length = 255, IsNullable = true)]
         public string ProcessName { get; set; }
 
+        /// <summary>
+        /// λÖñàºÅ
+        /// </summary>
+        public int PositionIndex { get; set; }
+
         /// <summary>
         /// ÊÇ·ñ³É¹¦
         /// </summary>

+ 74 - 0
TeamAAS-VM/Models/Torque/PickDynamicTestResult.cs

@@ -0,0 +1,74 @@
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Models.Torque
+{
+    public class PickDynamicTestResult:BindableBase
+    {
+
+        private int _Index;
+        /// <summary>
+        /// 序号
+        /// </summary>
+        public int Index
+        {
+            get { return _Index; }
+            set { SetProperty(ref _Index, value); }
+        }
+
+        private DateTime _Timestamp;
+        /// <summary>
+        /// 时间戳
+        /// </summary>
+        public DateTime Timestamp
+        {
+            get { return _Timestamp; }
+            set { SetProperty(ref _Timestamp, value); }
+        }
+
+        private bool _IsPickSuccess;
+
+        public bool IsPickSuccess
+        {
+            get { return _IsPickSuccess; }
+            set { SetProperty(ref _IsPickSuccess, value); }
+        }
+
+
+        private float _X_Position;
+        public float X_Position
+        {
+            get { return _X_Position; }
+            set { SetProperty(ref _X_Position, value); }
+        }
+
+        private float _Y_Position;
+        public float Y_Position
+        {
+            get { return _Y_Position; }
+            set { SetProperty(ref _Y_Position, value); }
+        }
+
+
+        private float _Z_Position;
+        public float Z_Position
+        {
+            get { return _Z_Position; }
+            set { SetProperty(ref _Z_Position, value); }
+        }
+
+        private double _CycleTime;
+        /// <summary>
+        /// 单次节拍
+        /// </summary>
+        public double CycleTime
+        {
+            get { return _CycleTime; }
+            set { SetProperty(ref _CycleTime, value); }
+        }
+    }
+}

+ 32 - 0
TeamAAS-VM/Models/Torque/PickScrewAccuracyAnalyzerrConfigModel.cs

@@ -0,0 +1,32 @@
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Models.Torque
+{
+    public class PickScrewAccuracyAnalyzerrConfigModel : BindableBase
+    {
+        private int _MoveSpeed = 100;
+        /// <summary>
+        /// 机器人移动速度
+        /// </summary>
+        public int MoveSpeed
+        {
+            get { return _MoveSpeed; }
+            set { SetProperty(ref _MoveSpeed, value); }
+        }
+        private int _RepeatCount = 10;
+        /// <summary>
+        /// 测试次数
+        /// </summary>
+        public int RepeatCount
+        {
+            get { return _RepeatCount; }
+            set { SetProperty(ref _RepeatCount, value); }
+        }
+    }
+
+}

+ 0 - 3
TeamAAS-VM/Models/Torque/PlcPoint_Torque.cs

@@ -54,9 +54,6 @@ namespace TeamAAS_VP.Models.Torque
             set { SetProperty(ref _Z_Position_Stop, value); }
         }
 
-
-
-
         public PlcPoint_Torque()
         {
             Number = 0;

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

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

+ 6 - 6
TeamAAS-VM/Services/CalibrationService.cs

@@ -170,19 +170,19 @@ namespace TeamAAS_VP.Services
             if (calib.ToolBlock != null)
             {
                 // 已有 ToolBlock,直接保存
-                CogSerializer.SaveObjectToFile(calib.ToolBlock, prcPath);
+                VisionProFileHelper.SaveObjectToFileSafe(calib.ToolBlock, prcPath);
             }
             else
             {
                 // 优先从当前目录加载已有 .vpp 文件,否则尝试从模板加载并保存
                 if (File.Exists(prcPath))
                 {
-                    calib.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                    calib.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(prcPath);
                 }
                 else if (File.Exists("..//Vision Template//Calibration.vpp"))
                 {
-                    calib.ToolBlock = CogSerializer.LoadObjectFromFile("..//Vision Template//Calibration.vpp") as CogToolBlock;
-                    CogSerializer.SaveObjectToFile(calib.ToolBlock, prcPath);
+                    calib.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>("..//Vision Template//Calibration.vpp");
+                    VisionProFileHelper.SaveObjectToFileSafe(calib.ToolBlock, prcPath);
                 }
             }
 
@@ -275,7 +275,7 @@ namespace TeamAAS_VP.Services
                             string prcPath = Path.Combine(FilePath.CalibrationPath, calib.Name, calib.Name + ".vpp");
                             if (File.Exists(prcPath))
                             {
-                                calib.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                                calib.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(prcPath);
                             }
                             _calibrations.Add(calib);
                         }
@@ -309,7 +309,7 @@ namespace TeamAAS_VP.Services
                     if (item.ToolBlock != null)
                     {
                         string prcPath = Path.Combine(folder, item.Name + ".vpp");
-                        CogSerializer.SaveObjectToFile(item.ToolBlock, prcPath);
+                        VisionProFileHelper.SaveObjectToFileSafe(item.ToolBlock, prcPath);
                     }
                 }
                 FileHelper.WriteJsonFile(list, Paths.CalibrationListFilePath);

+ 2 - 1
TeamAAS-VM/Services/ConfigService.cs

@@ -253,7 +253,8 @@ namespace TeamAAS_VP.Services
                 FileHelper.WriteJsonFile(Plcs, ConfigPaths.PlcConfigurationPath);
                 FileHelper.WriteJsonFile(BgCommunicate, ConfigPaths.BgTcpIpConfigurationPath);
                 FileHelper.WriteJsonFile(BgModbusCommunicate, ConfigPaths.BgModbusTcpConfigurationPath);
-                FileHelper.WriteJsonFile(LightControllers, ConfigPaths.ScrewDriverConfigurationPath);
+                FileHelper.WriteJsonFile(FeederClearanceTasks, ConfigPaths.FeederClearanceTasksConfigurationPath);
+                FileHelper.WriteJsonFile(LightControllers, ConfigPaths.LightControllersConfigurationPath);
                 // save screw driver config
                 if (_screwDriverConfig != null)
                     FileHelper.WriteJsonFile(_screwDriverConfig, ConfigPaths.ScrewDriverConfigurationPath);

+ 8 - 8
TeamAAS-VM/Services/ProductService.cs

@@ -461,22 +461,22 @@ namespace TeamAAS_VP.Services
                     }
                     if (item1.ToolBlock != null)
                     {
-                        CogSerializer.SaveObjectToFile(item1.ToolBlock, prcPath);
+                        VisionProFileHelper.SaveObjectToFileSafe(item1.ToolBlock, prcPath);
                     }
                     else
                     {
                         //判断路径下是否存在toolblock
                         if (File.Exists(prcPath))
                         {
-                            item1.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                            item1.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(prcPath);
                         }
                         else
                         {
                             if (File.Exists(TemplateToolBlock))
                             {
                                 //保存模板
-                                item1.ToolBlock = CogSerializer.LoadObjectFromFile(TemplateToolBlock) as CogToolBlock;
-                                CogSerializer.SaveObjectToFile(item1.ToolBlock, prcPath);
+                                item1.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(TemplateToolBlock);
+                                VisionProFileHelper.SaveObjectToFileSafe(item1.ToolBlock, prcPath);
                             }
 
                         }
@@ -527,7 +527,7 @@ namespace TeamAAS_VP.Services
                 foreach (var prc in camera.ProcedureModels)
                 {
                     string prcPath = dir + "//" + camera.Camera + "//" + prc.Name + ".vpp";
-                    prc.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                    prc.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(prcPath);
                 }
             }
 
@@ -1016,16 +1016,16 @@ namespace TeamAAS_VP.Services
             string vpppath= Path.Combine(ProductsRootPath, product.Name, cameraProcedure.Camera, prcname + ".vpp");
             if (File.Exists(vpppath))
             {
-                procedure.ToolBlock = CogSerializer.LoadObjectFromFile(vpppath) as CogToolBlock;
+                procedure.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(vpppath);
             }
             else
             {
                 //如果不存在,则加载一个模板工具
                 if (File.Exists(TemplateToolBlock))
                 {
-                    procedure.ToolBlock = CogSerializer.LoadObjectFromFile(TemplateToolBlock) as CogToolBlock;
+                    procedure.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(TemplateToolBlock);
                     //保存到指定路径
-                    CogSerializer.SaveObjectToFile(procedure.ToolBlock, vpppath);
+                    VisionProFileHelper.SaveObjectToFileSafe(procedure.ToolBlock, vpppath);
                 }
                 else
                 {

+ 17 - 7
TeamAAS-VM/Services/RemoteCommandService.cs

@@ -1765,8 +1765,10 @@ namespace TeamAAS_VP.Services
         /// <param name="InputTerminal"></param>
         /// <param name="robotCoord"></param>
         /// <param name="cancellationToken"></param>
+        /// <param name="positionIndex"></param>
+        /// <param name="remark"></param>
         /// <returns></returns>
-        public async Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken, string remark)
+        public async Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken, int positionIndex, string remark)
         {
             DateTime nowtime = DateTime.Now;
             await SetLightBeforePhoto(procedure);
@@ -1788,7 +1790,7 @@ namespace TeamAAS_VP.Services
                     if (!outputCollection.Contains("Found"))
                     {
                         SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
-                        await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, remark);
+                        await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
                         return (false, 0, 0, 0);
                     }
 
@@ -1802,6 +1804,13 @@ namespace TeamAAS_VP.Services
 
                     SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
 
+                    if (procedure.CalibrationId== Guid.Empty)
+                    {
+                        //没有关联校准时,则执行检测任务
+                        await RecordPhotoCaptureAsync(procedure, robotCoord, true, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
+                        return (true, 0, 0, 0);
+                    }
+
                     // 3. 获取视觉输出结果
                     LogHelper.WriteLogInfo(Lang.开始获取视觉输出结果);
                     //获取相机校准
@@ -1817,20 +1826,20 @@ namespace TeamAAS_VP.Services
                     var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
                     if (!calibResult.IsSucceed)
                     {
-                        await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { 0, 0, 0 }, string.Empty, remark);
+                        await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
                         return (false, 0, 0, 0);
                     }
-                    await RecordPhotoCaptureAsync(procedure, robotCoord,true, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { calibResult.X, calibResult.Y, calibResult.U }, string.Empty, remark);
+                    await RecordPhotoCaptureAsync(procedure, robotCoord,true, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { calibResult.X, calibResult.Y, calibResult.U }, string.Empty, positionIndex, remark);
                     return (true, calibResult.X, calibResult.Y, calibResult.U);
                 }
                 SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
-                await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, remark);
+                await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
                 return (false, 0, 0, 0);
             }
             catch (Exception ex)
             {
                 LogHelper.WriteLogError(Lang.执行相机取图并获取单点位时出错, ex);
-                await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, remark);
+                await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
                 return (false, 0, 0, 0);
             }
             finally
@@ -1849,9 +1858,10 @@ namespace TeamAAS_VP.Services
         /// <param name="pixelPosition"></param>
         /// <param name="absolutePosition"></param>
         /// <param name="imagePath"></param>
+        /// <param name="positionIndex"></param>
         /// <param name="emarks"></param>
         /// <returns></returns>
-        private async Task RecordPhotoCaptureAsync(ProcedureModel procedure, double[] robotCoord, bool isSuccess, double[] pixelPosition, double[] absolutePosition, string imagePath, string emarks)
+        private async Task RecordPhotoCaptureAsync(ProcedureModel procedure, double[] robotCoord, bool isSuccess, double[] pixelPosition, double[] absolutePosition, string imagePath, int positionIndex, string emarks)
         {
             try
             {

+ 2 - 2
TeamAAS-VM/Services/TorqueService.cs

@@ -101,7 +101,7 @@ namespace TeamAAS_VP.Services
             management = _container.Resolve<Management>();
         }
 
-        public async Task<bool> Throw_Screw_Async(IRobot Robot, OpcUaClientPLC plc, PlcAddressConfig addressConfig, TorqueProduceModel PlcPoint)
+        public async Task<bool> Throw_Screw_Async(IRobot Robot, OpcUaClientPLC plc, PlcAddressConfig addressConfig, TorqueProduceModel PlcPoint,float speed = 100)
         {
             List<bool> result = new List<bool>();
             var point = new RPoint()
@@ -111,7 +111,7 @@ namespace TeamAAS_VP.Services
                 Z = PlcPoint.TorquePoints[0].Z_Position_Start,
             };
 
-            result.Add(await plc.WriteNodeAsync(addressConfig.Manu_ZAxis_Velocity.Address, (float)99.0));
+            result.Add(await plc.WriteNodeAsync(addressConfig.Manu_ZAxis_Velocity.Address, speed));
 
             float Z_Distance = -(PlcPoint.TorquePoints[0].Z_Position_Start - PlcPoint.TorquePoints[0].Z_Position_Stop);
 

+ 14 - 1
TeamAAS-VM/TeamAAS-VP.csproj

@@ -530,6 +530,7 @@
       <DependentUpon>FeederSystemParam.xaml</DependentUpon>
     </Compile>
     <Compile Include="Core\StabilityAnalyzer.cs" />
+    <Compile Include="Core\VisionProFileHelper.cs" />
     <Compile Include="Events\MainTabSwitchNotification.cs" />
     <Compile Include="Events\WorkShiftChangedNotification.cs" />
     <Compile Include="Events\WorkShiftUpdateNotification.cs" />
@@ -539,6 +540,8 @@
     <Compile Include="Models\HeadChangeRecord.cs" />
     <Compile Include="Models\NozzleChangeRecord.cs" />
     <Compile Include="Models\NumberStatistics.cs" />
+    <Compile Include="Models\Torque\PickDynamicTestResult.cs" />
+    <Compile Include="Models\Torque\PickScrewAccuracyAnalyzerrConfigModel.cs" />
     <Compile Include="Models\Torque\PlcPoint_Torque.cs" />
     <Compile Include="Models\PhotoCaptureRecord.cs" />
     <Compile Include="Models\ScrewFeederBatchRecord.cs" />
@@ -553,6 +556,7 @@
     </Compile>
     <Compile Include="Services\MesService.cs" />
     <Compile Include="Services\ShiftWatcherService.cs" />
+    <Compile Include="ViewModels\Home\PickScrewAccuracyAnalyzerViewModel.cs" />
     <Compile Include="ViewModels\Product\PlcPointOffserParamsViewModel.cs" />
     <Compile Include="ViewModels\Statistics\HeadChangeRecordQueryViewModel.cs" />
     <Compile Include="ViewModels\Statistics\NozzleChangeRecordQueryViewModel.cs" />
@@ -966,6 +970,9 @@
     <Compile Include="Views\Home\ChangeNozzle.xaml.cs">
       <DependentUpon>ChangeNozzle.xaml</DependentUpon>
     </Compile>
+    <Compile Include="Views\Home\PickScrewAccuracyAnalyzer.xaml.cs">
+      <DependentUpon>PickScrewAccuracyAnalyzer.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Views\Home\ShowVisionRender.xaml.cs">
       <DependentUpon>ShowVisionRender.xaml</DependentUpon>
     </Compile>
@@ -1318,6 +1325,10 @@
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
+    <Page Include="Views\Home\PickScrewAccuracyAnalyzer.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
     <Page Include="Views\Home\ShowVisionRender.xaml">
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
@@ -1580,7 +1591,9 @@
       <LastGenOutput>Lang.Designer.cs</LastGenOutput>
       <SubType>Designer</SubType>
     </EmbeddedResource>
-    <EmbeddedResource Include="Resources\Languages\Lang.zh-TW.resx" />
+    <EmbeddedResource Include="Resources\Languages\Lang.zh-TW.resx">
+      <SubType>Designer</SubType>
+    </EmbeddedResource>
     <None Include="packages.config" />
     <None Include="Properties\Settings.settings">
       <Generator>SettingsSingleFileGenerator</Generator>

+ 3 - 3
TeamAAS-VM/ViewModels/Calibration/CalibrationCameraParamsViewModel.cs

@@ -310,18 +310,18 @@ namespace TeamAAS_VP.ViewModels.Calibration
             }
             if (SelectCalibration.IsCreate && SelectCalibration.ToolBlock == null)
             {
-                SelectCalibration.ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.CalibrationToolblockPath) as CogToolBlock;
+                SelectCalibration.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(FilePath.CalibrationToolblockPath);
             }
             else if (SelectCalibration.ToolBlock == null)
             {
                 string prcPath = FilePath.CalibrationPath + "//" + SelectCalibration.Name + "//" + SelectCalibration.Name + ".vpp";
                 if (File.Exists(prcPath))
                 {
-                    SelectCalibration.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                    SelectCalibration.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(prcPath);
                 }
                 else
                 {
-                    SelectCalibration.ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.CalibrationToolblockPath) as CogToolBlock;
+                    SelectCalibration.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(FilePath.CalibrationToolblockPath);
                 }
             }
             if (SelectCalibration.RobotId != Guid.Empty)

+ 1 - 1
TeamAAS-VM/ViewModels/Calibration/CalibrationHomeViewModel.cs

@@ -184,7 +184,7 @@ namespace TeamAAS_VP.ViewModels.Calibration
                         WaitPhoto = 200,
                         WaitSuction = 200,
                         IsCreate = true,
-                        ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.CalibrationToolblockPath) as CogToolBlock,
+                        ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(FilePath.CalibrationToolblockPath),
                     };
                     NavigationParameters param= new NavigationParameters();
                     param.Add("SelectCalibration", SelectCalibration);

+ 3 - 3
TeamAAS-VM/ViewModels/Calibration/FixedUpCameraFindP0ViewModel.cs

@@ -251,7 +251,7 @@ namespace TeamAAS_VP.ViewModels.Calibration
                 {
                     Directory.CreateDirectory(System.IO.Path.GetDirectoryName(prcPath));
                 }
-                CogSerializer.SaveObjectToFile(ToolBlockEdit.Subject, prcPath);
+                VisionProFileHelper.SaveObjectToFileSafe(ToolBlockEdit.Subject, prcPath);
                 NavigationParameters param = new NavigationParameters();
                 param.Add("SelectCalibration", SelectCalibration);
                 _regionManager.RequestNavigate("CalibrationRegionContext", "CalibrationAuto", param);
@@ -405,11 +405,11 @@ namespace TeamAAS_VP.ViewModels.Calibration
                 string prcPath = FilePath.CalibrationPath + "//" + SelectCalibration.Name + "//" + "FixedUpCameraTool.vpp";
                 if (File.Exists(prcPath))
                 {
-                    ToolBlockEdit.Subject = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                    ToolBlockEdit.Subject = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(prcPath);
                 }
                 else
                 {
-                    ToolBlockEdit.Subject = CogSerializer.LoadObjectFromFile(FilePath.CalibrationToolblockPath) as CogToolBlock;
+                    ToolBlockEdit.Subject = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(FilePath.CalibrationToolblockPath);
                 }
             }
 

+ 451 - 0
TeamAAS-VM/ViewModels/Home/PickScrewAccuracyAnalyzerViewModel.cs

@@ -0,0 +1,451 @@
+using MaterialDesignThemes.Wpf;
+using Newtonsoft.Json;
+using Prism.Commands;
+using Prism.Events;
+using Prism.Ioc;
+using Prism.Mvvm;
+using Prism.Regions;
+using Prism.Services.Dialogs;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Web.UI.WebControls;
+using System.Windows;
+using System.Windows.Threading;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Core.PLCs;
+using TeamAAS_VP.Events;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Models.PLC;
+using TeamAAS_VP.Models.Torque;
+using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.Services;
+using TeamAAS_VP.ViewModels.Product;
+using static TeamAAS_VP.ViewModels.Product.VisionDynamicAccuracyAnalyzerViewModel;
+
+namespace TeamAAS_VP.ViewModels.Home
+{
+    public class PickScrewAccuracyAnalyzerViewModel : BindableBase, IDialogAware
+    {
+        IRegionManager _regionManager;
+        IEventAggregator _eventAggregator;
+        IContainerProvider _container;
+        IDialogService _dialogService;
+        IRobotService _robotService;
+        ISystemDatabaseService _systemDatabaseService;
+        IConfigService _configService;
+        IPlcService _plcService;
+
+        TorqueService _torqueService;
+
+        //测试过程中控制取消的CTS
+        CancellationTokenSource _cts;
+        public PickScrewAccuracyAnalyzerViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container,
+            IDialogService dialogService, IRobotService robotService, ISystemDatabaseService systemDatabaseService,
+            IConfigService configService, TorqueService torqueService, IPlcService plcService)
+        {
+            _eventAggregator = ea;
+            _configService = configService;
+            _container = container;
+            _robotService = robotService;
+            _torqueService = torqueService;
+            _plcService = plcService;
+            management = _container.Resolve<Management>();
+            MessageQueue = new SnackbarMessageQueue(TimeSpan.FromSeconds(2));
+        }
+
+        #region 属性
+
+        private SnackbarMessageQueue _MessageQueue;
+        public SnackbarMessageQueue MessageQueue
+        {
+            get { return _MessageQueue; }
+            set { SetProperty(ref _MessageQueue, value); }
+        }
+
+        private Management _management;
+        public Management management
+        {
+            get { return _management; }
+            set { SetProperty(ref _management, value); }
+        }
+
+        private int _MoveSpeed = 100;
+        /// <summary>
+        /// 移动速度
+        /// </summary>
+        public int MoveSpeed
+        {
+            get { return _MoveSpeed; }
+            set { SetProperty(ref _MoveSpeed, value); }
+        }
+
+        private double _CycleTime;
+        /// <summary>
+        /// 单次的时长
+        /// </summary>
+        public double CycleTime
+        {
+            get { return _CycleTime; }
+            set { SetProperty(ref _CycleTime, value); }
+        }
+
+        private int _RepeatCount = 10;
+        /// <summary>
+        /// 重复次数
+        /// </summary>
+        public int RepeatCount
+        {
+            get { return _RepeatCount; }
+            set { SetProperty(ref _RepeatCount, value); }
+        }
+
+        private int _CurrentProgress;
+        /// <summary>
+        /// 当前进度
+        /// </summary>
+        public int CurrentProgress
+        {
+            get { return _CurrentProgress; }
+            set { SetProperty(ref _CurrentProgress, value); }
+        }
+
+        private int _SuccessCount;
+        /// <summary>
+        /// 成功次数
+        /// </summary>
+        public int SuccessCount
+        {
+            get { return _SuccessCount; }
+            set { SetProperty(ref _SuccessCount, value); }
+        }
+
+        private int _FailCount;
+        /// <summary>
+        /// 失败次数
+        /// </summary>
+        public int FailCount
+        {
+            get { return _FailCount; }
+            set { SetProperty(ref _FailCount, value); }
+        }
+
+        private double _SuccessRate;
+        /// <summary>
+        /// 成功率
+        /// </summary>
+        public double SuccessRate
+        {
+            get { return _SuccessRate; }
+            set { SetProperty(ref _SuccessRate, value); }
+        }
+
+        private string _Message = "等待开始...";
+        public string Message
+        {
+            get { return _Message; }
+            set { SetProperty(ref _Message, value); }
+        }
+
+        private bool _IsRunning;
+
+        public bool IsRunning
+        {
+            get { return _IsRunning; }
+            set { SetProperty(ref _IsRunning, value); }
+        }
+
+        private IRobot _Robot;
+
+        public IRobot Robot
+        {
+            get { return _Robot; }
+            set { SetProperty(ref _Robot, value); }
+        }
+
+        private ObservableCollection<PickDynamicTestResult> _TestResults;
+        /// <summary>
+        /// 测试结果列表
+        /// </summary>
+        public ObservableCollection<PickDynamicTestResult> TestResults
+        {
+            get { return _TestResults; }
+            set { SetProperty(ref _TestResults, value); }
+        }
+
+        private RPoint _PointA = new RPoint();
+
+
+        private TorqueProduceModel _Points;
+
+        public TorqueProduceModel Points
+        {
+            get { return _Points; }
+            set { SetProperty(ref _Points, value); }
+        }
+
+
+        #endregion
+
+        #region 命令
+
+        private DelegateCommand _StopTestCommand;
+        public DelegateCommand StopTestCommand =>
+            _StopTestCommand ?? (_StopTestCommand = new DelegateCommand(() => { _cts?.Cancel(); }, () => IsRunning).ObservesProperty(() => IsRunning));
+
+        //暂停测试命令
+        private DelegateCommand _PauseTestCommand;
+        public DelegateCommand PauseTestCommand =>
+            _PauseTestCommand ?? (_PauseTestCommand = new DelegateCommand(() => { _cts?.Cancel(); }, () => IsRunning).ObservesProperty(() => IsRunning));
+
+        private DelegateCommand _LoadedCommand;
+        public DelegateCommand LoadedCommand =>
+            _LoadedCommand ?? (_LoadedCommand = new DelegateCommand(ExecuteLoadedCommand));
+
+        private DelegateCommand _StartTestCommand;
+        public DelegateCommand StartTestCommand =>
+            _StartTestCommand ?? (_StartTestCommand = new DelegateCommand(ExecuteStartTestCommand).ObservesProperty(() => IsRunning));
+
+        private DelegateCommand _SingleTestCommand;
+        public DelegateCommand SingleTestCommand =>
+            _SingleTestCommand ?? (_SingleTestCommand = new DelegateCommand(ExecuteSingleTestCommand));
+
+        private DelegateCommand _ExportCSVCommand;
+        public DelegateCommand ExportCSVCommand =>
+            _ExportCSVCommand ?? (_ExportCSVCommand = new DelegateCommand(ExecuteExportCSVCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
+
+        private DelegateCommand _ClearDataCommand;
+        public DelegateCommand ClearDataCommand =>
+            _ClearDataCommand ?? (_ClearDataCommand = new DelegateCommand(ExecuteClearDataCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
+
+
+        #endregion
+
+        /// <summary>
+        /// 保存配置
+        /// </summary>
+        private void SaveConfig()
+        {
+            try
+            {
+                var ConfigModel = new PickScrewAccuracyAnalyzerrConfigModel
+                {
+                    RepeatCount = this.RepeatCount,
+                    MoveSpeed = this.MoveSpeed
+                };
+                FileHelper.WriteJsonFile(ConfigModel, FilePath.PickScrewAccuracyAnalyzerrConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存视觉动态精度分析仪配置时出错", ex);
+            }
+        }
+
+        private void ExecuteLoadedCommand()
+        {
+            try
+            {
+                var res = FileHelper.ReadJsonFile<PickScrewAccuracyAnalyzerrConfigModel>(FilePath.PickScrewAccuracyAnalyzerrConfigurationPath);
+                this.RepeatCount = res.RepeatCount;
+                this.MoveSpeed = res.MoveSpeed;
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message);
+            }
+        }
+
+        private void ExecuteSingleTestCommand()
+        {
+
+        }
+
+        private async void ExecuteStartTestCommand()
+        {
+            IsRunning = true;
+            _cts = new CancellationTokenSource();
+            CurrentProgress = 0;
+            SuccessCount = 0;
+            SuccessRate = 0;
+            FailCount = 0;
+            TestResults = new ObservableCollection<PickDynamicTestResult>();
+            Message = "测试进行中...";
+
+            try
+            {
+                PlcAddressConfig addressConfig = _configService.GetPlcAddresses();
+                OpcUaClientPLC plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
+                var result = System.Windows.MessageBox.Show("确定进行连续测试吗?", "提示", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);
+                if (result != System.Windows.MessageBoxResult.Yes)
+                {
+                    return;
+                }
+
+                if (Robot == null || !Robot.IsConnected)
+                {
+                    SendTaskMessage("机器人未连接,无法示教!");
+                    return;
+                }
+                //为机器人设置移动速度
+                await Robot.CalibParameAsync(new PickInfo(), MoveSpeed, 0, false, 0, 0);
+
+                while (CurrentProgress < RepeatCount)
+                {
+                    DateTime startTime = DateTime.Now;
+                    if (_cts.Token.IsCancellationRequested)
+                    {
+                        Message = "测试已取消!";
+                        break;
+                    }
+                    bool isSuccess1 = await _torqueService.Throw_Screw_Async(Robot, plc, addressConfig, Points, MoveSpeed);
+                    if (!isSuccess1)
+                    {
+                        SendTaskMessage("机器人移动到抛料点失败!");
+                        return;
+                    }
+                    if (_cts.Token.IsCancellationRequested)
+                    {
+                        Message = "测试已取消!";
+                        break;
+                    }
+
+                    bool isSuccess2 = await _torqueService.Pick_Screw_Async(Robot, plc, addressConfig, Points);
+                    if (isSuccess2)
+                    {
+                        SuccessCount++;
+                        CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
+                        TestResults.Add(new PickDynamicTestResult()
+                        {
+                            Index = CurrentProgress + 1,
+                            X_Position = Points.TorquePoints[1].X_Position,
+                            Y_Position = Points.TorquePoints[1].Y_Position,
+                            Z_Position = Points.TorquePoints[1].Z_Position_Start,
+                            Timestamp = DateTime.Now,
+                            CycleTime = this.CycleTime,
+                            IsPickSuccess = isSuccess2
+                        });
+                    }
+                    else
+                    {
+                        FailCount++;
+                        CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
+                        TestResults.Add(new PickDynamicTestResult()
+                        {
+                            Index = CurrentProgress + 1,
+                            X_Position = Points.TorquePoints[1].X_Position,
+                            Y_Position = Points.TorquePoints[1].Y_Position,
+                            Z_Position = Points.TorquePoints[1].Z_Position_Start,
+                            Timestamp = DateTime.Now,
+                            CycleTime = this.CycleTime,
+                            IsPickSuccess = isSuccess2
+                        });
+                    }
+                    CurrentProgress++;
+                    SuccessRate = (double)SuccessCount / CurrentProgress * 100;
+                    SendTaskMessage($"测试进行中... {CurrentProgress}/{RepeatCount}");
+                }
+                if (CurrentProgress >= RepeatCount)
+                {
+                    Message = "测试完成!";
+                    await _torqueService.Throw_Screw_Async(Robot, plc, addressConfig, Points, MoveSpeed);
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("取料重复测试时出错!", ex);
+            }
+            finally
+            {
+                IsRunning = false;
+            }
+        }
+
+        public void SendTaskMessage(string msg)
+        {
+            App.Current.Dispatcher.Invoke(() =>
+            {
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg =msg, Duration = 1 });
+            });            
+        }
+
+        private void ExecuteExportCSVCommand()
+        {
+            if (TestResults == null || TestResults.Count == 0)
+            {
+                SendTaskMessage("无测试数据,无法导出。");
+                return;
+            }
+            try
+            {
+                var dlg = new Microsoft.Win32.SaveFileDialog
+                {
+                    DefaultExt = "csv",
+                    Filter = "CSV 文件 (*.csv)|*.csv|所有文件 (*.*)|*.*",
+                    FileName = "TestResults.csv",
+                    Title = "保存测试结果为 CSV"
+                };
+
+                bool? dlgResult = dlg.ShowDialog();
+                if (dlgResult != true)
+                    return;
+
+                string path = dlg.FileName;
+                if (File.Exists(path))
+                {
+                    File.Delete(path);
+                }
+                using (StreamWriter sw = new StreamWriter(path, true))
+                {
+                    //初始化文件,写入标题行
+                    sw.WriteLine("序号,状态,位置X,位置Y,位置Z,循环时间,时间戳");
+                    foreach (var item in TestResults)
+                    {
+                        sw.WriteLine($"{item.Index},{item.IsPickSuccess},{item.X_Position},{item.Y_Position},{item.Z_Position},{item.CycleTime},{item.Timestamp}");
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show("写入数据失败" + ex);
+            }
+        }
+
+
+        private void ExecuteClearDataCommand()
+        {
+            TestResults.Clear();
+        }
+
+        #region 继承
+        public string Title { get; set; } = "动态取料测试";
+
+        public event Action<IDialogResult> RequestClose;
+
+        public bool CanCloseDialog()
+        {
+            return true;
+        }
+
+        public void OnDialogClosed()
+        {
+            SaveConfig();
+        }
+
+        public void OnDialogOpened(IDialogParameters parameters)
+        {
+            if (parameters.ContainsKey("PickScrewPoint") && parameters.ContainsKey("Robot"))
+            {
+                Points = parameters.GetValue<TorqueProduceModel>("PickScrewPoint");
+                Robot = parameters.GetValue<IRobot>("Robot");
+            }
+        }
+        #endregion
+
+    }
+}

+ 32 - 7
TeamAAS-VM/ViewModels/Home/TorqueCheckViewModel.cs

@@ -44,6 +44,8 @@ namespace TeamAAS_VP.ViewModels.Home
         IRobotService _robotService;
         IPlcService _plcService;
         TorqueService _torqueService;
+        IDialogService _dialogService;
+
         float Value { get; set; } = 0;
 
         #region 属性
@@ -168,7 +170,11 @@ namespace TeamAAS_VP.ViewModels.Home
         public ObservableCollection<PlcPoint_Torque> Points
         {
             get { return _Points; }
-            set { SetProperty(ref _Points, value); }
+            set
+            {
+                SetProperty(ref _Points, value);
+                AllProductParameter.TorquePoints = Points;
+            }
         }
 
         private TorqueProduceModel _AllProductParameter = new TorqueProduceModel();
@@ -191,7 +197,7 @@ namespace TeamAAS_VP.ViewModels.Home
                 SetProperty(ref _selectedPointInDataGrid, value);
                 // 可以同步到 SelectPoint 属性
                 SelectedPoint = value;
-                AllProductParameter.TorquePoints = _Points;
+                AllProductParameter.TorquePoints = Points;
             }
         }
 
@@ -246,12 +252,16 @@ namespace TeamAAS_VP.ViewModels.Home
         public DelegateCommand SavePointsCommand =>
             _SavePointsCommand ?? (_SavePointsCommand = new DelegateCommand(ExecuteSavePointsCommand));
 
+        private DelegateCommand _PickScrewTestCommand;
+        public DelegateCommand PickScrewTestCommand =>
+            _PickScrewTestCommand ?? (_PickScrewTestCommand = new DelegateCommand(ExecutePickScrewTestCommand));
+
         #endregion
 
         #region 方法
 
         public TorqueCheckViewModel(IEventAggregator ea, IConfigService configService, TorqueService torqueService,
-            IContainerProvider container, IRobotService robotService, IPlcService plcService)
+            IContainerProvider container, IRobotService robotService, IPlcService plcService, IDialogService dialogService)
         {
             _eventAggregator = ea;
             _configService = configService;
@@ -259,12 +269,9 @@ namespace TeamAAS_VP.ViewModels.Home
             _robotService = robotService;
             _plcService = plcService;
             _torqueService = torqueService;
+            _dialogService = dialogService;
             management = _container.Resolve<Management>();
         }
-        bool CanExecuteDeletePointCommand()
-        {
-            return SelectedPointInDataGrid != null;
-        }
 
         void ExecuteCancelCommand()
         {
@@ -604,6 +611,24 @@ namespace TeamAAS_VP.ViewModels.Home
             }
             return false;
         }
+
+        private void ExecutePickScrewTestCommand()
+        {
+            var param = new DialogParameters();
+            param.Add("PickScrewPoint", AllProductParameter);
+            param.Add("Robot", Robot);
+            _dialogService.ShowDialog("PickScrewAccuracyAnalyzer", param, rst =>
+            {
+                //对话框关闭之后的回调函数,可以在这解析结果。
+                ButtonResult result1 = rst.Result;
+
+                if (result1 == ButtonResult.OK)
+                {
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
+                }
+            });
+        }
+
         #endregion
 
         public string Title { get; set; } = "扭力点检";

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

@@ -280,7 +280,7 @@ namespace TeamAAS_VP.ViewModels
                     var waiting = new WaitingControl();
                     //show the dialog
                     var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
-                    await _productService.LoadProductAsync(product.ID);
+                    _productService.LoadProduct(product.ID);
                     _productService.SetCurrentProduct(product.ID);
                     await management.WritePositionToPlcAsync();
                     if (DialogHost.IsDialogOpen("RootDialog"))

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

@@ -372,7 +372,7 @@ namespace TeamAAS_VP.ViewModels
             Guid productid = _configService.GetSystemConfiguration().LastOpenedProductId;
             if (productid != Guid.Empty)
             {
-                await _productService.LoadProductAsync(productid);
+                _productService.LoadProduct(productid);
                 _productService.SetCurrentProduct(productid);
                 await management.WritePositionToPlcAsync();
             }

+ 12 - 10
TeamAAS-VM/ViewModels/Product/AdvancedProcedureViewModel.cs

@@ -56,11 +56,13 @@ namespace TeamAAS_VP.ViewModels.Product
         public ProcedureModel SelectProcedure
         {
             get { return _SelectProcedure; }
-            set { SetProperty(ref _SelectProcedure, value);
+            set
+            {
+                SetProperty(ref _SelectProcedure, value);
             }
         }
 
-        public CogToolBlockEditV2 ToolBlockEdit { get;set; }
+        public CogToolBlockEditV2 ToolBlockEdit { get; set; }
 
         private IRobot _Robot;
 
@@ -107,7 +109,7 @@ namespace TeamAAS_VP.ViewModels.Product
         public DelegateCommand VisionStaticAccuracyAnalyzerCommand =>
             _VisionStaticAccuracyAnalyzerCommand ?? (_VisionStaticAccuracyAnalyzerCommand = new DelegateCommand(ExecuteVisionStaticAccuracyAnalyzerCommand));
 
-        
+
         #endregion
 
         #region 事件
@@ -115,7 +117,7 @@ namespace TeamAAS_VP.ViewModels.Product
         #endregion
 
         public AdvancedProcedureViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IDialogService dialogService,
-            IFeederService feederService, IRobotService robotService,ICameraService cameraService, ISystemDatabaseService systemDatabaseService)
+            IFeederService feederService, IRobotService robotService, ICameraService cameraService, ISystemDatabaseService systemDatabaseService)
         {
             _regionManager = regionManager;
             _eventAggregator = ea;
@@ -127,7 +129,7 @@ namespace TeamAAS_VP.ViewModels.Product
             _systemDatabaseService = systemDatabaseService;
             //订阅权限登录事件
             _eventAggregator.GetEvent<UserLoginNotification>().Subscribe(LoginChange);
-            
+
         }
 
         #region 方法
@@ -151,7 +153,7 @@ namespace TeamAAS_VP.ViewModels.Product
                 {
                     var management = _container.Resolve<Management>();
                     var Feeder = _feederService.GetFeeder(SelectProcedure.FeederId);
-                    
+
                     if (Feeder.FeederBrand == FeederBrand.AFAG)
                     {
                         _regionManager.RequestNavigate("ProductRegionContext", "AfagFeederParams", param);
@@ -164,7 +166,7 @@ namespace TeamAAS_VP.ViewModels.Product
             }
             catch (Exception ex)
             {
-                LogHelper.WriteLogError(ex.Message,ex);
+                LogHelper.WriteLogError(ex.Message, ex);
             }
         }
 
@@ -203,17 +205,17 @@ namespace TeamAAS_VP.ViewModels.Product
             try
             {
                 SelectProcedure.ToolBlock = ToolBlockEdit.Subject;
-                var image= Camera.Grab();
+                var image = Camera.Grab();
                 if (image != null)
                 {
                     ToolBlockEdit.Subject.Inputs["InputImage"].Value = image;
                     ToolBlockEdit.Subject.Run();
-                    
+
                     Message = $"{Lang.图像采集耗时}:{Camera.TotalTime.TotalMilliseconds.ToString("F2")} ms {Lang.工具运行耗时}:{ToolBlockEdit.Subject.RunStatus.TotalTime.ToString("F2")} ms";
                 }
                 else
                 {
-                    Message=Lang.图像采集失败耗时.Replace("{0}", Camera.TotalTime.TotalMilliseconds.ToString("F2")).Replace("{1}", Camera.ErrorMessage);  
+                    Message = Lang.图像采集失败耗时.Replace("{0}", Camera.TotalTime.TotalMilliseconds.ToString("F2")).Replace("{1}", Camera.ErrorMessage);
                 }
             }
             catch (Exception ex)

+ 203 - 0
TeamAAS-VM/ViewModels/Product/PlcPointParamsViewModel.cs

@@ -30,6 +30,9 @@ using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.Services;
 using TeamAAS_VP.Views.Product;
 using static TeamAAS_VP.ViewModels.Product.AutoCorrectLockPointViewModel;
+using System.IO;
+using System.Xml.Serialization;
+using Microsoft.Win32;
 
 namespace TeamAAS_VP.ViewModels.Product
 {
@@ -352,6 +355,44 @@ namespace TeamAAS_VP.ViewModels.Product
 
         #endregion
 
+        #region DTOs for import/export
+        public class ProductPointsExport
+        {
+            /// <summary>
+            /// 软件版本号
+            /// </summary>
+            public string SoftwareVersion { get; set; }
+
+            /// <summary>
+            /// 产品名称
+            /// </summary>
+            public string ProductName { get; set; }
+
+            /// <summary>
+            /// 产品描述
+            /// </summary>
+            public string ProductDescription { get; set; }
+
+            /// <summary>
+            /// 设备名称
+            /// </summary>
+            public string DeviceName { get; set; }
+
+            /// <summary>
+            /// 创建日期
+            /// </summary>
+            public DateTime? Created { get; set; }
+
+            public List<PlcPoint> PickCameraPoints { get; set; }
+            public List<PlcPoint> PickPoints { get; set; }
+            public List<PlcPoint> SecPosCameraPoints { get; set; }
+            public List<PlcPoint> ScrewCameraPoints { get; set; }
+            public List<PlcPoint> ScrewPoints { get; set; }
+            public List<PlcPoint> QrCodePoints { get; set; }
+            public List<PlcPoint> CheckCameraPoints { get; set; }
+        }
+        #endregion
+
         #region 命令
         private DelegateCommand _NextCommand;
         public DelegateCommand NextCommand =>
@@ -456,6 +497,14 @@ namespace TeamAAS_VP.ViewModels.Product
         public DelegateCommand SetOffsetCommand =>
             _SetOffsetCommand ?? (_SetOffsetCommand = new DelegateCommand(ExecuteSetOffsetCommand));
 
+        private DelegateCommand _ImportPointsCommand;
+        public DelegateCommand ImportPointsCommand =>
+            _ImportPointsCommand ?? (_ImportPointsCommand = new DelegateCommand(ExecuteImportPointsCommand));
+
+        private DelegateCommand _ExportAllPointsCommand;
+        public DelegateCommand ExportAllPointsCommand =>
+            _ExportAllPointsCommand ?? (_ExportAllPointsCommand = new DelegateCommand(ExecuteExportAllPointsCommand));
+
 
         #endregion
 
@@ -1679,6 +1728,160 @@ namespace TeamAAS_VP.ViewModels.Product
 
             });
         }
+
+        /// <summary>
+        /// 导出所有点位到本地文件(XML)
+        /// </summary>
+        void ExecuteExportAllPointsCommand()
+        {
+            try
+            {
+                if (SelectProduct == null)
+                {
+                    MessageBox.Show("未选择产品", Lang.错误, MessageBoxButton.OK, MessageBoxImage.Warning);
+                    return;
+                }
+
+                var dlg = new SaveFileDialog();
+                dlg.Filter = "Plc Product Points File|*.plcproductpoints.xml|All files|*.*";
+                dlg.FileName = SelectProduct != null ? ($"{SelectProduct.Name}_allpoints_{DateTime.Now:yyyyMMdd_HHmmss}.plcproductpoints.xml") : ($"product_points_{DateTime.Now:yyyyMMdd_HHmmss}.plcproductpoints.xml");
+                var res = dlg.ShowDialog();
+                if (res != true) return;
+
+                var filePath = dlg.FileName;
+                // 构建导出对象
+                var export = new ProductPointsExport
+                {
+                    SoftwareVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),
+                    ProductName = SelectProduct.Name,
+                    ProductDescription = SelectProduct.Description,
+                    DeviceName=_configService.GetDeviceInfo().Station,
+                    Created= DateTime.Now,
+                    PickCameraPoints = SelectProduct.PickCameraPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    PickPoints = SelectProduct.PickPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    SecPosCameraPoints = SelectProduct.SecPosCameraPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    ScrewCameraPoints = SelectProduct.ScrewCameraPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    ScrewPoints = SelectProduct.ScrewPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    QrCodePoints = SelectProduct.QrCodePoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    CheckCameraPoints = SelectProduct.CheckCameraPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>()
+                };
+
+                var serializer = new XmlSerializer(typeof(ProductPointsExport));
+                using (var fs = File.Create(filePath))
+                {
+                    serializer.Serialize(fs, export);
+                }
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = "导出完成", Duration = 1 });
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("导出点位时出错", ex);
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
+            }
+        }
+
+        /// <summary>
+        /// 导入点位文件,覆盖当前点位
+        /// </summary>
+        void ExecuteImportPointsCommand()
+        {
+            try
+            {
+                var dlg = new OpenFileDialog();
+                dlg.Filter = "Plc Points File|*.plcproductpoints.xml|All files|*.*";
+                var res = dlg.ShowDialog();
+                if (res != true) return;
+                var filePath = dlg.FileName;
+
+                // 验证并读取文件(ProductPointsExport)
+                var serializer = new XmlSerializer(typeof(ProductPointsExport));
+                ProductPointsExport import = null;
+                using (var fs = File.OpenRead(filePath))
+                {
+                    try
+                    {
+                        import = (ProductPointsExport)serializer.Deserialize(fs);
+                    }
+                    catch (Exception ex)
+                    {
+                        MessageBox.Show("无效的点位文件或文件已损坏", Lang.错误, MessageBoxButton.OK, MessageBoxImage.Error);
+                        LogHelper.WriteLogError("导入点位文件解析失败", ex);
+                        return;
+                    }
+                }
+
+                if (import == null)
+                {
+                    MessageBox.Show("导入的点位文件为空", Lang.提示, MessageBoxButton.OK, MessageBoxImage.Information);
+                    return;
+                }
+
+                // 提示用户是否覆盖
+                if (MessageBox.Show("确认要导入点位文件并覆盖当前所有点位吗", "导入点位", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
+                {
+                    return;
+                }
+
+                // 覆盖 SelectProduct 下的各类点集合
+                SelectProduct.PickCameraPoints = new ObservableCollection<PlcPoint>(import.PickCameraPoints ?? new List<PlcPoint>());
+                SelectProduct.PickPoints = new ObservableCollection<PlcPoint>(import.PickPoints ?? new List<PlcPoint>());
+                SelectProduct.SecPosCameraPoints = new ObservableCollection<PlcPoint>(import.SecPosCameraPoints ?? new List<PlcPoint>());
+                SelectProduct.ScrewCameraPoints = new ObservableCollection<PlcPoint>(import.ScrewCameraPoints ?? new List<PlcPoint>());
+                SelectProduct.ScrewPoints = new ObservableCollection<PlcPoint>(import.ScrewPoints ?? new List<PlcPoint>());
+                SelectProduct.QrCodePoints = new ObservableCollection<PlcPoint>(import.QrCodePoints ?? new List<PlcPoint>());
+                SelectProduct.CheckCameraPoints = new ObservableCollection<PlcPoint>(import.CheckCameraPoints ?? new List<PlcPoint>());
+
+                // 重新编号每个集合
+                Action<ObservableCollection<PlcPoint>> renumber = (col) =>
+                {
+                    for (int i = 0; i < col.Count; i++) col[i].Number = i + 1;
+                };
+                renumber(SelectProduct.PickCameraPoints);
+                renumber(SelectProduct.PickPoints);
+                renumber(SelectProduct.SecPosCameraPoints);
+                renumber(SelectProduct.ScrewCameraPoints);
+                renumber(SelectProduct.ScrewPoints);
+                renumber(SelectProduct.QrCodePoints);
+                renumber(SelectProduct.CheckCameraPoints);
+
+                // 根据当前 SelectedIndex 切换 Points 绑定到对应集合
+                switch (SelectedIndex)
+                {
+                    case 0:
+                        Points = SelectProduct.PickCameraPoints;
+                        break;
+                    case 1:
+                        Points = SelectProduct.PickPoints;
+                        break;
+                    case 2:
+                        Points = SelectProduct.SecPosCameraPoints;
+                        break;
+                    case 3:
+                        Points = SelectProduct.ScrewCameraPoints;
+                        break;
+                    case 4:
+                        Points = SelectProduct.ScrewPoints;
+                        break;
+                    case 5:
+                        Points = SelectProduct.CheckCameraPoints;
+                        break;
+                    case 6:
+                        Points = SelectProduct.QrCodePoints;
+                        break;
+                    default:
+                        Points = SelectProduct.PickCameraPoints;
+                        break;
+                }
+                
+                LogHelper.WriteLogDebug("导入点位文件成功");
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = "导入完成", Duration = 1 });
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("导入点位时出错", ex);
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
+            }
+        }
         #endregion
 
         #region 继承

+ 3 - 3
TeamAAS-VM/ViewModels/Product/ProcessBasicsViewModel.cs

@@ -316,18 +316,18 @@ namespace TeamAAS_VP.ViewModels.Product
 
                 //if (SelectProduct.IsCreate && SelectProcedure.ToolBlock == null)
                 //{
-                //    SelectProcedure.ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.SimpleProcedurePath) as CogToolBlock; 
+                //    SelectProcedure.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe(FilePath.SimpleProcedurePath) as CogToolBlock; 
                 //}
                 //else if (SelectProcedure.ToolBlock == null)
                 //{
                 //    string prcPath = FilePath.ProductsPath + "//" + SelectProduct.Name + "//" + SelectProcedure.CameraName + "//" + SelectProcedure.Name + ".vpp";
                 //    if (File.Exists(prcPath))
                 //    {
-                //        SelectProcedure.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                //        SelectProcedure.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe(prcPath) as CogToolBlock;
                 //    }
                 //    else
                 //    {
-                //        SelectProcedure.ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.SimpleProcedurePath) as CogToolBlock;
+                //        SelectProcedure.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe(FilePath.SimpleProcedurePath) as CogToolBlock;
                 //    }
                 //}
 

+ 2 - 2
TeamAAS-VM/ViewModels/Product/ProductProcessManageViewModel.cs

@@ -217,7 +217,7 @@ namespace TeamAAS_VP.ViewModels.Product
                                 IsExcludeNearPoint=false,
                                 ExcludeNearPointThreshol=1,
                                 OutputSeparator=";",
-                                ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.SimpleProcedurePath) as CogToolBlock,
+                                ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(FilePath.SimpleProcedurePath),
                                 FeederFindFrequency = new FeederFrequencyModel(11)
                             };
                             var waiting = new WaitingControl();
@@ -225,7 +225,7 @@ namespace TeamAAS_VP.ViewModels.Product
                             var task = DialogHost.Show(waiting, "RootDialog", null, null, null);
                             await Task.Run(() =>
                             {
-                                procedureModel.ToolBlock = CogSerializer.LoadObjectFromFile(ProductService.TemplateToolBlock) as CogToolBlock;
+                                procedureModel.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(ProductService.TemplateToolBlock);
                             });
                             if (DialogHost.IsDialogOpen("RootDialog"))
                             {

+ 27 - 2
TeamAAS-VM/ViewModels/Statistics/PhotoCaptureQueryViewModel.cs

@@ -150,10 +150,25 @@ namespace TeamAAS_VP.ViewModels.Statistics
                 var path = dlg.FileName;
                 using (var sw = new StreamWriter(path, false, Encoding.UTF8))
                 {
-                    sw.WriteLine("CaptureTime,RecipeName,CameraName,ProductSN,Result,ImagePath");
+                    sw.WriteLine("Id,CaptureTime,RecipeName,ProcessName,CameraName,ProductSN,PositionIndex,IsSuccess,RobotPosition,PixelPosition,AbsolutePosition,ImagePath,OperatorName,Remarks");
                     foreach (var r in all)
                     {
-                        sw.WriteLine($"{r.CaptureTime:yyyy-MM-dd HH:mm:ss},{r.RecipeName},{r.CameraName},{r.ProductSN},{r.IsSuccess},{r.ImagePath}");
+                        sw.WriteLine(string.Join(",",
+                            EscapeCsv(r.Id.ToString()),
+                            EscapeCsv(r.CaptureTime.ToString("yyyy-MM-dd HH:mm:ss")),
+                            EscapeCsv(r.RecipeName),
+                            EscapeCsv(r.ProcessName),
+                            EscapeCsv(r.CameraName),
+                            EscapeCsv(r.ProductSN),
+                            EscapeCsv(r.PositionIndex.ToString()),
+                            EscapeCsv(r.IsSuccess ? "1" : "0"),
+                            EscapeCsv(r.RobotPosition),
+                            EscapeCsv(r.PixelPosition),
+                            EscapeCsv(r.AbsolutePosition),
+                            EscapeCsv(r.ImagePath),
+                            EscapeCsv(r.OperatorName),
+                            EscapeCsv(r.Remarks)
+                        ));
                     }
                 }
             }
@@ -162,5 +177,15 @@ namespace TeamAAS_VP.ViewModels.Statistics
                 MessageBox.Show(ex.Message, "´íÎó", MessageBoxButton.OK, MessageBoxImage.Error);
             }
         }
+
+        private string EscapeCsv(string s)
+        {
+            if (s == null) return "";
+            if (s.Contains(",") || s.Contains("\"") || s.Contains("\r") || s.Contains("\n"))
+            {
+                return "\"" + s.Replace("\"", "\"\"") + "\"";
+            }
+            return s;
+        }
     }
 }

+ 28 - 8
TeamAAS-VM/ViewModels/Statistics/ProductionRecordQueryViewModel.cs

@@ -2,6 +2,7 @@ using Prism.Commands;
 using Prism.Mvvm;
 using System;
 using System.Collections.ObjectModel;
+using System.Globalization;
 using System.IO;
 using System.Linq;
 using System.Text;
@@ -108,19 +109,27 @@ namespace TeamAAS_VP.ViewModels.Statistics
         {
             try
             {
-                var start = StartDate.HasValue ? StartDate.Value.Date : DateTime.MinValue;
-                var end = EndDate.HasValue ? EndDate.Value.Date.AddDays(1) : DateTime.MaxValue;
-                string productName = SelectedProduct?.Name;
-                var resAll = await _systemDatabaseService.GetProductionStatsAsync(new ProductionStatQuery { ProductName = productName, Start = start, End = end, GroupBy = "total" });
-                var saveFileDialog = new Microsoft.Win32.SaveFileDialog { FileName = $"Production_{DateTime.Now:yyyyMMddHHmmss}.csv", DefaultExt = ".csv", Filter = "CSV Files (*.csv)|*.csv" };
+                // Export current page Results (paged) to CSV including all ProductionRecord fields
+                var saveFileDialog = new Microsoft.Win32.SaveFileDialog { FileName = $"ProductionRecords_{DateTime.Now:yyyyMMddHHmmss}.csv", DefaultExt = ".csv", Filter = "CSV Files (*.csv)|*.csv" };
                 if (saveFileDialog.ShowDialog() != true) return;
                 var path = saveFileDialog.FileName;
                 using (var sw = new StreamWriter(path, false, Encoding.UTF8))
                 {
-                    sw.WriteLine("PeriodStart,PeriodEnd,Quantity,ProductName");
-                    foreach (var r in resAll)
+                    sw.WriteLine("Id,Timestamp,ProductName,ProductCode,DeviceId,DeviceName,Category,Quantity,UserName,Remark");
+                    foreach (var r in Results)
                     {
-                        sw.WriteLine($"{r.PeriodStart:yyyy-MM-dd HH:mm:ss},{r.PeriodEnd:yyyy-MM-dd HH:mm:ss},{r.Quantity},{r.ProductName}");
+                        sw.WriteLine(string.Join(",",
+                            EscapeCsv(r.Id.ToString()),
+                            EscapeCsv(r.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")),
+                            EscapeCsv(r.ProductName),
+                            EscapeCsv(r.ProductCode),
+                            EscapeCsv(r.DeviceId.ToString()),
+                            EscapeCsv(r.DeviceName),
+                            EscapeCsv(r.Category),
+                            EscapeCsv(r.Quantity.ToString()),
+                            EscapeCsv(r.UserName),
+                            EscapeCsv(r.Remark)
+                        ));
                     }
                 }
             }
@@ -128,6 +137,7 @@ namespace TeamAAS_VP.ViewModels.Statistics
             {
                 MessageBox.Show(ex.Message, "´íÎó", MessageBoxButton.OK, MessageBoxImage.Error);
             }
+            await Task.CompletedTask;
         }
 
         private async void LoadCategoriesForProduct(string productName)
@@ -143,5 +153,15 @@ namespace TeamAAS_VP.ViewModels.Statistics
             }
             catch { }
         }
+
+        private string EscapeCsv(string s)
+        {
+            if (s == null) return "";
+            if (s.Contains(",") || s.Contains("\"") || s.Contains("\r") || s.Contains("\n"))
+            {
+                return "\"" + s.Replace("\"", "\"\"") + "\"";
+            }
+            return s;
+        }
     }
 }

+ 471 - 0
TeamAAS-VM/Views/Home/PickScrewAccuracyAnalyzer.xaml

@@ -0,0 +1,471 @@
+<UserControl x:Class="TeamAAS_VP.Views.Home.PickScrewAccuracyAnalyzer"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:prism="http://prismlibrary.com/"
+             xmlns:wf="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:vm="clr-namespace:TeamAAS_VP.ViewModels.Product"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DataContext="{d:DesignInstance Type=vm:VisionDynamicAccuracyAnalyzerViewModel}"
+             d:Height="1100"
+             d:Width="1000"
+             MinHeight="500"
+             MinWidth="500"
+             d:Background="White"
+             HorizontalAlignment="Stretch"
+             VerticalAlignment="Stretch"
+             FontFamily="{DynamicResource DefaultFont}">
+    <b:Interaction.Triggers>
+        <b:EventTrigger EventName="Loaded">
+            <b:InvokeCommandAction Command="{Binding LoadedCommand}" />
+        </b:EventTrigger>
+    </b:Interaction.Triggers>
+    <prism:Dialog.WindowStyle>
+        <Style TargetType="Window">
+            <Setter Property="prism:Dialog.WindowStartupLocation"
+                    Value="CenterScreen" />
+            <Setter Property="AllowDrop"
+                    Value="True" />
+            <Setter Property="ShowInTaskbar"
+                    Value="True" />
+            <Setter Property="MinHeight"
+                    Value="500" />
+            <Setter Property="MinWidth"
+                    Value="500" />
+            <Setter Property="WindowState"
+                    Value="Normal" />
+            <Setter Property="Topmost"
+                    Value="False" />
+        </Style>
+    </prism:Dialog.WindowStyle>
+
+    <UserControl.Resources>
+        <!-- 复用静态测试的样式 -->
+        <Style TargetType="Button"
+               BasedOn="{StaticResource MaterialDesignFlatDarkBgButton}">
+            <Setter Property="Padding"
+                    Value="10 5" />
+            <Setter Property="Margin"
+                    Value="5" />
+            <Setter Property="FontSize"
+                    Value="14" />
+            <Setter Property="BorderThickness"
+                    Value="0" />
+        </Style>
+
+        <Style TargetType="TextBlock">
+            <Setter Property="VerticalAlignment"
+                    Value="Center" />
+            <Setter Property="Margin"
+                    Value="5" />
+        </Style>
+
+        <Style TargetType="TextBox"
+               BasedOn="{StaticResource MaterialDesignTextBox}">
+            <Setter Property="Margin"
+                    Value="5" />
+            <Setter Property="VerticalContentAlignment"
+                    Value="Center" />
+        </Style>
+
+        <Style x:Key="DataGridStyle"
+               TargetType="DataGrid"
+               BasedOn="{StaticResource MaterialDesignDataGrid}">
+            <Setter Property="Margin"
+                    Value="5" />
+            <Setter Property="AutoGenerateColumns"
+                    Value="False" />
+            <Setter Property="CanUserAddRows"
+                    Value="False" />
+            <Setter Property="CanUserDeleteRows"
+                    Value="False" />
+            <Setter Property="IsReadOnly"
+                    Value="True" />
+            <Setter Property="AlternatingRowBackground"
+                    Value="#F5F5F5" />
+        </Style>
+
+        <Style x:Key="TitleStyle"
+               TargetType="TextBlock">
+            <Setter Property="FontSize"
+                    Value="16" />
+            <Setter Property="FontWeight"
+                    Value="Bold" />
+            <Setter Property="Margin"
+                    Value="0 10 0 5" />
+            <Setter Property="Foreground"
+                    Value="#2C3E50" />
+        </Style>
+    </UserControl.Resources>
+    <Grid>
+        <ScrollViewer>
+            <Border Grid.Column="0"
+                    BorderBrush="#BDC3C7"
+                    BorderThickness="0 0 1 0">
+                <Grid>
+                    <Grid.RowDefinitions>
+                        <RowDefinition Height="Auto" />
+                        <RowDefinition Height="Auto" />
+                        <RowDefinition Height="Auto" />
+                        <RowDefinition Height="Auto" />
+                        <RowDefinition Height="*"
+                                       MinHeight="150" />
+                        <RowDefinition Height="Auto" />
+                    </Grid.RowDefinitions>
+
+                    <!-- 机器人位置 -->
+                    <Border Grid.Row="0"
+                            Background="#ECF0F1"
+                            Padding="10">
+                        <StackPanel>
+                            <TextBlock Style="{StaticResource TitleStyle}"
+                                       Text="机器人位置" />
+
+                            <Grid Margin="0 10 0 0">
+                                <Grid.RowDefinitions>
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                </Grid.RowDefinitions>
+
+                                <Grid Grid.Row="0"
+                                      Margin="0 0 0 10">
+                                    <Grid.ColumnDefinitions>
+                                        <ColumnDefinition Width="Auto" />
+                                        <ColumnDefinition Width="*" />
+                                        <ColumnDefinition Width="Auto" />
+                                    </Grid.ColumnDefinitions>
+
+                                    <TextBlock Text="取料坐标:"
+                                               Grid.Column="0"
+                                               VerticalAlignment="Center" />
+                                    <TextBox Grid.Column="1"
+                                             d:Text="X:0.000 Y:0.000 Z:0.000"
+                                             ToolTip="机器人A点位置坐标"
+                                             IsReadOnly="True"
+                                             Background="#F8F9FA">
+                                        <TextBox.Text>
+                                            <MultiBinding StringFormat="X:{0:f3} Y:{1:f3} Z:{2:f3}">
+                                                <Binding Path="Points.TorquePoints[1].X_Position" />
+                                                <Binding Path="Points.TorquePoints[1].Y_Position" />
+                                                <Binding Path="Points.TorquePoints[1].Z_Position_Start" />
+                                            </MultiBinding>
+                                        </TextBox.Text>
+                                    </TextBox>
+                                    <!--<Button Grid.Column="2"
+                                            Content="示教"
+                                            Command="{Binding TeachPointACommand}"
+                                            Background="#3498DB"
+                                            Foreground="White"
+                                            Width="60"
+                                            Margin="5,0,0,0" />-->
+                                </Grid>
+
+                                <Grid Grid.Row="1"
+                                      Margin="0 0 0 10">
+                                    <Grid.ColumnDefinitions>
+                                        <ColumnDefinition Width="Auto" />
+                                        <ColumnDefinition Width="*" />
+                                        <ColumnDefinition Width="Auto" />
+                                    </Grid.ColumnDefinitions>
+
+                                    <TextBlock Text="抛料坐标:"
+                                               Grid.Column="0"
+                                               VerticalAlignment="Center" />
+                                    <TextBox Grid.Column="1"
+                                             d:Text="X:100.000 Y:50.000 Z:0.000"
+                                             ToolTip="机器人B点拍照位置坐标"
+                                             IsReadOnly="True"
+                                             Background="#F8F9FA">
+                                        <TextBox.Text>
+                                            <MultiBinding StringFormat="X:{0:f3} Y:{1:f3} Z:{2:f3}">
+                                                <Binding Path="Points.TorquePoints[0].X_Position" />
+                                                <Binding Path="Points.TorquePoints[0].Y_Position" />
+                                                <Binding Path="Points.TorquePoints[0].Z_Position_Start" />
+                                            </MultiBinding>
+                                        </TextBox.Text>
+                                    </TextBox>
+                                    <!--<Button Grid.Column="2"
+                                            Content="示教"
+                                            Command="{Binding TeachPointBCommand}"
+                                            Background="#3498DB"
+                                            Foreground="White"
+                                            Width="60"
+                                            Margin="5,0,0,0" />-->
+                                </Grid>
+                            </Grid>
+                        </StackPanel>
+                    </Border>
+
+                    <!-- 测试参数设置 -->
+                    <Border Grid.Row="1"
+                            Background="#F8F9FA"
+                            Padding="10">
+                        <StackPanel>
+                            <TextBlock Style="{StaticResource TitleStyle}"
+                                       Text="测试参数设置" />
+
+                            <Grid Margin="0 10 0 0">
+                                <Grid.ColumnDefinitions>
+                                    <ColumnDefinition Width="*" />
+                                    <ColumnDefinition Width="*" />
+                                </Grid.ColumnDefinitions>
+
+                                <!-- 重复次数 -->
+                                <StackPanel Grid.Column="0">
+                                    <TextBlock Text="重复次数:" />
+                                    <mah:NumericUpDown Value="{Binding RepeatCount, Mode=TwoWay}"
+                                                       Minimum="1"
+                                                       Maximum="1000"
+                                                       d:Value="50"
+                                                       TextAlignment="Center"
+                                                       HorizontalContentAlignment="Center"
+                                                       HorizontalAlignment="Stretch"
+                                                       IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}" />
+                                </StackPanel>
+
+                                <!-- 移动速度 -->
+                                <StackPanel Grid.Column="1"
+                                            Margin="10,0,0,0">
+                                    <TextBlock Text="移动速度(%):" />
+                                    <mah:NumericUpDown Value="{Binding MoveSpeed, Mode=TwoWay}"
+                                                       Minimum="1"
+                                                       Maximum="100"
+                                                       d:Value="50"
+                                                       TextAlignment="Center"
+                                                       HorizontalContentAlignment="Center"
+                                                       HorizontalAlignment="Stretch"
+                                                       IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}" />
+                                </StackPanel>
+                            </Grid>
+
+
+                        </StackPanel>
+                    </Border>
+
+                    <!-- 测试控制区域 -->
+                    <Border Grid.Row="2"
+                            Background="#ECF0F1"
+                            Padding="10">
+                        <StackPanel>
+                            <TextBlock Style="{StaticResource TitleStyle}"
+                                       Text="测试控制" />
+
+                            <WrapPanel HorizontalAlignment="Center"
+                                       Margin="0 10 0 0">
+
+                                <!--<Button Content="单次测试"
+                                        Background="#3498DB"
+                                        Foreground="White"
+                                        MinWidth="100"
+                                        Height="35"
+                                        FontWeight="Bold"
+                                        Command="{Binding SingleTestCommand}"
+                                        IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}" />-->
+
+                                <Button Content="连续测试"
+                                        Background="#27AE60"
+                                        Foreground="White"
+                                        MinWidth="100"
+                                        Height="35"
+                                        FontWeight="Bold"
+                                        Command="{Binding StartTestCommand}" />
+
+                                <Button Content="停止"
+                                        Background="#E74C3C"
+                                        Foreground="White"
+                                        MinWidth="100"
+                                        Height="35"
+                                        Command="{Binding StopTestCommand}" />
+
+                                <Button Content="暂停"
+                                        Background="#F39C12"
+                                        Foreground="White"
+                                        MinWidth="100"
+                                        Height="35"
+                                        Command="{Binding PauseTestCommand}" />
+                            </WrapPanel>
+                        </StackPanel>
+                    </Border>
+
+                    <!-- 进度显示 -->
+                    <Border Grid.Row="3"
+                            Background="White"
+                            Padding="10">
+                        <StackPanel>
+                            <TextBlock Style="{StaticResource TitleStyle}"
+                                       Text="测试进度" />
+
+                            <Grid Margin="0 10 0 0">
+                                <Grid.RowDefinitions>
+                                    <RowDefinition Height="Auto" />
+                                    <RowDefinition Height="Auto" />
+                                </Grid.RowDefinitions>
+
+                                <ProgressBar Grid.Row="0"
+                                             Height="25"
+                                             Margin="5"
+                                             Minimum="0"
+                                             Maximum="{Binding RepeatCount}"
+                                             Value="{Binding CurrentProgress}"
+                                             IsEnabled="False"
+                                             d:Maximum="100"
+                                             d:Value="50" />
+
+                                <TextBlock Grid.Row="1"
+                                           HorizontalAlignment="Center"
+                                           FontSize="12"
+                                           Foreground="#7F8C8D"
+                                           d:Text="等待开始..."
+                                           Text="{Binding Message}" />
+                            </Grid>
+
+                            <!-- 实时统计信息 -->
+                            <WrapPanel Margin="0 15 0 0"
+                                       HorizontalAlignment="Center">
+                                <Border Background="#3498DB"
+                                        Padding="10 5"
+                                        Margin="5"
+                                        CornerRadius="3">
+                                    <StackPanel>
+                                        <TextBlock Text="当前循环"
+                                                   Foreground="White"
+                                                   FontSize="11" />
+                                        <TextBlock Text="{Binding CurrentProgress}"
+                                                   d:Text="1"
+                                                   Foreground="White"
+                                                   FontSize="16"
+                                                   FontWeight="Bold"
+                                                   HorizontalAlignment="Center" />
+                                    </StackPanel>
+                                </Border>
+
+                                <Border Background="#2ECC71"
+                                        Padding="10 5"
+                                        Margin="5"
+                                        CornerRadius="3">
+                                    <StackPanel>
+                                        <TextBlock Text="成功率"
+                                                   Foreground="White"
+                                                   FontSize="11" />
+                                        <TextBlock Text="{Binding SuccessRate, StringFormat={}{0:F1}%}"
+                                                   d:Text="100%"
+                                                   Foreground="White"
+                                                   FontSize="16"
+                                                   FontWeight="Bold"
+                                                   HorizontalAlignment="Center" />
+                                    </StackPanel>
+                                </Border>
+
+                                <Border Background="#9B59B6"
+                                        Padding="10 5"
+                                        Margin="5"
+                                        CornerRadius="3">
+                                    <StackPanel>
+                                        <TextBlock Text="往返时间"
+                                                   Foreground="White"
+                                                   FontSize="11" />
+                                        <TextBlock Text="{Binding CycleTime, StringFormat={}{0:F2}s}"
+                                                   d:Text="2.34s"
+                                                   Foreground="White"
+                                                   FontSize="16"
+                                                   FontWeight="Bold"
+                                                   HorizontalAlignment="Center" />
+                                    </StackPanel>
+                                </Border>
+                            </WrapPanel>
+                        </StackPanel>
+                    </Border>
+
+                    <!-- 测试结果列表 -->
+                    <Border Grid.Row="4"
+                            Background="White"
+                            Padding="10">
+                        <Grid>
+                            <Grid.RowDefinitions>
+                                <RowDefinition Height="Auto" />
+                                <RowDefinition Height="*" />
+                            </Grid.RowDefinitions>
+
+                            <StackPanel Grid.Row="0"
+                                        Orientation="Horizontal">
+                                <TextBlock Style="{StaticResource TitleStyle}"
+                                           Text="测试结果列表" />
+                                <TextBlock Margin="10,0,0,0"
+                                           VerticalAlignment="Center"
+                                           Foreground="#7F8C8D"
+                                           Text="(显示最近20次结果)" />
+                            </StackPanel>
+
+                            <DataGrid x:Name="dgResults"
+                                      Grid.Row="1"
+                                      Style="{StaticResource DataGridStyle}"
+                                      MaxHeight="250"
+                                      AutoGenerateColumns="False"
+                                      CanUserAddRows="False"
+                                      IsReadOnly="True"
+                                      ItemsSource="{Binding TestResults}">
+                                <DataGrid.Columns>
+                                    <DataGridTextColumn Header="序号"
+                                                        Binding="{Binding Index}"
+                                                        MinWidth="50" />
+                                    <DataGridTextColumn Header="状态"
+                                                        Binding="{Binding IsPickSuccess}"
+                                                        MinWidth="60" />
+                                    <DataGridTextColumn Header="位置X"
+                                                        Binding="{Binding X_Position, StringFormat={}{0:F3}}"
+                                                        MinWidth="70" />
+                                    <DataGridTextColumn Header="位置Y"
+                                                        Binding="{Binding Y_Position, StringFormat={}{0:F3}}"
+                                                        MinWidth="70" />
+                                    <DataGridTextColumn Header="位置Z"
+                                                        Binding="{Binding Z_Position, StringFormat={}{0:F3}}"
+                                                        MinWidth="70" />
+                                    <DataGridTextColumn Header="循环时间"
+                                                        Binding="{Binding CycleTime, StringFormat={}{0:F2}s}"
+                                                        MinWidth="80" />
+                                    <DataGridTextColumn Header="时间戳"
+                                                        Binding="{Binding Timestamp}"
+                                                        MinWidth="120" />
+                                </DataGrid.Columns>
+                            </DataGrid>
+                        </Grid>
+                    </Border>
+
+                    <!-- 导出和精度分析 -->
+                    <Border Grid.Row="5"
+                            Background="#ECF0F1"
+                            Padding="10">
+                        <StackPanel>
+                            <!-- 导出按钮 -->
+                            <WrapPanel HorizontalAlignment="Right">
+                                <Button Content="导出CSV"
+                                        Background="#3498DB"
+                                        Foreground="White"
+                                        MinWidth="100"
+                                        Command="{Binding ExportCSVCommand}" />
+
+                                <Button Content="清空数据"
+                                        Background="#95A5A6"
+                                        Foreground="White"
+                                        MinWidth="100"
+                                        Command="{Binding ClearDataCommand}" />
+                            </WrapPanel>
+
+                        </StackPanel>
+                    </Border>
+                </Grid>
+            </Border>
+        </ScrollViewer>
+    </Grid>
+</UserControl>

+ 28 - 0
TeamAAS-VM/Views/Home/PickScrewAccuracyAnalyzer.xaml.cs

@@ -0,0 +1,28 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace TeamAAS_VP.Views.Home
+{
+    /// <summary>
+    /// PickScrewAccuracyAnalyzer.xaml 的交互逻辑
+    /// </summary>
+    public partial class PickScrewAccuracyAnalyzer : UserControl
+    {
+        public PickScrewAccuracyAnalyzer()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 4 - 4
TeamAAS-VM/Views/Home/TorqueCheck.xaml

@@ -99,12 +99,12 @@
                                 Margin="5,2"
                                 MinWidth="80"
                                 materialDesign:ButtonAssist.CornerRadius="5"
-                                Command="{Binding AddPointCommand}" />
-                        <Button Content="{lex:Loc 删除点}"
+                                Command="{Binding AddPointCommand}" />-->
+                        <Button Content="取料测试"
                                 Margin="5,2"
-                                MinWidth="80"
+                                MinWidth="100"
                                 materialDesign:ButtonAssist.CornerRadius="5"
-                                Command="{Binding DeletePointCommand}" />-->
+                                Command="{Binding PickScrewTestCommand}" />
                         <Button Content="{lex:Loc 保存}"
                                 Margin="20"
                                 MinWidth="100"

+ 11 - 0
TeamAAS-VM/Views/Product/PlcPointParams.xaml

@@ -319,6 +319,17 @@
                                     MinWidth="80"
                                     materialDesign:ButtonAssist.CornerRadius="5"
                                     Command="{Binding MovePointDownCommand}" />
+                            <!-- 导入/导出点位文件 -->
+                            <Button Content="导入点位文件"
+                                    Margin="5,2"
+                                    MinWidth="120"
+                                    materialDesign:ButtonAssist.CornerRadius="5"
+                                    Command="{Binding ImportPointsCommand}" />
+                            <Button Content="导出所有点位"
+                                    Margin="5,2"
+                                    MinWidth="120"
+                                    materialDesign:ButtonAssist.CornerRadius="5"
+                                    Command="{Binding ExportAllPointsCommand}" />
                             <Button Content="{lex:Loc CAD导入点位}"
                                     Margin="5,2"
                                     MinWidth="80"

+ 1 - 1
TeamAAS-VM/Views/Product/PlcPointParams.xaml.cs

@@ -39,7 +39,7 @@ namespace TeamAAS_VP.Views.Product
             {
                 try
                 {
-                    var visible = VM.SelectedIndex == 3 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
+                    var visible = VM.SelectedIndex == 3|| VM.SelectedIndex == 5 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                     this.Dispatcher.BeginInvoke(new Action(() =>
                     {
                         if (colProcedure != null)

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

@@ -2493,7 +2493,7 @@
                             </Grid>
                         </GroupBox>
 
-                        <GroupBox Header="电批配置"  Width="300">
+                        <GroupBox Header="扭力测量仪配置"  Width="300">
                             <Grid Margin="10">
                                 <Grid.ColumnDefinitions>
                                     <ColumnDefinition Width="auto" />
@@ -2560,7 +2560,7 @@
                                         <materialDesign:PackIcon Kind="ContentSaveCheck"
                                          Margin="0,0,6,0" />
                                         <TextBlock VerticalAlignment="Center"
-                           Text="保存电批配置" />
+                           Text="保存扭力测量仪配置" />
                                     </StackPanel>
                                 </Button>
                             </Grid>

+ 58 - 7
TeamAAS-VM/Views/Statistics/PhotoCaptureQuery.xaml

@@ -83,18 +83,69 @@
                   CanUserAddRows="False"
                   IsReadOnly="True">
             <DataGrid.Columns>
+                <DataGridTextColumn Header="Id"
+                                    Binding="{Binding Id}"
+                                    Width="50" />
                 <DataGridTextColumn Header="CaptureTime"
-                                    Binding="{Binding CaptureTime, StringFormat=yyyy-MM-dd HH:mm:ss}" />
-                <DataGridTextColumn Header="RecipeName"
+                                    Binding="{Binding CaptureTime, StringFormat=yyyy-MM-dd HH:mm:ss}"/>
+                <DataGridTextColumn Header="配方名"
                                     Binding="{Binding RecipeName}" />
-                <DataGridTextColumn Header="CameraName"
+                <DataGridTextColumn Header="流程名"
+                                    Binding="{Binding ProcessName}" />
+                <DataGridTextColumn Header="相机名"
                                     Binding="{Binding CameraName}" />
-                <DataGridTextColumn Header="ProductSN"
+                <DataGridTextColumn Header="产品SN"
                                     Binding="{Binding ProductSN}" />
-                <DataGridTextColumn Header="Result"
-                                    Binding="{Binding Result}" />
-                <DataGridTextColumn Header="ImagePath"
+                <DataGridTextColumn Header="拍照编号"
+                                    Binding="{Binding PositionIndex}" />
+                <!-- Changed to TemplateColumn to show OK/NG with color -->
+                <DataGridTemplateColumn Header="是否成功"
+                                        Width="85">
+                    <DataGridTemplateColumn.CellTemplate>
+                        <DataTemplate>
+                            <Border CornerRadius="4"
+                                    Padding="2"
+                                    HorizontalAlignment="Center"
+                                    VerticalAlignment="Center">
+                                <TextBlock HorizontalAlignment="Center"
+                                           VerticalAlignment="Center"
+                                           Foreground="White"
+                                           FontWeight="Bold"
+                                           TextAlignment="Center">
+                                    <TextBlock.Style>
+                                        <Style TargetType="TextBlock">
+                                            <Setter Property="Text"
+                                                    Value="OK" />
+                                            <Setter Property="Background"
+                                                    Value="Green" />
+                                            <Style.Triggers>
+                                                <DataTrigger Binding="{Binding IsSuccess}"
+                                                             Value="False">
+                                                    <Setter Property="Text"
+                                                            Value="NG" />
+                                                    <Setter Property="Background"
+                                                            Value="Red" />
+                                                </DataTrigger>
+                                            </Style.Triggers>
+                                        </Style>
+                                    </TextBlock.Style>
+                                </TextBlock>
+                            </Border>
+                        </DataTemplate>
+                    </DataGridTemplateColumn.CellTemplate>
+                </DataGridTemplateColumn>
+                <DataGridTextColumn Header="机器人位置"
+                                    Binding="{Binding RobotPosition}" />
+                <DataGridTextColumn Header="像素坐标"
+                                    Binding="{Binding PixelPosition}"/>
+                <DataGridTextColumn Header="绝对坐标"
+                                    Binding="{Binding AbsolutePosition}" />
+                <DataGridTextColumn Header="图片路径"
                                     Binding="{Binding ImagePath}" />
+                <DataGridTextColumn Header="操作员"
+                                    Binding="{Binding OperatorName}"/>
+                <DataGridTextColumn Header="备注"
+                                    Binding="{Binding Remarks}" />
             </DataGrid.Columns>
         </DataGrid>
         <StackPanel Grid.Row="3"

+ 9 - 0
TeamAAS-VM/Views/Statistics/ProductionRecordQuery.xaml

@@ -79,8 +79,17 @@
             <DataGrid.Columns>
                 <DataGridTextColumn Header="时间"
                                     Binding="{Binding Timestamp, StringFormat=yyyy-MM-dd HH:mm:ss}" />
+                <DataGridTextColumn Header="Id"
+                                    Binding="{Binding Id}"
+                                    Width="50" />
                 <DataGridTextColumn Header="产品"
                                     Binding="{Binding ProductName}" />
+                <DataGridTextColumn Header="产品编码"
+                                    Binding="{Binding ProductCode}" />
+                <DataGridTextColumn Header="设备Id"
+                                    Binding="{Binding DeviceId}" />
+                <DataGridTextColumn Header="设备名称"
+                                    Binding="{Binding DeviceName}" />
                 <DataGridTextColumn Header="类别"
                                     Binding="{Binding Category}" />
                 <DataGridTextColumn Header="数量"