wanghan 9 months ago
parent
commit
1f2f586d1c
49 changed files with 4182 additions and 351 deletions
  1. 142 82
      TeamAAS-VM/Core/Cameras/OptCamera.cs
  2. 796 54
      TeamAAS-VM/Core/FileHelper.cs
  3. 183 63
      TeamAAS-VM/Core/Management.cs
  4. 5 2
      TeamAAS-VM/Core/ScriptHelper.cs
  5. 687 0
      TeamAAS-VM/Core/VisionProFileHelper.cs
  6. 13 1
      TeamAAS-VM/Data/DatabaseInitializer.cs
  7. 115 0
      TeamAAS-VM/Data/SystemDatabaseService.cs
  8. 5 0
      TeamAAS-VM/Enums/ProcedureSaveImagePathModel.cs
  9. 4 0
      TeamAAS-VM/Events/LockFinishNotification.cs
  10. 3 1
      TeamAAS-VM/Interfaces/IRemoteCommandService.cs
  11. 76 0
      TeamAAS-VM/Interfaces/ISystemDatabaseService.cs
  12. 132 0
      TeamAAS-VM/Models/AssemblyRecord.cs
  13. 87 0
      TeamAAS-VM/Models/PhotoCaptureRecord.cs
  14. 40 0
      TeamAAS-VM/Models/Product/ProductModel.cs
  15. 2 2
      TeamAAS-VM/Properties/AssemblyInfo.cs
  16. 3 0
      TeamAAS-VM/Resources/Languages/Lang.resx
  17. 6 6
      TeamAAS-VM/Services/CalibrationService.cs
  18. 2 1
      TeamAAS-VM/Services/ConfigService.cs
  19. 8 8
      TeamAAS-VM/Services/ProductService.cs
  20. 95 52
      TeamAAS-VM/Services/RemoteCommandService.cs
  21. 27 0
      TeamAAS-VM/TeamAAS-VP.csproj
  22. 3 3
      TeamAAS-VM/ViewModels/Calibration/CalibrationCameraParamsViewModel.cs
  23. 2 2
      TeamAAS-VM/ViewModels/Calibration/CalibrationDistortionViewModel.cs
  24. 1 1
      TeamAAS-VM/ViewModels/Calibration/CalibrationEditVisionViewModel.cs
  25. 1 1
      TeamAAS-VM/ViewModels/Calibration/CalibrationHomeViewModel.cs
  26. 4 4
      TeamAAS-VM/ViewModels/Calibration/FixedUpCameraFindP0ViewModel.cs
  27. 29 2
      TeamAAS-VM/ViewModels/HomeViewModel.cs
  28. 195 4
      TeamAAS-VM/ViewModels/Product/PlcPointParamsViewModel.cs
  29. 3 3
      TeamAAS-VM/ViewModels/Product/ProcessBasicsViewModel.cs
  30. 101 0
      TeamAAS-VM/ViewModels/Product/ProductParamsViewModel.cs
  31. 2 2
      TeamAAS-VM/ViewModels/Product/ProductProcessManageViewModel.cs
  32. 260 0
      TeamAAS-VM/ViewModels/Statistics/AssemblyRecordQueryViewModel.cs
  33. 1 1
      TeamAAS-VM/ViewModels/Statistics/LockResultRecoredQueryViewModel.cs
  34. 191 0
      TeamAAS-VM/ViewModels/Statistics/PhotoCaptureQueryViewModel.cs
  35. 167 0
      TeamAAS-VM/ViewModels/Statistics/ProductionRecordQueryViewModel.cs
  36. 19 15
      TeamAAS-VM/ViewModels/Statistics/ProductionStatementViewModel.cs
  37. 64 10
      TeamAAS-VM/Views/Home/ShowVisionRender.xaml.cs
  38. 15 19
      TeamAAS-VM/Views/HomeView.xaml
  39. 11 0
      TeamAAS-VM/Views/Product/PlcPointParams.xaml
  40. 5 5
      TeamAAS-VM/Views/Product/PlcPointParams.xaml.cs
  41. 97 0
      TeamAAS-VM/Views/Product/ProductParams.xaml
  42. 164 0
      TeamAAS-VM/Views/Statistics/AssemblyRecordQuery.xaml
  43. 15 0
      TeamAAS-VM/Views/Statistics/AssemblyRecordQuery.xaml.cs
  44. 7 5
      TeamAAS-VM/Views/Statistics/LockResultRecoredQuery.xaml
  45. 190 0
      TeamAAS-VM/Views/Statistics/PhotoCaptureQuery.xaml
  46. 28 0
      TeamAAS-VM/Views/Statistics/PhotoCaptureQuery.xaml.cs
  47. 142 0
      TeamAAS-VM/Views/Statistics/ProductionRecordQuery.xaml
  48. 28 0
      TeamAAS-VM/Views/Statistics/ProductionRecordQuery.xaml.cs
  49. 6 2
      TeamAAS-VM/Views/StatisticsView.xaml

+ 142 - 82
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,12 +356,12 @@ 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);
                 // ch:设置采集策略 | en:Set Grab Strategy
-                nReVal = mvCameraAcq.SetGrabStrategy(SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Upcoming);
+                nReVal = mvCameraAcq.SetGrabStrategy(CurrentGrabStrategy);
                 if (nReVal != SciCam.SCI_CAMERA_OK)
                 {
                     Console.WriteLine("Register Event CallBack fail! nRet {0}", nReVal);
@@ -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,42 +437,38 @@ namespace TeamAAS_VP.Core.Cameras
                             OpenDevice();
                         }
 
-                        //如果仅仅采集最后一帧,则清空缓存
-                        //if (lastImageOnly)
-                        //{
-                        //    //判断当前的模式是否为最新模式,如果不是则设置为最新模式
-                        //    if (CurrentGrabStrategy != SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Upcoming)
-                        //    {
-                        //        CurrentGrabStrategy = SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Upcoming;
-                        //        nReVal = mvCameraAcq.SetGrabStrategy(CurrentGrabStrategy);
-                        //    }
-                        //}
-                        //else
-                        //{
-                        //    //判断当前的模式是否为顺序模式,如果不是则设置为顺序模式
-                        //    if (CurrentGrabStrategy != SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Latest)
-                        //    {
-                        //        CurrentGrabStrategy = SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Latest;
-                        //        nReVal = mvCameraAcq.SetGrabStrategy(CurrentGrabStrategy);
-                        //    }
-                        //}
-                        //if (!mvCameraAcq.IsGrabbing())
-                        //{
-                        //    mvCameraAcq.StartGrabbing();
-                        //}
-                        //nReVal = mvCameraAcq.StartGrabbing();
-                        //mvCameraAcq.ClearPayloadBuffer();
+                        // 重置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");
-                        nReVal = mvCameraAcq.Grab(ref payload);
+                        nReVal = mvCameraAcq.SetCommandValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerSoftware");
                         if (nReVal == SciCam.SCI_CAMERA_OK)
                         {
-                            Image = GetConvertedInfo(payload);
-                            mvCameraAcq.FreePayload(payload);
-                            //nReVal = mvCameraAcq.StopGrabbing();
-                            TotalTime = sw.Elapsed;
-                            ErrorMessage = $"{i + 1}";
-                            return Image;
+                            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);
+                                //nReVal = mvCameraAcq.StopGrabbing();
+                                //_operationSemaphore.Release();
+                                CloseDevice();
+                                OpenDevice();
+                                ErrorMessage = "图像采集失败!";
+                            }
                         }
                         else
                         {
@@ -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
             {

+ 796 - 54
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;
@@ -8,118 +10,858 @@ using System.Linq;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;
-using TeamAAS_VP.Models;
 using TeamAAS_VP;
-using static Org.BouncyCastle.Math.EC.ECCurve;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Resources.Languages;
 
 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>
+        /// 安全写入文本文件(支持目录创建、临时写入、原子替换与可选版本化备份)。
+        /// </summary>
+        /// <param name="content">要写入的文本内容。</param>
+        /// <param name="path">目标文件完整路径。</param>
+        public static void WriteFile(string content, string path)
+        {
+            ValidatePath(path);
+            WriteFileInternal(content, path);
         }
 
         /// <summary>
-        /// 读取Json文件
+        /// 读取文本文件,支持自动恢复(从 .bak 或版本化备份恢复)。
         /// </summary>
-        /// <typeparam name="T">对象</typeparam>
-        /// <param name="path">文件路径</param>
-        /// <returns></returns>
-        /// <exception cref="Exception"></exception>
-        public static T ReadJsonFile<T>(string path)
+        /// <param name="path">文件路径。</param>
+        /// <param name="autoRecover">可选:覆盖默认的自动恢复行为(null 表示使用配置项)。</param>
+        /// <returns>文件内容字符串。</returns>
+        /// <exception cref="FileNotFoundException">当文件不存在且无法恢复时抛出。</exception>
+        public static string ReadFile(string path, bool? autoRecover = null)
         {
-            if (File.Exists(path))
+            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($"文件不存在:[{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)
+        {
+            try
+            {
+                return ReadFile(path, true);
+            }
+            catch
+            {
+                return defaultValue;
+            }
+        }
+        #endregion
+
+        #region 文件恢复相关
+        /// <summary>
+        /// 检查并修复指定目录下的所有相关临时文件与备份文件。
+        /// - 恢复或清理 .tmp 文件
+        /// - 清理孤立或过旧的 .bak 文件
+        /// - 清理版本化备份超过保留数量的旧版本
+        /// </summary>
+        /// <param name="directoryPath">要检查的目录路径。</param>
+        public static void CheckAndRepairDirectory(string directoryPath)
         {
-            if (!Directory.Exists(Path.GetDirectoryName(path)))
+            if (!Directory.Exists(directoryPath))
+                return;
+
+            // 处理临时文件
+            var tempFiles = Directory.GetFiles(directoryPath, "*.tmp", SearchOption.AllDirectories);
+            foreach (var tempFile in tempFiles)
             {
-                Directory.CreateDirectory(Path.GetDirectoryName(path));
+                TryRecoverFromTempFile(tempFile);
             }
-            using (StreamWriter sw = new StreamWriter(path))
+
+            // 处理备份文件
+            var backupFiles = Directory.GetFiles(directoryPath, "*.bak", SearchOption.AllDirectories);
+            foreach (var backupFile in backupFiles)
             {
-                sw.Write(content);
+                TryCleanOrphanedBackup(backupFile);
             }
+
+            // 处理版本化备份
+            CleanupOldBackupVersions(directoryPath);
         }
 
         /// <summary>
-        /// 读取文件
+        /// 强制从备份恢复主文件。优先使用直接的 .bak,其次尝试版本化备份目录中的最新文件。
         /// </summary>
-        /// <param name="path"></param>
-        /// <returns></returns>
-        /// <exception cref="Exception"></exception>
-        public static string ReadFile(string path)
+        /// <param name="originalPath">原文件路径。</param>
+        /// <returns>成功返回 true,失败返回 false。</returns>
+        public static bool ForceRecoverFile(string originalPath)
         {
-            if (File.Exists(path))
+            try
             {
-                string buffer;
-                using (StreamReader sr = new StreamReader(path))
+                // 尝试从直接备份恢复
+                string backupPath = originalPath + ".bak";
+                if (File.Exists(backupPath))
                 {
-                    buffer = sr.ReadToEnd();
+                    File.Copy(backupPath, originalPath, true);
+                    Log($"从备份强制恢复: {originalPath}");
+                    return true;
                 }
-                return buffer;
+
+                // 尝试从版本化备份恢复
+                var recovered = TryFindLatestBackup(originalPath);
+                if (recovered != null)
+                {
+                    File.Copy(recovered, originalPath, true);
+                    Log($"从版本备份强制恢复: {originalPath}");
+                    return true;
+                }
+
+                return false;
             }
-            else
+            catch (Exception ex)
             {
-                throw new Exception($"文件不存在:[{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
     }
 }

+ 183 - 63
TeamAAS-VM/Core/Management.cs

@@ -121,17 +121,6 @@ namespace TeamAAS_VP.Core
             set { SetProperty(ref _Renders, value); }
         }
 
-        private ProductModel _CurrentProduct;
-
-        /// <summary>
-        /// 当前产品
-        /// </summary>
-        public ProductModel CurrentProduct
-        {
-            get { return _CurrentProduct; }
-            set { SetProperty(ref _CurrentProduct, value); }
-        }
-
         public BgCommunicate BgCommunicate { get; private set; }
 
         public BgModbusTcpCommunicate BgModbusTcpCommunicate { get; private set; }
@@ -828,7 +817,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);
@@ -842,6 +831,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
             {
@@ -1101,7 +1099,18 @@ namespace TeamAAS_VP.Core
         /// 移动向下相机拍照结果
         /// </summary>
         OpenCvSharp.Point3f[] UpCameraPutResults = new OpenCvSharp.Point3f[10];
-
+        /// <summary>
+        /// 取料移动相机拍照结果
+        /// </summary>
+        OpenCvSharp.Point3f UpCameraPickResult = new OpenCvSharp.Point3f();
+        /// <summary>
+        /// 最终组装位置
+        /// </summary>
+        OpenCvSharp.Point3f PlaceActualCoord = new OpenCvSharp.Point3f();
+        /// <summary>
+        /// 零件SN
+        /// </summary>
+        string PartSN = "";
 
 
         /// <summary>
@@ -1209,7 +1218,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);
+                                    var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, cameraIndex, null);
                                     if (isDryMode)
                                     {
                                         await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
@@ -1257,8 +1266,8 @@ namespace TeamAAS_VP.Core
                                     }
                                     // 执行视觉任务
                                     var _cts = new CancellationTokenSource();
-                                    var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
-                                    var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
+                                    var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 1, null);
+                                    var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 2, null);
                                     var visionResults = await Task.WhenAll(task1, task2);
                                     if (isDryMode)
                                     {
@@ -1353,8 +1362,8 @@ namespace TeamAAS_VP.Core
                                     }
                                     // 执行视觉任务
                                     var _cts = new CancellationTokenSource();
-                                    var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
-                                    var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
+                                    var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 1, null);
+                                    var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 2, null);
                                     var visionResults = await Task.WhenAll(task1, task2);
                                     if (isDryMode)
                                     {
@@ -1505,7 +1514,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);
+                                var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, cameraIndex, null);
                                 if (isDryMode)
                                 {
                                     await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)1);
@@ -1546,8 +1555,8 @@ namespace TeamAAS_VP.Core
                                 }
                                 // 执行视觉任务
                                 var _cts = new CancellationTokenSource();
-                                var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
-                                var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
+                                var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 1, null);
+                                var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 2, null);
                                 var visionResults = await Task.WhenAll(task1, task2);
                                 if (isDryMode)
                                 {
@@ -1633,7 +1642,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);
+                                var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, cameraIndex, null);
                                 if (isDryMode)
                                 {
                                     await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)1);
@@ -1672,8 +1681,8 @@ namespace TeamAAS_VP.Core
                                 }
                                 // 执行视觉任务
                                 var _cts = new CancellationTokenSource();
-                                var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
-                                var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
+                                var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 1, null);
+                                var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token, 2, null);
                                 var visionResults = await Task.WhenAll(task1, task2);
                                 if (isDryMode)
                                 {
@@ -1721,7 +1730,7 @@ namespace TeamAAS_VP.Core
                         {
                             SendTaskMessage($"触发上相机检测拍照...", MessageLevel.Debug);
                             //相机的编号
-                            //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.Out_UPCameracheckNum.Address);
+                            Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.Out_UPCameracheckNum.Address);
 
                             if (isDryMode)
                             {
@@ -1729,6 +1738,37 @@ namespace TeamAAS_VP.Core
                                 return;
                             }
 
+                            //视觉流程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;
+                            }
+
+                            // 执行视觉任务
+                            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);
+                            }
                             await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)1);
                         }
                         else
@@ -1758,11 +1798,66 @@ namespace TeamAAS_VP.Core
                             //相机的编号
                             //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameraPickNum.Address);
 
+                            if (currentProduct.IndependentCamer1AuxProcedureId == Guid.Empty)
+                            {
+                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                return;
+                            }
+                            if (currentProduct.IndependentCamer2AuxProcedureId == Guid.Empty)
+                            {
+                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                return;
+                            }
+                            if (currentProduct.IndependentCamer3AuxProcedureId == Guid.Empty)
+                            {
+                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                return;
+                            }
+                            if (currentProduct.IndependentCamer4AuxProcedureId == Guid.Empty)
+                            {
+                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                return;
+                            }
+
+                            //获取四个独立相机的流程id
+                            var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer1AuxProcedureId);
+                            var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer2AuxProcedureId);
+                            var process3 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer3AuxProcedureId);
+                            var process4 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer4AuxProcedureId);
+
+                            // 执行视觉任务
+                            var _cts = new CancellationTokenSource();
+                            var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, null, _cts.Token, 1, null);
+                            var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, null, _cts.Token, 2, null);
+                            var task3 = _remoteCommandService.ExecutePhotoGetSinglePoint(process3, null, null, _cts.Token, 3, null);
+                            var task4 = _remoteCommandService.ExecutePhotoGetSinglePoint(process4, null, null, _cts.Token, 4, null);
+
+                            var visionResults = await Task.WhenAll(task1, task2, task3, task4);
                             if (isDryMode)
                             {
                                 await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
                                 return;
                             }
+                            if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
+                            {
+
+                                Vector<double> p1 = Vector<double>.Build.Dense(new double[] { visionResults[1].X, visionResults[1].Y });
+                                Vector<double> p2 = Vector<double>.Build.Dense(new double[] { visionResults[2].X, visionResults[2].Y });
+                                Vector<double> p3 = Vector<double>.Build.Dense(new double[] { visionResults[3].X, visionResults[3].Y });
+                                Vector<double> p4 = Vector<double>.Build.Dense(new double[] { visionResults[0].X, visionResults[0].Y });
+
+                                var center = RectangleCenterCalculator.CalculateByPCAWithKnownOrder(new List<Vector<double>> { p1, p2, p3, p4 });
+                                UpCameraPutResults[1].X = (float)center.Center[0];
+                                UpCameraPutResults[1].Y = (float)center.Center[1];
+                                UpCameraPutResults[1].Z = (float)center.MajorAxisAngle;
+                                SendTaskMessage($"LCD拍照结果:X={UpCameraPutResults[1].X},Y={UpCameraPutResults[1].Y},Angle={UpCameraPutResults[1].Z}", MessageLevel.Info);
+                            }
+                            else
+                            {
+
+                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)2);
+                                return;
+                            }
 
                             await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
                         }
@@ -1821,10 +1916,10 @@ namespace TeamAAS_VP.Core
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, null, _cts.Token);
-                            var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, null, _cts.Token);
-                            var task3 = _remoteCommandService.ExecutePhotoGetSinglePoint(process3, null, null, _cts.Token);
-                            var task4 = _remoteCommandService.ExecutePhotoGetSinglePoint(process4, null, null, _cts.Token);
+                            var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, null, _cts.Token, 1, null);
+                            var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, null, _cts.Token, 2, null);
+                            var task3 = _remoteCommandService.ExecutePhotoGetSinglePoint(process3, null, null, _cts.Token, 3, null);
+                            var task4 = _remoteCommandService.ExecutePhotoGetSinglePoint(process4, null, null, _cts.Token, 4, null);
 
                             var visionResults = await Task.WhenAll(task1, task2, task3, task4);
                             if (isDryMode)
@@ -1881,39 +1976,39 @@ namespace TeamAAS_VP.Core
                             //相机的编号
                             //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameracheckNum.Address);
 
-                            if (currentProduct.IndependentCamer1AuxProcedureId == Guid.Empty)
+                            if (currentProduct.IndependentCamer1CheckProcedureId == Guid.Empty)
                             {
                                 await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
                                 return;
                             }
-                            if (currentProduct.IndependentCamer2AuxProcedureId == Guid.Empty)
+                            if (currentProduct.IndependentCamer2CheckProcedureId == Guid.Empty)
                             {
                                 await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
                                 return;
                             }
-                            if (currentProduct.IndependentCamer3AuxProcedureId == Guid.Empty)
+                            if (currentProduct.IndependentCamer3CheckProcedureId == Guid.Empty)
                             {
                                 await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
                                 return;
                             }
-                            if (currentProduct.IndependentCamer4AuxProcedureId == Guid.Empty)
+                            if (currentProduct.IndependentCamer4CheckProcedureId == Guid.Empty)
                             {
                                 await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
                                 return;
                             }
 
                             //获取四个独立相机的流程id
-                            var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer1AuxProcedureId);
-                            var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer2AuxProcedureId);
-                            var process3 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer3AuxProcedureId);
-                            var process4 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer4AuxProcedureId);
+                            var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer1CheckProcedureId);
+                            var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer2CheckProcedureId);
+                            var process3 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer3CheckProcedureId);
+                            var process4 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer4CheckProcedureId);
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, null, _cts.Token);
-                            var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, null, _cts.Token);
-                            var task3 = _remoteCommandService.ExecutePhotoGetSinglePoint(process3, null, null, _cts.Token);
-                            var task4 = _remoteCommandService.ExecutePhotoGetSinglePoint(process4, null, null, _cts.Token);
+                            var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, null, _cts.Token, 1, null);
+                            var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, null, _cts.Token, 2, null);
+                            var task3 = _remoteCommandService.ExecutePhotoGetSinglePoint(process3, null, null, _cts.Token, 3, null);
+                            var task4 = _remoteCommandService.ExecutePhotoGetSinglePoint(process4, null, null, _cts.Token, 4, null);
 
                             var visionResults = await Task.WhenAll(task1, task2, task3, task4);
                             if (isDryMode)
@@ -1923,26 +2018,16 @@ namespace TeamAAS_VP.Core
                             }
                             if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
                             {
-                                
-                                Vector<double> p1 = Vector<double>.Build.Dense(new double[] { visionResults[1].X, visionResults[1].Y });
-                                Vector<double> p2 = Vector<double>.Build.Dense(new double[] { visionResults[2].X, visionResults[2].Y });
-                                Vector<double> p3 = Vector<double>.Build.Dense(new double[] { visionResults[3].X, visionResults[3].Y });
-                                Vector<double> p4 = Vector<double>.Build.Dense(new double[] { visionResults[0].X, visionResults[0].Y });
-
-                                var center = RectangleCenterCalculator.CalculateByPCAWithKnownOrder(new List<Vector<double>> { p1, p2, p3, p4 });
-                                UpCameraPutResults[1].X = (float)center.Center[0];
-                                UpCameraPutResults[1].Y = (float)center.Center[1];
-                                UpCameraPutResults[1].Z = (float)center.MajorAxisAngle;
-                                SendTaskMessage($"LCD拍照结果:X={UpCameraPutResults[1].X},Y={UpCameraPutResults[1].Y},Angle={UpCameraPutResults[1].Z}", MessageLevel.Info);
+                                SendTaskMessage($"固定相机检测OK", MessageLevel.Debug);
+                                await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)1);
+                                return;
                             }
                             else
                             {
-                                
+                                SendTaskMessage($"固定相机检测NG", MessageLevel.Error);
                                 await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
                                 return;
                             }
-
-                            await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)1);
                         }
                         else
                         {
@@ -2005,7 +2090,7 @@ namespace TeamAAS_VP.Core
                             point.X_Position = (float)p0[0];
                             point.Y_Position = (float)p0[1];
                             point.U_Position = (float)angle;
-
+                            PlaceActualCoord = new OpenCvSharp.Point3f(point.X_Position, point.Y_Position, point.U_Position);
                             SendTaskMessage($"点:1,{point.X_Position:F3},{point.Y_Position:F4},{point.U_Position:F4}", MessageLevel.Info);
                             await point.WriteToPlcAddress(addressConfig.Out_Screw, plc);
                             await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)1);
@@ -2095,16 +2180,40 @@ namespace TeamAAS_VP.Core
                                     SendTaskMessage($"收到{i}上传本站数据请求...", MessageLevel.Debug);
 
                                     //这里缺少上传MES的本站数据结果及开始和结束时间,需要补充
-                                    if(i == 0)
+                                    double ct = DateTime.UtcNow.Subtract(_LastMesCheckTime[i]).TotalSeconds;
+                                    if (i == 0)
                                     {
-                                        CTtime = DateTime.UtcNow.Subtract(_LastMesCheckTime[i]).TotalSeconds;
+                                        CTtime = ct;
                                     }
 
                                     //读取产品结果
                                     Int16 resultIndex = plc.ReadNode<Int16>(string.Format(addressConfig.In_Result.Address,i));
+                                    //读取压力值
+                                    float pressure = plc.ReadNode<float>(string.Format(addressConfig.In_PressureValue.Address, i));
+                                    AssemblyRecord assemblyRecord = new AssemblyRecord();
+                                    assemblyRecord.ProductSN = code;
+                                    assemblyRecord.RecipeName = currentProduct.Name;
+                                    assemblyRecord.PartSN = PartSN;
+                                    assemblyRecord.AssemblyDurationSeconds = ct;
+                                    assemblyRecord.AssemblyPressure = pressure;
+                                    assemblyRecord.DeviceId = i;
+                                    assemblyRecord.DeviceName = $"";
+                                    assemblyRecord.OperatorName = _systemDatabaseService.GetCurrentUser().UserName;
+                                    assemblyRecord.Success = resultIndex == 1 ? true : false;
+                                    assemblyRecord.DownCameraCoord1 = "";
+                                    assemblyRecord.DownCameraCoord2 = "";
+                                    assemblyRecord.DownCameraCoord3 = "";
+                                    assemblyRecord.DownCameraCoord4 = "";
+                                    assemblyRecord.PickMoveCameraCoord = "";
+                                    assemblyRecord.PlaceMoveCameraCoord1 = "";
+                                    assemblyRecord.PlaceMoveCameraCoord2 = "";
+                                    assemblyRecord.PlaceMoveCameraCoord3 = "";
+                                    assemblyRecord.PlaceMoveCameraCoord4 = "";
+                                    assemblyRecord.PlaceActualCoord = "";
 
                                     //目前只记录当前站
                                     if (i == 0)
+                                    {
                                         await _systemDatabaseService.RecordProductionAsync(new ProductionRecord()
                                         {
                                             ProductName = currentProduct.Name,
@@ -2113,8 +2222,19 @@ namespace TeamAAS_VP.Core
                                             DeviceName = "",
                                             Category = resultIndex == 1 ? "OK" : "NG",
                                             Quantity = 1,
-                                            Remark = $"TotalSeconds:{DateTime.UtcNow.Subtract(_LastMesCheckTime[i]).TotalSeconds.ToString("F2")}",
+                                            Remark = $"TotalSeconds:{ct.ToString("F2")}",
+                                            UserName = _systemDatabaseService.GetCurrentUser().UserName,
+                                        });
+                                        assemblyRecord.PlaceMoveCameraCoord1 = $"{UpCameraPutResults[0].X:F3},{UpCameraPutResults[0].Y:F3},{UpCameraPutResults[0].Z:F3}";
+                                        assemblyRecord.PlaceMoveCameraCoord2 = $"{UpCameraPutResults[1].X:F3},{UpCameraPutResults[1].Y:F3},{UpCameraPutResults[1].Z:F3}";
+                                        assemblyRecord.PlaceActualCoord = $"{PlaceActualCoord.X:F3},{PlaceActualCoord.Y:F3},{PlaceActualCoord.Z:F3}";
+                                        App.Current.Dispatcher.Invoke(() =>
+                                        {
+                                            _eventAggregator.GetEvent<AssemblyFinishNotification>().Publish(assemblyRecord);
                                         });
+                                    }
+
+                                    await _systemDatabaseService.RecordAssemblyAsync(assemblyRecord);
 
                                     (bool isSuccess, string response) = await _mesService.SubmitGetAsync(code, resultIndex == 1 ? true : false, _LastMesCheckTime[i], DateTime.UtcNow);
                                     //假设上传成功,这里缺少上传失败的处理
@@ -2426,12 +2546,12 @@ namespace TeamAAS_VP.Core
         {
             try
             {
-                if (CurrentProduct == null) return;
                 //获取当前产品
                 var currentproduct = _productService.GetCurrentProduct();
-                TotalQuantity = await _systemDatabaseService.GetOverallProductionAsync(CurrentProduct.Name);
-                TotalQuantityToday = await _systemDatabaseService.GetTodayProductionAsync(CurrentProduct.Name);
-                CurrentUPH = await _systemDatabaseService.GetLastHourProductionAsync(CurrentProduct.Name);
+                if (currentproduct == null) return;
+                TotalQuantity = await _systemDatabaseService.GetOverallProductionAsync(currentproduct.Name);
+                TotalQuantityToday = await _systemDatabaseService.GetTodayProductionAsync(currentproduct.Name);
+                CurrentUPH = await _systemDatabaseService.GetLastHourProductionAsync(currentproduct.Name);
             }
             catch (Exception)
             {

+ 5 - 2
TeamAAS-VM/Core/ScriptHelper.cs

@@ -13,6 +13,7 @@ using System.Windows.Documents;
 using System.Windows.Forms;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
+using TeamAAS_VP.Services;
 
 namespace TeamAAS_VP.Core
 {
@@ -113,13 +114,14 @@ namespace TeamAAS_VP.Core
         {
             try
             {
+                IProductService productService = container.Resolve<IProductService>();
                 var eval = CSScript.Evaluator.ReferenceDomainAssemblies(DomainAssemblies.AllStatic);
                 IBackgroundScripting scripting = eval.LoadCode<IBackgroundScripting>(strSourceCode);
                 scripting.regionManager = regionManager;
                 scripting.eventAggregator = ea;
                 scripting.container = container;
                 scripting.management = container.Resolve<Management>();
-                scripting.CurrentProduct = scripting.management.CurrentProduct;
+                scripting.CurrentProduct = productService.GetCurrentProduct();
                 return scripting.Execute();
             }
             catch (CSScriptLib.CompilerException e1)
@@ -160,13 +162,14 @@ namespace TeamAAS_VP.Core
         {
             try
             {
+                IProductService productService = container.Resolve<IProductService>();
                 var eval = CSScript.Evaluator.ReferenceDomainAssemblies(DomainAssemblies.AllStatic);
                 IVisionScripting scripting = eval.LoadCode<IVisionScripting>(strSourceCode);
                 scripting.regionManager = regionManager;
                 scripting.eventAggregator = ea;
                 scripting.container= container;
                 scripting.management= container.Resolve<Management>();
-                scripting.CurrentProduct = scripting.management.CurrentProduct;
+                scripting.CurrentProduct = productService.GetCurrentProduct();
                 await scripting.Execute(procedure, items, rst =>
                 {
                     callback.Invoke(rst);

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

+ 13 - 1
TeamAAS-VM/Data/DatabaseInitializer.cs

@@ -26,7 +26,7 @@ namespace TeamAAS_VP.Data
                 // 创建数据库(如果不存在)
                 _db.DbMaintenance.CreateDatabase();
                 // 创建表
-                _db.CodeFirst.InitTables(typeof(User), typeof(ProductionRecord), typeof(UserLoginRecord), typeof(AlarmRecord), typeof(LockResult));
+                _db.CodeFirst.InitTables(typeof(User), typeof(ProductionRecord), typeof(UserLoginRecord), typeof(AlarmRecord), typeof(LockResult), typeof(PhotoCaptureRecord), typeof(AssemblyRecord));
 
                 // 创建索引
                 CreateIndexes();
@@ -73,6 +73,18 @@ namespace TeamAAS_VP.Data
 
                 // 你可以在这里为其他表添加索引,例如 ProductionRecord 的 Timestamp 或 ProductName
                 try { _db.DbMaintenance.CreateIndex("ProductionRecord", new string[] { "ProductName", "Timestamp" }, "IX_ProductionRecord_ProductName_Timestamp", false); } catch { }
+
+                // Photo capture records indexes
+                try { _db.DbMaintenance.CreateIndex("PhotoCaptureRecord", new string[] { "CaptureTime" }, "IX_PhotoCaptureRecord_CaptureTime", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("PhotoCaptureRecord", new string[] { "RecipeName" }, "IX_PhotoCaptureRecord_RecipeName", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("PhotoCaptureRecord", new string[] { "ProductSN" }, "IX_PhotoCaptureRecord_ProductSN", false); } catch { }
+
+                // Assembly records indexes
+                try { _db.DbMaintenance.CreateIndex("AssemblyRecord", new string[] { "Timestamp" }, "IX_AssemblyRecord_Timestamp", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("AssemblyRecord", new string[] { "RecipeName" }, "IX_AssemblyRecord_RecipeName", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("AssemblyRecord", new string[] { "ProductSN" }, "IX_AssemblyRecord_ProductSN", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("AssemblyRecord", new string[] { "PartSN" }, "IX_AssemblyRecord_PartSN", false); } catch { }
+
             }
             catch
             {

+ 115 - 0
TeamAAS-VM/Data/SystemDatabaseService.cs

@@ -588,6 +588,20 @@ namespace TeamAAS_VP.Data
             return dict;
         }
 
+        /// <summary>
+        /// 分页查询生产记录
+        /// </summary>
+        public async Task<(IEnumerable<ProductionRecord> Items, int TotalCount)> QueryProductionRecordsPagedAsync(DateTime start, DateTime end, int pageIndex, int pageSize, string productName = null, string category = null)
+        {
+            if (pageIndex < 1) pageIndex = 1;
+            if (pageSize < 1) pageSize = 20;
+            var q = _db.Queryable<ProductionRecord>().Where(r => r.Timestamp >= start && r.Timestamp < end);
+            if (!string.IsNullOrEmpty(productName)) q = q.Where(r => r.ProductName == productName);
+            if (!string.IsNullOrEmpty(category)) q = q.Where(r => r.Category == category);
+            var total = await q.CountAsync();
+            var list = await q.OrderBy(r => r.Timestamp, OrderByType.Desc).ToPageListAsync(pageIndex, pageSize);
+            return (list, total);
+        }
         #endregion
 
         #region 报警记录
@@ -622,6 +636,107 @@ namespace TeamAAS_VP.Data
 
         #endregion
 
+        #region 拍照记录
+        /// <summary>
+        /// 记录产品拍照结果
+        /// </summary>
+        /// <param name="record"></param>
+        /// <returns></returns>
+        /// <exception cref="ArgumentNullException"></exception>
+        public async Task RecordPhotoCaptureAsync(PhotoCaptureRecord record)
+        {
+            if (record == null) throw new ArgumentNullException(nameof(record));
+            if (record.CaptureTime == default(DateTime)) record.CaptureTime = DateTime.UtcNow;
+            record.Id = record.Id == Guid.Empty ? Guid.NewGuid() : record.Id;
+            await _db.Insertable(record).ExecuteCommandAsync();
+        }
+
+        /// <summary>
+        /// 查询拍照记录,支持按配方名、产品SN和时间段过滤,参数均为可选。
+        /// </summary>
+        /// <param name="recipeName"></param>
+        /// <param name="cameraName"></param>
+        /// <param name="productSN"></param>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <returns></returns>
+        public async Task<IEnumerable<PhotoCaptureRecord>> QueryPhotoCapturesAsync(string recipeName = null, string cameraName = null, string productSN = null, DateTime? start = null, DateTime? end = null)
+        {
+            var q = _db.Queryable<PhotoCaptureRecord>();
+            if (!string.IsNullOrEmpty(recipeName)) q = q.Where(r => r.RecipeName == recipeName);
+            if (!string.IsNullOrEmpty(productSN)) q = q.Where(r => r.ProductSN == productSN);
+            if (start.HasValue) q = q.Where(r => r.CaptureTime >= start.Value);
+            if (end.HasValue) q = q.Where(r => r.CaptureTime <= end.Value);
+            var list = await q.OrderBy(r => r.CaptureTime, OrderByType.Desc).ToListAsync();
+            return list;
+        }
+
+        /// <summary>
+        /// 分页查询拍照记录
+        /// </summary>
+        public async Task<(IEnumerable<PhotoCaptureRecord> Items, int TotalCount)> QueryPhotoCapturesPagedAsync(string recipeName = null, string cameraName = null, string productSN = null, DateTime? start = null, DateTime? end = null, int pageIndex = 1, int pageSize = 20)
+        {
+            if (pageIndex < 1) pageIndex = 1;
+            if (pageSize < 1) pageSize = 20;
+            var q = _db.Queryable<PhotoCaptureRecord>();
+            if (!string.IsNullOrEmpty(recipeName)) q = q.Where(r => r.RecipeName == recipeName);
+            if (!string.IsNullOrEmpty(cameraName)) q = q.Where(r => r.CameraName == cameraName);
+            if (!string.IsNullOrEmpty(productSN)) q = q.Where(r => r.ProductSN == productSN);
+            if (start.HasValue) q = q.Where(r => r.CaptureTime >= start.Value);
+            if (end.HasValue) q = q.Where(r => r.CaptureTime <= end.Value);
+            var total = await q.CountAsync();
+            var list = await q.OrderBy(r => r.CaptureTime, OrderByType.Desc).ToPageListAsync(pageIndex, pageSize);
+            return (list, total);
+        }
+        #endregion
+
+        #region 组装过程记录
+
+        /// <summary>
+        /// 记录一次组装过程记录
+        /// </summary>
+        /// <param name="record">组装记录对象</param>
+        public async Task RecordAssemblyAsync(AssemblyRecord record)
+        {
+            if (record == null) throw new ArgumentNullException(nameof(record));
+            if (record.Timestamp == default(DateTime)) record.Timestamp = DateTime.UtcNow;
+            record.Id = record.Id == Guid.Empty ? Guid.NewGuid() : record.Id;
+            await _db.Insertable(record).ExecuteCommandAsync();
+        }
+
+        /// <summary>
+        /// 查询组装记录,支持按配方名、产品序列号和时间范围过滤
+        /// </summary>
+        public async Task<IEnumerable<AssemblyRecord>> QueryAssemblyRecordsAsync(string recipeName = null, string productSN = null, DateTime? start = null, DateTime? end = null)
+        {
+            var q = _db.Queryable<AssemblyRecord>();
+            if (!string.IsNullOrEmpty(recipeName)) q = q.Where(r => r.RecipeName == recipeName);
+            if (!string.IsNullOrEmpty(productSN)) q = q.Where(r => r.ProductSN == productSN);
+            if (start.HasValue) q = q.Where(r => r.Timestamp >= start.Value);
+            if (end.HasValue) q = q.Where(r => r.Timestamp < end.Value);
+            var list = await q.OrderBy(r => r.Timestamp, OrderByType.Desc).ToListAsync();
+            return list;
+        }
+
+        /// <summary>
+        /// 分页查询组装记录
+        /// </summary>
+        public async Task<(IEnumerable<AssemblyRecord> Items, int TotalCount)> QueryAssemblyRecordsPagedAsync(string recipeName = null, string productSN = null, DateTime? start = null, DateTime? end = null, int pageIndex = 1, int pageSize = 20)
+        {
+            if (pageIndex < 1) pageIndex = 1;
+            if (pageSize < 1) pageSize = 20;
+            var q = _db.Queryable<AssemblyRecord>();
+            if (!string.IsNullOrEmpty(recipeName)) q = q.Where(r => r.RecipeName == recipeName);
+            if (!string.IsNullOrEmpty(productSN)) q = q.Where(r => r.ProductSN == productSN);
+            if (start.HasValue) q = q.Where(r => r.Timestamp >= start.Value);
+            if (end.HasValue) q = q.Where(r => r.Timestamp < end.Value);
+            var total = await q.CountAsync();
+            var list = await q.OrderBy(r => r.Timestamp, OrderByType.Desc).ToPageListAsync(pageIndex, pageSize);
+            return (list, total);
+        }
+
+        #endregion
+
         // Lock result methods
         /// <summary>
         /// 记录单次锁付结果(WaveDatas 不写入数据库)

+ 5 - 0
TeamAAS-VM/Enums/ProcedureSaveImagePathModel.cs

@@ -43,5 +43,10 @@ namespace TeamAAS_VP.Enums
         [Description("..//yyyy-MM//MM-dd//NG//yyyy-MM-dd HH_mm_ss.png")]
         [Localization(ResourceName = "ProcedureSaveImagePathModel_Month_Day_Ng_Time", ResourceType = typeof(Lang))]
         Month_Day_Ng_Time = 3,
+
+        //年月/日/配方名/产品SN/产品SN+时间
+        [Description("..//yyyy-MM//MM-dd//产品配方名//产品SN//产品SN-yyyy-MM-dd HH_mm_ss.png")]
+        [Localization(ResourceName = "ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time", ResourceType = typeof(Lang))]
+        Month_Day_Formula_ProductSN_Time = 4
     }
 }

+ 4 - 0
TeamAAS-VM/Events/LockFinishNotification.cs

@@ -11,6 +11,10 @@ namespace TeamAAS_VP.Events
     {
     }
 
+    public class AssemblyFinishNotification : Prism.Events.PubSubEvent<AssemblyRecord>
+    {
+    }
+
     //保压完成通知
     public class PressureFinishNotification : Prism.Events.PubSubEvent<(bool IsSuccess, int Index, (DateTime Timestamp, float Value)[] values, string SavePath)>
     {

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

@@ -248,8 +248,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);
+        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>
         /// 执行相机拍照获取单个点位结果,并且返回图像和图形

+ 76 - 0
TeamAAS-VM/Interfaces/ISystemDatabaseService.cs

@@ -68,6 +68,37 @@ namespace TeamAAS_VP.Interfaces
         /// </returns>
         Task<IEnumerable<User>> GetAllUsersAsync();
 
+        // Assembly process records
+
+        /// <summary>
+        /// 将一条组装过程记录写入数据库。
+        /// </summary>
+        /// <param name="record">要记录的 <see cref="AssemblyRecord"/> 实例,包含时间戳、配方名、产品序列号、零件序列号、是否成功、组装用时、各类坐标、操作员、备注等信息。</param>
+        /// <returns>完成写入操作的任务。</returns>
+        Task RecordAssemblyAsync(AssemblyRecord record);
+
+        /// <summary>
+        /// 查询组装记录,支持按配方名、产品序列号和时间段过滤(所有参数可选)。
+        /// </summary>
+        /// <param name="recipeName">可选的配方名称过滤,传入 null 表示不过滤。</param>
+        /// <param name="productSN">可选的产品序列号过滤,传入 null 表示不过滤。</param>
+        /// <param name="start">可选的起始时间(含),传入 null 表示不限制开始时间。</param>
+        /// <param name="end">可选的结束时间(不含),传入 null 表示不限制结束时间。</param>
+        /// <returns>满足条件的组装记录集合;如果没有匹配项,可以返回空集合(建议不返回 null)。</returns>
+        Task<IEnumerable<AssemblyRecord>> QueryAssemblyRecordsAsync(string recipeName = null, string productSN = null, DateTime? start = null, DateTime? end = null);
+
+        /// <summary>
+        /// 分页查询组装记录,支持按配方名、产品序列号和时间段过滤(所有参数可选)。
+        /// </summary>
+        /// <param name="recipeName">可选的配方名称过滤,传入 null 表示不过滤。</param>
+        /// <param name="productSN">可选的产品序列号过滤,传入 null 表示不过滤。</param>
+        /// <param name="start">可选的起始时间(含),传入 null 表示不限制开始时间。</param>
+        /// <param name="end">可选的结束时间(不含),传入 null 表示不限制结束时间。</param>
+        /// <param name="pageIndex">页号(从 1 开始)。</param>
+        /// <param name="pageSize">每页大小。</param>
+        /// <returns>返回一个元组,包含记录集合和总记录数。</returns>
+        Task<(IEnumerable<AssemblyRecord> Items, int TotalCount)> QueryAssemblyRecordsPagedAsync(string recipeName = null, string productSN = null, DateTime? start = null, DateTime? end = null, int pageIndex = 1, int pageSize = 20);
+
         // User authentication
 
         /// <summary>
@@ -272,6 +303,17 @@ namespace TeamAAS_VP.Interfaces
         /// <returns></returns>
         Task<Dictionary<int, Dictionary<string, int>>> GetDailyProductionByHourAndCategoryAsync(string productName);
 
+        /// <summary>
+        /// 分页查询生产记录。
+        /// </summary>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <param name="pageIndex"></param>
+        /// <param name="pageSize"></param>
+        /// <param name="productName"></param>
+        /// <param name="category"></param>
+        /// <returns></returns>
+        Task<(IEnumerable<ProductionRecord> Items, int TotalCount)> QueryProductionRecordsPagedAsync(DateTime start, DateTime end, int pageIndex, int pageSize, string productName = null, string category = null);
 
         // Alarm records
 
@@ -329,5 +371,39 @@ namespace TeamAAS_VP.Interfaces
         /// 记录一次螺丝供料器批次更换记录
         /// </summary>
         Task RecordScrewFeederBatchAsync(ScrewFeederBatchRecord record);
+
+        /// <summary>
+        /// 记录产品拍照结果(含图片路径、机器人位置、像素与绝对坐标等)。
+        /// </summary>
+        /// <param name="record"></param>
+        /// <returns></returns>
+        Task RecordPhotoCaptureAsync(PhotoCaptureRecord record);
+
+        /// <summary>
+        /// 查询拍照记录,支持按配方名、产品序列号和时间段过滤(所有参数可选)。
+        /// </summary>
+        /// <param name="recipeName"></param>
+        /// <param name="cameraName"></param>
+        /// <param name="productSN"></param>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <returns></returns>
+        Task<IEnumerable<PhotoCaptureRecord>> QueryPhotoCapturesAsync(string recipeName = null, string cameraName = null, string productSN = null, DateTime? start = null, DateTime? end = null);
+
+        /// <summary>
+        /// 分页查询拍照记录,支持按配方名、产品序列号和时间段过滤(所有参数可选)。
+        /// </summary>
+        /// <param name="recipeName"></param>
+        /// <param name="cameraName"></param>
+        /// <param name="productSN"></param>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <param name="pageIndex"></param>
+        /// <param name="pageSize"></param>
+        /// <returns></returns>
+        Task<(IEnumerable<PhotoCaptureRecord> Items, int TotalCount)> QueryPhotoCapturesPagedAsync(string recipeName = null, string cameraName = null, string productSN = null, DateTime? start = null, DateTime? end = null, int pageIndex = 1, int pageSize = 20);
+
+        //组装过程记录
+
     }
 }

+ 132 - 0
TeamAAS-VM/Models/AssemblyRecord.cs

@@ -0,0 +1,132 @@
+using System;
+using SqlSugar;
+
+namespace TeamAAS_VP.Models
+{
+    /// <summary>
+    /// 组装记录实体,表示一次组装操作的详细信息(用于持久化到数据库的 AssemblyRecord 表)
+    /// </summary>
+    [SugarTable("AssemblyRecord")]
+    public class AssemblyRecord
+    {
+        /// <summary>
+        /// 主键,唯一标识
+        /// </summary>
+        [SugarColumn(IsPrimaryKey = true)]
+        public Guid Id { get; set; } = Guid.NewGuid();
+
+        /// <summary>
+        /// 时间戳
+        /// </summary>
+        public DateTime Timestamp { get; set; } = DateTime.UtcNow;
+
+        /// <summary>
+        /// 配方名称
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string RecipeName { get; set; }
+
+        /// <summary>
+        /// 产品序列号
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string ProductSN { get; set; }
+
+        /// <summary>
+        /// 零件序列号
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string PartSN { get; set; }
+
+        /// <summary>
+        /// 是否组装成功
+        /// </summary>
+        public bool Success { get; set; }
+
+        /// <summary>
+        /// 组装压力
+        /// </summary>
+        public double AssemblyPressure { get; set; }
+
+        /// <summary>
+        /// 组装用时(秒)
+        /// </summary>
+        public double AssemblyDurationSeconds { get; set; }
+
+        /// <summary>
+        /// 下相机拍摄的坐标1,字符串格式(例如 "x,y,z"),用于简化数据库存储,可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string DownCameraCoord1 { get; set; }
+        /// <summary>
+        /// 下相机拍摄的坐标2,字符串格式(例如 "x,y,z"),用于简化数据库存储,可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string DownCameraCoord2 { get; set; }
+        /// <summary>
+        /// 下相机拍摄的坐标3,字符串格式(例如 "x,y,z"),用于简化数据库存储,可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string DownCameraCoord3 { get; set; }
+        /// <summary>
+        /// 下相机拍摄的坐标4,字符串格式(例如 "x,y,z"),用于简化数据库存储,可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string DownCameraCoord4 { get; set; }
+
+        /// <summary>
+        /// 抓取运动过程中的相机坐标,字符串格式(例如 "x,y,z"),可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string PickMoveCameraCoord { get; set; }
+
+        /// <summary>
+        /// 放置运动过程的相机坐标1,字符串格式(例如 "x,y,z"),可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string PlaceMoveCameraCoord1 { get; set; }
+        /// <summary>
+        /// 放置运动过程的相机坐标2,字符串格式(例如 "x,y,z"),可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string PlaceMoveCameraCoord2 { get; set; }
+        /// <summary>
+        /// 放置运动过程的相机坐标3,字符串格式(例如 "x,y,z"),可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string PlaceMoveCameraCoord3 { get; set; }
+        /// <summary>
+        /// 放置运动过程的相机坐标4,字符串格式(例如 "x,y,z"),可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string PlaceMoveCameraCoord4 { get; set; }
+
+        /// <summary>
+        /// 实际放置坐标,字符串格式(例如 "x,y,z"),可用于记录放置位置的实际测量值
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string PlaceActualCoord { get; set; }
+
+        /// <summary>
+        /// 设备名称,可为空
+        /// </summary>
+        [SugarColumn(IsNullable = true, Length = 255)]
+        public string DeviceName { get; set; }
+        /// <summary>
+        /// 设备ID,关联设备的数字标识
+        /// </summary>
+        public int DeviceId { get; set; }
+
+        /// <summary>
+        /// 操作员名称,可为空
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string OperatorName { get; set; }
+
+        /// <summary>
+        /// 备注信息,可为空
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string Remark { get; set; }
+    }
+}

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

@@ -0,0 +1,87 @@
+using SqlSugar;
+using System;
+
+namespace TeamAAS_VP.Models
+{
+    [SugarTable("PhotoCaptureRecord")]
+    public class PhotoCaptureRecord
+    {
+        [SugarColumn(IsPrimaryKey = true)]
+        public Guid Id { get; set; } = Guid.NewGuid();
+
+        /// <summary>
+        /// 拍照时间
+        /// </summary>
+        public DateTime CaptureTime { get; set; } = DateTime.UtcNow;
+
+        /// <summary>
+        /// 配方名
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string RecipeName { get; set; }
+
+        /// <summary>
+        /// 产品序列号
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string ProductSN { get; set; }
+
+        /// <summary>
+        /// 相机名
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string CameraName { get; set; }
+
+        /// <summary>
+        /// 流程名
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string ProcessName { get; set; }
+
+        /// <summary>
+        /// 位置编号
+        /// </summary>
+        public int PositionIndex { get; set; }
+
+        /// <summary>
+        /// 是否成功
+        /// </summary>
+        public bool IsSuccess { get; set; }
+
+        /// <summary>
+        /// 机器人拍照位置
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string RobotPosition { get; set; }
+
+        /// <summary>
+        /// 像素坐标
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string PixelPosition { get; set; }
+
+        /// <summary>
+        /// 绝对坐标
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string AbsolutePosition { get; set; }
+
+        /// <summary>
+        /// 图片路径
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string ImagePath { get; set; }
+
+        /// <summary>
+        /// 备注
+        /// </summary>
+        [SugarColumn(Length = 1000, IsNullable = true)]
+        public string Remarks { get; set; }
+
+        /// <summary>
+        /// 当前的操作员名称
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string OperatorName { get; set; }
+    }
+}

+ 40 - 0
TeamAAS-VM/Models/Product/ProductModel.cs

@@ -316,6 +316,46 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref _IndependentCamer4AuxProcedureId, value); }
         }
 
+        private Guid _IndependentCamer1CheckProcedureId;
+        /// <summary>
+        /// 独立移动模组相机1检测任务拍照流程ID
+        /// </summary>
+        public Guid IndependentCamer1CheckProcedureId
+        {
+            get { return _IndependentCamer1CheckProcedureId; }
+            set { SetProperty(ref _IndependentCamer1CheckProcedureId, value); }
+        }
+
+        private Guid _IndependentCamer2CheckProcedureId;
+        /// <summary>
+        /// 独立移动模组相机2检测任务拍照流程ID
+        /// </summary>
+        public Guid IndependentCamer2CheckProcedureId
+        {
+            get { return _IndependentCamer2CheckProcedureId; }
+            set { SetProperty(ref _IndependentCamer2CheckProcedureId, value); }
+        }
+
+        private Guid _IndependentCamer3CheckProcedureId;
+        /// <summary>
+        /// 独立移动模组相机3检测任务拍照流程ID
+        /// </summary>
+        public Guid IndependentCamer3CheckProcedureId
+        {
+            get { return _IndependentCamer3CheckProcedureId; }
+            set { SetProperty(ref _IndependentCamer3CheckProcedureId, value); }
+        }
+
+        private Guid _IndependentCamer4CheckProcedureId;
+        /// <summary>
+        /// 独立移动模组相机4检测任务拍照流程ID
+        /// </summary>
+        public Guid IndependentCamer4CheckProcedureId
+        {
+            get { return _IndependentCamer4CheckProcedureId; }
+            set { SetProperty(ref _IndependentCamer4CheckProcedureId, value); }
+        }
+
         /// <summary>
         /// 移动向上的相机模板角度
         /// </summary>

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

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

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

@@ -2132,4 +2132,7 @@
   <data name="视觉静态精度分析" xml:space="preserve">
     <value>视觉静态精度分析</value>
   </data>
+  <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" xml:space="preserve">
+    <value>年月/日/配方名/产品SN/产品SN+时间</value>
+  </data>
 </root>

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

@@ -130,19 +130,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);
                 }
             }
 
@@ -235,7 +235,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);
                         }
@@ -269,7 +269,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

@@ -263,7 +263,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

@@ -460,22 +460,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);
                             }
 
                         }
@@ -526,7 +526,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);
                 }
             }
 
@@ -1015,16 +1015,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
                 {

+ 95 - 52
TeamAAS-VM/Services/RemoteCommandService.cs

@@ -1463,10 +1463,6 @@ namespace TeamAAS_VP.Services
                 {
                     SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
                 }
-                else
-                {
-                    SendTaskMessage($"曝光设置{procedure.ExposureTime}!", MessageLevel.Info);
-                }
                 succed = camera.SetGain(procedure.Gain);
                 if (!succed)
                 {
@@ -1474,7 +1470,7 @@ namespace TeamAAS_VP.Services
                 }
                 DateTime nowtime = DateTime.Now;
                 LogHelper.WriteLogInfo("开始采集图像");
-                Thread.Sleep(100);
+                Thread.Sleep(250);
                 var image = camera.Grab();
                 if (image == null)
                 {
@@ -1483,26 +1479,6 @@ namespace TeamAAS_VP.Services
                     outputCollection = null;
                     return false;
                 }
-                //图像畸变校正
-                var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
-                if (calib != null)
-                {
-                    if (calib.IsDistortionCorrection)
-                    {
-                        if (calib.CalibCheckerboardTool == null)
-                        {
-                            string prcPath = FilePath.CalibrationPath + "//" + calib.Name + "//" + "CalibCheckerboardTool.vpp";
-                            if (File.Exists(prcPath))
-                            {
-                                calib.CalibCheckerboardTool = CogSerializer.LoadObjectFromFile(prcPath) as Cognex.VisionPro.CalibFix.CogCalibCheckerboardTool;
-                                calib.CalibCheckerboardTool.InputImage = image;
-                                calib.CalibCheckerboardTool.Run();
-                                image = calib.CalibCheckerboardTool.OutputImage;
-                            }
-                        }
-                    }
-                }
-
                 procedure.ToolBlock.Inputs["InputImage"].Value = image;
                 LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
 
@@ -1596,13 +1572,13 @@ namespace TeamAAS_VP.Services
         /// <param name="outImage"></param>
         /// <param name="outGraphicCollection"></param>
         /// <returns></returns>
-        public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection, out ICogImage outImage, out CogGraphicCollection outGraphicCollection)
+        public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection,out ICogImage outImage,out CogGraphicCollection outGraphicCollection)
         {
             outImage = null;
             outGraphicCollection = null;
             try
             {
-
+                
                 // 1. 采集图像
                 var camera = _cameraService.GetCamera(procedure.CameraId);
                 bool succed = camera.SetExposureTime(procedure.ExposureTime);
@@ -1625,26 +1601,7 @@ namespace TeamAAS_VP.Services
                     outputCollection = null;
                     return false;
                 }
-                //图像畸变校正
-                var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
-                if (calib != null)
-                {
-                    if (calib.IsDistortionCorrection)
-                    {
-                        if (calib.CalibCheckerboardTool == null)
-                        {
-                            string prcPath = FilePath.CalibrationPath + "//" + calib.Name + "//" + "CalibCheckerboardTool.vpp";
-                            if (File.Exists(prcPath))
-                            {
-                                calib.CalibCheckerboardTool = CogSerializer.LoadObjectFromFile(prcPath) as Cognex.VisionPro.CalibFix.CogCalibCheckerboardTool;
-                                calib.CalibCheckerboardTool.InputImage = image;
-                                calib.CalibCheckerboardTool.Run();
-                                image = calib.CalibCheckerboardTool.OutputImage;
-                            }
-                        }
-                    }
-                }
-                outImage = image;
+                outImage= image;
                 procedure.ToolBlock.Inputs["InputImage"].Value = image;
                 LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
 
@@ -1682,7 +1639,7 @@ namespace TeamAAS_VP.Services
                         if (item.Value is ICogRecord)
                             record = item.Value as ICogRecord;
                     }
-                    outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
+                    outGraphicCollection= outputCollection["Graphic"].Value as CogGraphicCollection;
                     return true;
                 }
                 else
@@ -1710,12 +1667,13 @@ 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)
+        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);
-
             try
             {
                 //拍照失败时,需要多次拍照
@@ -1734,6 +1692,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, positionIndex, remark);
                         return (false, 0, 0, 0);
                     }
 
@@ -1747,6 +1706,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("开始获取视觉输出结果");
                     //获取相机校准
@@ -1764,22 +1730,27 @@ 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, 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, positionIndex, remark);
                         return (true, calibResult.X, calibResult.Y, calibResult.U);
                     }
                     else
                     {
+                        await RecordPhotoCaptureAsync(procedure, robotCoord, true, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
                         return (true, _pixel_x, _pixel_y, _pixel_u);
                     }
 
                 }
                 SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
+                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("执行相机取图并获取单点位时出错!", ex);
+                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
@@ -1789,6 +1760,78 @@ namespace TeamAAS_VP.Services
             }
         }
 
+        /// <summary>
+        /// 记录拍照结果数据至数据库
+        /// </summary>
+        /// <param name="procedure"></param>
+        /// <param name="robotCoord"></param>
+        /// <param name="isSuccess"></param>
+        /// <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, int positionIndex, string emarks)
+        {
+            try
+            {
+                //当前的产品配方名
+                string formulaName = _productService.GetCurrentProduct().Name;
+                //如果当前产品名称存在非法字符,则替换为下划线
+                foreach (char c in System.IO.Path.GetInvalidFileNameChars())
+                {
+                    formulaName = formulaName.Replace(c, '_');
+                }
+                //获取当前的产品SN
+                string productSN = _productService.CurrentProductCode;
+                //如果产品SN存在非法字符,则替换为下划线
+                foreach (char c in System.IO.Path.GetInvalidFileNameChars())
+                {
+                    productSN = productSN.Replace(c, '_');
+                }
+                //当前用户
+                string currentUser = _systemDatabaseService.GetCurrentUser()?.UserName;
+
+                //相机名称
+                string cameraName = procedure.CameraName;
+                //视觉流程名称
+                string procedureName = procedure.Name;
+                //如果机器人坐标为空,则获取当前机器人坐标
+                if (robotCoord == null)
+                {
+                    var robot = _robotService.GetAllRobots().FirstOrDefault();
+                    if (robot != null)
+                    {
+                        var pos = await robot.GetRobotPosAsync();
+                        robotCoord = new double[] { pos.X, pos.Y, pos.Z };
+                    }
+                    else
+                    {
+                        robotCoord = new double[] { 0, 0, 0 };
+                    }
+                }
+                PhotoCaptureRecord photoCaptureRecord = new PhotoCaptureRecord();
+                photoCaptureRecord.RecipeName = formulaName;
+                photoCaptureRecord.ProductSN = productSN;
+                photoCaptureRecord.CameraName = cameraName;
+                photoCaptureRecord.ProcessName = procedureName;
+                photoCaptureRecord.RobotPosition = string.Join(",", robotCoord);
+                photoCaptureRecord.IsSuccess = isSuccess;
+                photoCaptureRecord.PixelPosition = string.Join(",", pixelPosition);
+                photoCaptureRecord.AbsolutePosition = string.Join(",", absolutePosition);
+                photoCaptureRecord.ImagePath = imagePath;
+                photoCaptureRecord.Remarks = emarks;
+                photoCaptureRecord.OperatorName = currentUser;
+
+                await _systemDatabaseService.RecordPhotoCaptureAsync(photoCaptureRecord);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("记录拍照结果数据至数据库时出错", ex);
+            }
+        }
+
         /// <summary>
         /// 执行相机拍照获取单个点位结果,并且返回图像和图形
         /// </summary>
@@ -1801,8 +1844,8 @@ namespace TeamAAS_VP.Services
         {
             DateTime nowtime = DateTime.Now;
             await SetLightBeforePhoto(procedure);
-            ICogImage outImage = null;
-            CogGraphicCollection outGraphicCollection = null;
+            ICogImage outImage=null;
+            CogGraphicCollection outGraphicCollection=null;
             try
             {
                 //拍照失败时,需要多次拍照

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

@@ -534,10 +534,13 @@
     </Compile>
     <Compile Include="Core\RectangleCenterCalculator.cs" />
     <Compile Include="Core\StabilityAnalyzer.cs" />
+    <Compile Include="Core\VisionProFileHelper.cs" />
     <Compile Include="Events\MainTabSwitchNotification.cs" />
     <Compile Include="Interfaces\IMesService.cs" />
+    <Compile Include="Models\AssemblyRecord.cs" />
     <Compile Include="Models\DeviceInfo.cs" />
     <Compile Include="Models\Feeder\ScrewFeederInfo.cs" />
+    <Compile Include="Models\PhotoCaptureRecord.cs" />
     <Compile Include="Models\ScrewFeederBatchRecord.cs" />
     <Compile Include="Services\MesService.cs" />
     <Compile Include="ValueConverter\CountToColumnsConverter.cs" />
@@ -549,7 +552,10 @@
     <Compile Include="ViewModels\Product\VisionDynamicAccuracyAnalyzerViewModel.cs" />
     <Compile Include="ViewModels\Product\VisionStaticAccuracyAnalyzerViewModel.cs" />
     <Compile Include="ViewModels\Setting\AddScrewFeederViewModel.cs" />
+    <Compile Include="ViewModels\Statistics\AssemblyRecordQueryViewModel.cs" />
     <Compile Include="ViewModels\Statistics\LockResultRecoredQueryViewModel.cs" />
+    <Compile Include="ViewModels\Statistics\PhotoCaptureQueryViewModel.cs" />
+    <Compile Include="ViewModels\Statistics\ProductionRecordQueryViewModel.cs" />
     <Compile Include="ViewModels\User\CardLoginWindowViewModel.cs" />
     <Compile Include="Views\Calibration\CalibIndependentCamera.xaml.cs">
       <DependentUpon>CalibIndependentCamera.xaml</DependentUpon>
@@ -1072,9 +1078,18 @@
     <Compile Include="Views\Statistics\AlarmQuery.xaml.cs">
       <DependentUpon>AlarmQuery.xaml</DependentUpon>
     </Compile>
+    <Compile Include="Views\Statistics\AssemblyRecordQuery.xaml.cs">
+      <DependentUpon>AssemblyRecordQuery.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Views\Statistics\LockResultRecoredQuery.xaml.cs">
       <DependentUpon>LockResultRecoredQuery.xaml</DependentUpon>
     </Compile>
+    <Compile Include="Views\Statistics\PhotoCaptureQuery.xaml.cs">
+      <DependentUpon>PhotoCaptureQuery.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Statistics\ProductionRecordQuery.xaml.cs">
+      <DependentUpon>ProductionRecordQuery.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Views\Statistics\ProductionStatement.xaml.cs">
       <DependentUpon>ProductionStatement.xaml</DependentUpon>
     </Compile>
@@ -1470,10 +1485,22 @@
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
+    <Page Include="Views\Statistics\AssemblyRecordQuery.xaml">
+      <Generator>MSBuild:Compile</Generator>
+      <SubType>Designer</SubType>
+    </Page>
     <Page Include="Views\Statistics\LockResultRecoredQuery.xaml">
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
+    <Page Include="Views\Statistics\PhotoCaptureQuery.xaml">
+      <Generator>MSBuild:Compile</Generator>
+      <SubType>Designer</SubType>
+    </Page>
+    <Page Include="Views\Statistics\ProductionRecordQuery.xaml">
+      <Generator>MSBuild:Compile</Generator>
+      <SubType>Designer</SubType>
+    </Page>
     <Page Include="Views\Statistics\ProductionStatement.xaml">
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>

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

@@ -336,18 +336,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)

+ 2 - 2
TeamAAS-VM/ViewModels/Calibration/CalibrationDistortionViewModel.cs

@@ -131,7 +131,7 @@ namespace TeamAAS_VP.ViewModels.Calibration
                 }
                 SelectCalibration.CalibCheckerboardTool = CalibCheckerboardEdit.Subject;
                 //保存校准工具
-                CogSerializer.SaveObjectToFile(CalibCheckerboardEdit.Subject, calibToolPath);
+                VisionProFileHelper.SaveObjectToFileSafe(CalibCheckerboardEdit.Subject, calibToolPath);
                 
                 NavigationParameters param = new NavigationParameters();
                 param.Add("SelectCalibration", SelectCalibration);
@@ -206,7 +206,7 @@ namespace TeamAAS_VP.ViewModels.Calibration
                 string calibToolPath = FilePath.CalibrationPath + "//" + SelectCalibration.Name + "//" + "CalibCheckerboard.vpp";
                 if (System.IO.File.Exists(calibToolPath))
                 {
-                    SelectCalibration.CalibCheckerboardTool = CogSerializer.LoadObjectFromFile(calibToolPath) as CogCalibCheckerboardTool;
+                    SelectCalibration.CalibCheckerboardTool = VisionProFileHelper.LoadObjectFromFileSafe<CogCalibCheckerboardTool>(calibToolPath);
                     CalibCheckerboardEdit.Subject = SelectCalibration.CalibCheckerboardTool;
                 }
                 else

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

@@ -145,7 +145,7 @@ namespace TeamAAS_VP.ViewModels.Calibration
                     Directory.CreateDirectory(Path.GetDirectoryName(toolBlockPath));
                 }
                 //保存校准工具
-                CogSerializer.SaveObjectToFile(ToolBlockEdit.Subject, toolBlockPath);
+                VisionProFileHelper.SaveObjectToFileSafe(ToolBlockEdit.Subject, toolBlockPath);
                 NavigationParameters param = new NavigationParameters();
                 param.Add("SelectCalibration", SelectCalibration);
                 _regionManager.RequestNavigate("CalibrationRegionContext", "CalibrationTeachCenterPoint", param);

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

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

@@ -268,7 +268,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);
@@ -580,7 +580,7 @@ namespace TeamAAS_VP.ViewModels.Calibration
                         string prcPath = FilePath.CalibrationPath + "//" + SelectedCalibration.Name + "//" + "CalibCheckerboardTool.vpp";
                         if (File.Exists(prcPath))
                         {
-                            SelectedCalibration.CalibCheckerboardTool = CogSerializer.LoadObjectFromFile(prcPath) as Cognex.VisionPro.CalibFix.CogCalibCheckerboardTool;
+                            SelectedCalibration.CalibCheckerboardTool = VisionProFileHelper.LoadObjectFromFileSafe<Cognex.VisionPro.CalibFix.CogCalibCheckerboardTool>(prcPath);
                             SelectedCalibration.CalibCheckerboardTool.InputImage = image;
                             SelectedCalibration.CalibCheckerboardTool.Run();
                             image = SelectedCalibration.CalibCheckerboardTool.OutputImage;
@@ -643,11 +643,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);
             }
 
             if (SelectCalibration.RobotId != Guid.Empty)

+ 29 - 2
TeamAAS-VM/ViewModels/HomeViewModel.cs

@@ -158,6 +158,16 @@ namespace TeamAAS_VP.ViewModels
             set { SetProperty(ref _LockResults, value); }
         }
 
+        private ObservableCollection<AssemblyRecord> _AssemblyResults=new ObservableCollection<AssemblyRecord>();
+        /// <summary>
+        /// 组装结果列表
+        /// </summary>
+        public ObservableCollection<AssemblyRecord> AssemblyResults
+        {
+            get { return _AssemblyResults; }
+            set { SetProperty(ref _AssemblyResults, value); }
+        }
+
         // 可选:记录传感器 Id -> 索引 的映射,便于外部(如 Management)按 Id 更新
         private readonly Dictionary<string, int> _sensorIdToIndex = new Dictionary<string, int>();
         #endregion
@@ -204,6 +214,7 @@ namespace TeamAAS_VP.ViewModels
             _systemDatabaseService = systemDatabaseService;
             _eventAggregator.GetEvent<LockFinishNotification>().Subscribe(OnLockFinish);
             _eventAggregator.GetEvent<PressureFinishNotification>().Subscribe(OnPressureFinish);
+            _eventAggregator.GetEvent<AssemblyFinishNotification>().Subscribe(OnAssemblyFinish);
 
             //获取所有的压力传感器配置,初始化曲线图
             var systemConfig = _configService.GetSystemConfiguration();
@@ -375,7 +386,8 @@ namespace TeamAAS_VP.ViewModels
         /// </summary>
         async void ExecuteResetCounterCommand()
         {
-            if (management.CurrentProduct == null) return;
+            var currentProduct = _productService.GetCurrentProduct();
+            if (currentProduct == null) return;
             var view = new ShowMessage(Lang.计数清零, Lang.是否重置当前产品的计数);
             //show the dialog
             var result = await DialogHost.Show(view, "RootDialog", null, null, null);
@@ -384,7 +396,7 @@ namespace TeamAAS_VP.ViewModels
                 if (((bool)result))
                 {
                     isCanExecute = false;
-                    await _systemDatabaseService.ResetProductionAsync(management.CurrentProduct.Name);
+                    await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
                     isCanExecute = true;
                 }
             }
@@ -467,6 +479,21 @@ namespace TeamAAS_VP.ViewModels
 
         }
 
+        /// <summary>
+        /// 锁付完成时调用
+        /// </summary>
+        /// <param name="record"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void OnAssemblyFinish(AssemblyRecord record)
+        {
+            AssemblyResults.Add(record);
+            //如果记录数超过1000,则删除最早的记录
+            if (AssemblyResults.Count > 50)
+            {
+                AssemblyResults.RemoveAt(0);
+            }
+        }
+
         /// <summary>
         /// 保压完成时调用
         /// </summary>

+ 195 - 4
TeamAAS-VM/ViewModels/Product/PlcPointParamsViewModel.cs

@@ -2,6 +2,7 @@
 using MahApps.Metro.Controls;
 using MaterialDesignThemes.Wpf;
 using MathNet.Numerics.LinearAlgebra;
+using Microsoft.Win32;
 using NPOI.SS.Formula.Functions;
 using OpenCvSharp.Flann;
 using Prism.Commands;
@@ -14,10 +15,12 @@ using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Drawing;
+using System.IO;
 using System.Linq;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Windows;
+using System.Xml.Serialization;
 using TeamAAS_VP.Controls;
 using TeamAAS_VP.Core;
 using TeamAAS_VP.Core.PLCs;
@@ -311,6 +314,48 @@ 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 PlcPoint ScrewCameraLocalPos1 { get; set; }
+            public PlcPoint ScrewCameraLocalPos2 { get; set; }
+            public List<PlcPoint> ScrewPoints { get; set; }
+            public List<PlcPoint> CheckCameraPoints { get; set; }
+            public List<PlcPoint> IndependentCamerPoints { get; set; }
+            public List<PlcPoint> RemovePoints { get; set; }
+            public List<PlcPoint> PressurePlacePoints { get; set; }
+        }
+        #endregion
+
         #region 命令
         private DelegateCommand _NextCommand;
         public DelegateCommand NextCommand =>
@@ -436,6 +481,14 @@ namespace TeamAAS_VP.ViewModels.Product
         private DelegateCommand _SetOffsetCommand;
         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
 
         #region 事件
@@ -1343,8 +1396,8 @@ namespace TeamAAS_VP.ViewModels.Product
                 }
                 // 执行视觉任务
                 var _cts = new CancellationTokenSource();
-                var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token);
-                var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token);
+                var task1 = _remoteCommandService.ExecutePhotoGetSinglePointWithImage(process1, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token);
+                var task2 = _remoteCommandService.ExecutePhotoGetSinglePointWithImage(process2, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token);
                 var visionResults = await Task.WhenAll(task1, task2);
                 if (visionResults[0].IsSucceed && visionResults[1].IsSucceed)
                 {
@@ -1441,7 +1494,7 @@ namespace TeamAAS_VP.ViewModels.Product
                 }
                 // 执行视觉任务
                 var _cts = new CancellationTokenSource();
-                var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token);
+                var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePointWithImage(process1, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token);
                 if (visionResult.IsSucceed)
                 {
                     _PutPoints[0] = new OpenCvSharp.Point3f((float)visionResult.X, (float)visionResult.Y, (float)visionResult.U);
@@ -1483,7 +1536,7 @@ namespace TeamAAS_VP.ViewModels.Product
                 }
                 // 执行视觉任务
                 _cts = new CancellationTokenSource();
-                visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token);
+                visionResult = await _remoteCommandService.ExecutePhotoGetSinglePointWithImage(process2, null, new double[] { rpoint.X, rpoint.Y, rpoint.U }, _cts.Token);
                 if (visionResult.IsSucceed)
                 {
                     _PutPoints[1] = new OpenCvSharp.Point3f((float)visionResult.X, (float)visionResult.Y, (float)visionResult.U);
@@ -2017,6 +2070,144 @@ namespace TeamAAS_VP.ViewModels.Product
                 MessageBox.Show(ex.Message);
             }
         }
+
+        /// <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>(),
+                    ScrewCameraLocalPos1 = SelectProduct.ScrewCameraLocalPos1?.Clone() ?? new PlcPoint(),
+                    ScrewCameraLocalPos2 = SelectProduct.ScrewCameraLocalPos2?.Clone() ?? new PlcPoint(),
+                    ScrewPoints = SelectProduct.ScrewPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    CheckCameraPoints = SelectProduct.CheckCameraPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    IndependentCamerPoints = SelectProduct.IndependentCamerPoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    RemovePoints = SelectProduct.RemovePoints?.Select(p => p.Clone()).ToList() ?? new List<PlcPoint>(),
+                    PressurePlacePoints = SelectProduct.PressurePlacePoints?.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.ScrewCameraLocalPos1 = import.ScrewCameraLocalPos1 ?? new PlcPoint();
+                SelectProduct.ScrewCameraLocalPos2 = import.ScrewCameraLocalPos2 ?? new PlcPoint();
+                SelectProduct.ScrewPoints = new ObservableCollection<PlcPoint>(import.ScrewPoints ?? new List<PlcPoint>());
+                SelectProduct.CheckCameraPoints = new ObservableCollection<PlcPoint>(import.CheckCameraPoints ?? new List<PlcPoint>());
+                SelectProduct.IndependentCamerPoints = new ObservableCollection<PlcPoint>(import.IndependentCamerPoints ?? new List<PlcPoint>());
+                SelectProduct.RemovePoints = new ObservableCollection<PlcPoint>(import.RemovePoints ?? new List<PlcPoint>());
+                SelectProduct.PressurePlacePoints = new ObservableCollection<PlcPoint>(import.PressurePlacePoints ?? 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.CheckCameraPoints);
+                renumber(SelectProduct.IndependentCamerPoints);
+                renumber(SelectProduct.RemovePoints);
+                renumber(SelectProduct.PressurePlacePoints);
+
+                // 根据当前 SelectedIndex 切换 Points 绑定到对应集合
+                ExecuteSelectionChangedCommand();
+
+                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<CogToolBlock>(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<CogToolBlock>(prcPath) as CogToolBlock;
                 //    }
                 //    else
                 //    {
-                //        SelectProcedure.ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.SimpleProcedurePath) as CogToolBlock;
+                //        SelectProcedure.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(FilePath.SimpleProcedurePath) as CogToolBlock;
                 //    }
                 //}
 

+ 101 - 0
TeamAAS-VM/ViewModels/Product/ProductParamsViewModel.cs

@@ -340,6 +340,74 @@ namespace TeamAAS_VP.ViewModels.Product
             }
         }
 
+        private ProcedureModel _IndependentCamer1CheckProcedureId;
+        /// <summary>
+        /// 独立移动模组相机1检测任务拍照流程ID
+        /// </summary>
+        public ProcedureModel IndependentCamer1CheckProcedureId
+        {
+            get { return _IndependentCamer1CheckProcedureId; }
+            set
+            {
+                SetProperty(ref _IndependentCamer1CheckProcedureId, value);
+                if (value != null)
+                {
+                    SelectProduct.IndependentCamer1CheckProcedureId = value.Id;
+                }
+            }
+        }
+
+        private ProcedureModel _IndependentCamer2CheckProcedureId;
+        /// <summary>
+        /// 独立移动模组相机2检测任务拍照流程ID
+        /// </summary>
+        public ProcedureModel IndependentCamer2CheckProcedureId
+        {
+            get { return _IndependentCamer2CheckProcedureId; }
+            set
+            {
+                SetProperty(ref _IndependentCamer2CheckProcedureId, value);
+                if (value != null)
+                {
+                    SelectProduct.IndependentCamer2CheckProcedureId = value.Id;
+                }
+            }
+        }
+
+        private ProcedureModel _IndependentCamer3CheckProcedureId;
+        /// <summary>
+        /// 独立移动模组相机3检测任务拍照流程ID
+        /// </summary>
+        public ProcedureModel IndependentCamer3CheckProcedureId
+        {
+            get { return _IndependentCamer3CheckProcedureId; }
+            set
+            {
+                SetProperty(ref _IndependentCamer3CheckProcedureId, value);
+                if (value != null)
+                {
+                    SelectProduct.IndependentCamer3CheckProcedureId = value.Id;
+                }
+            }
+        }
+
+        private ProcedureModel _IndependentCamer4CheckProcedureId;
+        /// <summary>
+        /// 独立移动模组相机4检测任务拍照流程ID
+        /// </summary>
+        public ProcedureModel IndependentCamer4CheckProcedureId
+        {
+            get { return _IndependentCamer4CheckProcedureId; }
+            set
+            {
+                SetProperty(ref _IndependentCamer4CheckProcedureId, value);
+                if (value != null)
+                {
+                    SelectProduct.IndependentCamer4CheckProcedureId = value.Id;
+                }
+            }
+        }
+
         #endregion
 
         #region 命令
@@ -490,6 +558,22 @@ namespace TeamAAS_VP.ViewModels.Product
                 SelectProduct.IndependentCamer4AuxProcedureId = Guid.Empty;
             }
 
+            if (IndependentCamer1CheckProcedureId == null)
+            {
+                SelectProduct.IndependentCamer1CheckProcedureId = Guid.Empty;
+            }
+            if (IndependentCamer2CheckProcedureId == null)
+            {
+                SelectProduct.IndependentCamer2CheckProcedureId = Guid.Empty;
+            }
+            if (IndependentCamer3CheckProcedureId == null)
+            {
+                SelectProduct.IndependentCamer3CheckProcedureId = Guid.Empty;
+            }
+            if (IndependentCamer4CheckProcedureId == null)
+            {
+                SelectProduct.IndependentCamer4CheckProcedureId = Guid.Empty;
+            }
 
         }
 
@@ -612,6 +696,23 @@ namespace TeamAAS_VP.ViewModels.Product
                 {
                     IndependentCamer4ProductProcedureId = ProcedureModels.FirstOrDefault(p => p.Id == SelectProduct.IndependentCamer4ProductProcedureId);
                 }
+
+                if (SelectProduct.IndependentCamer1CheckProcedureId != Guid.Empty)
+                {
+                    IndependentCamer1CheckProcedureId = ProcedureModels.FirstOrDefault(p => p.Id == SelectProduct.IndependentCamer1CheckProcedureId);
+                }
+                if (SelectProduct.IndependentCamer2CheckProcedureId != Guid.Empty)
+                {
+                    IndependentCamer2CheckProcedureId = ProcedureModels.FirstOrDefault(p => p.Id == SelectProduct.IndependentCamer2CheckProcedureId);
+                }
+                if (SelectProduct.IndependentCamer3CheckProcedureId != Guid.Empty)
+                {
+                    IndependentCamer3CheckProcedureId = ProcedureModels.FirstOrDefault(p => p.Id == SelectProduct.IndependentCamer3CheckProcedureId);
+                }
+                if (SelectProduct.IndependentCamer4CheckProcedureId != Guid.Empty)
+                {
+                    IndependentCamer4CheckProcedureId = ProcedureModels.FirstOrDefault(p => p.Id == SelectProduct.IndependentCamer4CheckProcedureId);
+                }
             }
             catch (Exception ex)
             {

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

+ 260 - 0
TeamAAS-VM/ViewModels/Statistics/AssemblyRecordQueryViewModel.cs

@@ -0,0 +1,260 @@
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.ViewModels.Statistics
+{
+    public class AssemblyRecordQueryViewModel : BindableBase
+    {
+        private readonly IProductService _productService;
+        private readonly ISystemDatabaseService _systemDatabaseService;
+
+        public AssemblyRecordQueryViewModel(IProductService productService, ISystemDatabaseService systemDatabaseService)
+        {
+            _productService = productService;
+            _systemDatabaseService = systemDatabaseService;
+
+            PageSize = 20;
+            PageIndex = 1;
+
+            SearchCommand = new DelegateCommand(async () => await ExecuteSearchCommand(), CanSearch).ObservesProperty(() => SelectedProduct).ObservesProperty(() => StartDate).ObservesProperty(() => EndDate).ObservesProperty(() => IsSearching);
+            PrevPageCommand = new DelegateCommand(async () => { if (PageIndex > 1) { PageIndex--; await ExecuteSearchCommand(); } }).ObservesProperty(() => PageIndex);
+            NextPageCommand = new DelegateCommand(async () => { if (PageIndex * PageSize < TotalCount) { PageIndex++; await ExecuteSearchCommand(); } }).ObservesProperty(() => PageIndex).ObservesProperty(() => TotalCount);
+            ExportCommand = new DelegateCommand(async () => await ExecuteExportCommand(), CanExport).ObservesProperty(() => Results).ObservesProperty(() => IsSearching);
+
+            AllProduct = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
+            StartDate = DateTime.Now.Date;
+            EndDate = DateTime.Now.Date.AddDays(1);
+        }
+
+        #region Properties
+        private ObservableCollection<ProductModel> _AllProduct;
+        public ObservableCollection<ProductModel> AllProduct
+        {
+            get { return _AllProduct; }
+            set { SetProperty(ref _AllProduct, value); }
+        }
+
+        private ProductModel _SelectedProduct;
+        public ProductModel SelectedProduct
+        {
+            get { return _SelectedProduct; }
+            set { SetProperty(ref _SelectedProduct, value); }
+        }
+
+        private DateTime? _StartDate;
+        public DateTime? StartDate
+        {
+            get { return _StartDate; }
+            set { SetProperty(ref _StartDate, value); }
+        }
+
+        private DateTime? _EndDate;
+        public DateTime? EndDate
+        {
+            get { return _EndDate; }
+            set { SetProperty(ref _EndDate, value); }
+        }
+
+        private string _ProductNumber;
+        public string ProductNumber
+        {
+            get { return _ProductNumber; }
+            set { SetProperty(ref _ProductNumber, value); }
+        }
+
+        private ObservableCollection<AssemblyRecord> _Results = new ObservableCollection<AssemblyRecord>();
+        public ObservableCollection<AssemblyRecord> Results
+        {
+            get { return _Results; }
+            set { SetProperty(ref _Results, value); }
+        }
+
+        private int _PageIndex;
+        public int PageIndex
+        {
+            get { return _PageIndex; }
+            set { SetProperty(ref _PageIndex, value); }
+        }
+
+        private int _PageSize;
+        public int PageSize
+        {
+            get { return _PageSize; }
+            set { SetProperty(ref _PageSize, value); }
+        }
+
+        private int _TotalCount;
+        public int TotalCount
+        {
+            get { return _TotalCount; }
+            set { SetProperty(ref _TotalCount, value); }
+        }
+
+        private bool _IsSearching = false;
+        public bool IsSearching
+        {
+            get { return _IsSearching; }
+            set { SetProperty(ref _IsSearching, value); }
+        }
+        #endregion
+
+        #region Commands
+        public DelegateCommand SearchCommand { get; private set; }
+        public DelegateCommand PrevPageCommand { get; private set; }
+        public DelegateCommand NextPageCommand { get; private set; }
+        public DelegateCommand ExportCommand { get; private set; }
+        #endregion
+
+        private bool CanSearch()
+        {
+            if (IsSearching) return false;
+            if (SelectedProduct == null && string.IsNullOrWhiteSpace(ProductNumber))
+                return false;
+            if (!StartDate.HasValue || !EndDate.HasValue) return false;
+            return true;
+        }
+
+        private bool CanExport()
+        {
+            // allow export even if current page is empty; user may want to export all matching records
+            return !IsSearching && StartDate.HasValue && EndDate.HasValue && (SelectedProduct != null || !string.IsNullOrWhiteSpace(ProductNumber));
+        }
+
+        private async Task ExecuteSearchCommand()
+        {
+            try
+            {
+                IsSearching = true;
+
+                // determine time range (use full days)
+                var start = StartDate.HasValue ? StartDate.Value.Date : DateTime.MinValue;
+                var end = EndDate.HasValue ? EndDate.Value.Date.AddDays(1) : DateTime.MaxValue;
+
+                string productNumberFilter = null;
+                if (!string.IsNullOrWhiteSpace(ProductNumber)) productNumberFilter = ProductNumber.Trim();
+                // if SelectedProduct is selected, use its Name as productNumber? The user requested select product name then time range; productNumber precise search should still be supported
+                if (SelectedProduct != null && string.IsNullOrEmpty(productNumberFilter))
+                {
+                    // assume SelectedProduct.Name correspond to ProductNumber field used when storing
+                    productNumberFilter = SelectedProduct.Name;
+                }
+
+                int pageIndex = PageIndex < 1 ? 1 : PageIndex;
+                int pageSize = PageSize < 1 ? 20 : PageSize;
+
+                var res = await _systemDatabaseService.QueryAssemblyRecordsPagedAsync(productNumberFilter,ProductNumber, start, end, pageIndex, pageSize);
+                Results = new ObservableCollection<AssemblyRecord>(res.Items);
+                TotalCount = res.TotalCount;
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+            finally
+            {
+                IsSearching = false;
+            }
+        }
+
+        private async Task ExecuteExportCommand()
+        {
+            try
+            {
+                IsSearching = true;
+
+                // determine time range
+                var start = StartDate.HasValue ? StartDate.Value.Date : DateTime.MinValue;
+                var end = EndDate.HasValue ? EndDate.Value.Date.AddDays(1) : DateTime.MaxValue;
+
+                string productNumberFilter = null;
+                if (!string.IsNullOrWhiteSpace(ProductNumber)) productNumberFilter = ProductNumber.Trim();
+                if (SelectedProduct != null && string.IsNullOrEmpty(productNumberFilter))
+                {
+                    productNumberFilter = SelectedProduct.Name;
+                }
+
+                // fetch all matching records (not paged)
+                var all = await _systemDatabaseService.QueryAssemblyRecordsAsync(productNumberFilter, ProductNumber, start, end);
+                if (all == null || !all.Any())
+                {
+                    MessageBox.Show("没有找到符合条件的记录。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
+                    return;
+                }
+
+                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
+                {
+                    FileName = $"AssemblyRecords_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv",
+                    DefaultExt = ".csv",
+                    Filter = "CSV Files (*.csv)|*.csv"
+                };
+                var result = saveFileDialog.ShowDialog();
+                if (result != true) return;
+                var path = saveFileDialog.FileName;
+
+                // write in streaming manner to support large sets
+                using (var sw = new StreamWriter(path, false, Encoding.UTF8))
+                {
+                    // header matches AssemblyRecord properties shown in the UI, include all coordinate fields
+                    sw.WriteLine("Id,Timestamp,RecipeName,ProductSN,PartSN,Success,AssemblyPressure,AssemblyDurationSeconds,DownCameraCoord1,DownCameraCoord2,DownCameraCoord3,DownCameraCoord4,PickMoveCameraCoord,PlaceMoveCameraCoord1,PlaceMoveCameraCoord2,PlaceMoveCameraCoord3,PlaceMoveCameraCoord4,PlaceActualCoord,DeviceName,DeviceId,OperatorName,Remark");
+                    foreach (var r in all)
+                    {
+                        var line = string.Join(",",
+                            EscapeCsv(r.Id.ToString()),
+                            EscapeCsv(r.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")),
+                            EscapeCsv(r.RecipeName),
+                            EscapeCsv(r.ProductSN),
+                            EscapeCsv(r.PartSN),
+                            EscapeCsv(r.Success ? "1" : "0"),
+                            EscapeCsv(r.AssemblyPressure.ToString()),
+                            EscapeCsv(r.AssemblyDurationSeconds.ToString()),
+                            EscapeCsv(r.DownCameraCoord1),
+                            EscapeCsv(r.DownCameraCoord2),
+                            EscapeCsv(r.DownCameraCoord3),
+                            EscapeCsv(r.DownCameraCoord4),
+                            EscapeCsv(r.PickMoveCameraCoord),
+                            EscapeCsv(r.PlaceMoveCameraCoord1),
+                            EscapeCsv(r.PlaceMoveCameraCoord2),
+                            EscapeCsv(r.PlaceMoveCameraCoord3),
+                            EscapeCsv(r.PlaceMoveCameraCoord4),
+                            EscapeCsv(r.PlaceActualCoord),
+                            EscapeCsv(r.DeviceName),
+                            EscapeCsv(r.DeviceId.ToString()),
+                            EscapeCsv(r.OperatorName),
+                            EscapeCsv(r.Remark)
+                        );
+                        sw.WriteLine(line);
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+            finally
+            {
+                IsSearching = false;
+            }
+            await Task.CompletedTask;
+        }
+
+        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;
+        }
+    }
+}

+ 1 - 1
TeamAAS-VM/ViewModels/Statistics/LockResultRecoredQueryViewModel.cs

@@ -27,7 +27,7 @@ namespace TeamAAS_VP.ViewModels.Statistics
             PageIndex = 1;
 
             SearchCommand = new DelegateCommand(async () => await ExecuteSearchCommand(), CanSearch).ObservesProperty(() => SelectedProduct).ObservesProperty(() => StartDate).ObservesProperty(() => EndDate).ObservesProperty(() => IsSearching);
-            PrevPageCommand = new DelegateCommand(async () => { if (PageIndex>1) { PageIndex--; await ExecuteSearchCommand(); } }).ObservesProperty(() => PageIndex);
+            PrevPageCommand = new DelegateCommand(async () => { if (PageIndex > 1) { PageIndex--; await ExecuteSearchCommand(); } }).ObservesProperty(() => PageIndex);
             NextPageCommand = new DelegateCommand(async () => { if (PageIndex * PageSize < TotalCount) { PageIndex++; await ExecuteSearchCommand(); } }).ObservesProperty(() => PageIndex).ObservesProperty(() => TotalCount);
             ExportCommand = new DelegateCommand(async () => await ExecuteExportCommand(), CanExport).ObservesProperty(() => Results).ObservesProperty(() => IsSearching);
 

+ 191 - 0
TeamAAS-VM/ViewModels/Statistics/PhotoCaptureQueryViewModel.cs

@@ -0,0 +1,191 @@
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using TeamAAS_VP.Controls;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Services;
+
+namespace TeamAAS_VP.ViewModels.Statistics
+{
+    public class PhotoCaptureQueryViewModel : BindableBase
+    {
+        private readonly ISystemDatabaseService _systemDatabaseService;
+        private readonly IProductService _productService;
+        private readonly IConfigService _configService;
+
+        public PhotoCaptureQueryViewModel(ISystemDatabaseService systemDatabaseService, IProductService productService, IConfigService configService)
+        {
+            _systemDatabaseService = systemDatabaseService;
+            _productService = productService;
+            _configService = configService;
+            PageSize = 20; PageIndex = 1;
+            StartDate = DateTime.Now.Date; EndDate = DateTime.Now.Date.AddDays(1);
+            SearchCommand = new DelegateCommand(async () => await ExecuteSearchCommand());
+            PrevPageCommand = new DelegateCommand(async () => { if (PageIndex > 1) { PageIndex--; await ExecuteSearchCommand(); } });
+            NextPageCommand = new DelegateCommand(async () => { if (PageIndex * PageSize < TotalCount) { PageIndex++; await ExecuteSearchCommand(); } });
+            ExportCommand = new DelegateCommand(async () => await ExecuteExportCommand());
+        }
+
+        private ObservableCollection<ProductModel> _AllProduct;
+        public ObservableCollection<ProductModel> AllProduct
+        {
+            get { return _AllProduct; }
+            set { SetProperty(ref _AllProduct, value); }
+        }
+
+        private ProductModel _SelectedProduct;
+        public ProductModel SelectedProduct
+        {
+            get { return _SelectedProduct; }
+            set { SetProperty(ref _SelectedProduct, value); }
+        }
+
+        private ObservableCollection<CameraInfo> _AllCamera;
+        public ObservableCollection<CameraInfo> AllCamera
+        {
+            get { return _AllCamera; }
+            set { SetProperty(ref _AllCamera, value); }
+        }
+
+        private CameraInfo _SelectedCamera;
+        public CameraInfo SelectedCamera
+        {
+            get { return _SelectedCamera; }
+            set { SetProperty(ref _SelectedCamera, value); }
+        }
+        private string _ProductSN;
+        public string ProductSN
+        {
+            get { return _ProductSN; }
+            set { SetProperty(ref _ProductSN, value); }
+        }
+
+        private DateTime? _StartDate;
+        public DateTime? StartDate
+        {
+            get { return _StartDate; }
+            set { SetProperty(ref _StartDate, value); }
+        }
+
+        private DateTime? _EndDate;
+        public DateTime? EndDate
+        {
+            get { return _EndDate; }
+            set { SetProperty(ref _EndDate, value); }
+        }
+
+        private ObservableCollection<PhotoCaptureRecord> _Results;
+        public ObservableCollection<PhotoCaptureRecord> Results
+        {
+            get { return _Results; }
+            set { SetProperty(ref _Results, value); }
+        }
+
+        private int _PageIndex;
+        public int PageIndex
+        {
+            get { return _PageIndex; }
+            set { SetProperty(ref _PageIndex, value); }
+        }
+        private int _PageSize;
+        public int PageSize
+        {
+            get { return _PageSize; }
+            set { SetProperty(ref _PageSize, value); }
+        }
+        private int _TotalCount;
+        public int TotalCount
+        {
+            get { return _TotalCount; }
+            set { SetProperty(ref _TotalCount, value); }
+        }
+
+        public DelegateCommand SearchCommand { get; private set; }
+        public DelegateCommand PrevPageCommand { get; private set; }
+        public DelegateCommand NextPageCommand { get; private set; }
+        public DelegateCommand ExportCommand { get; private set; }
+
+        private DelegateCommand _LoadedCommand;
+        public DelegateCommand LoadedCommand =>
+            _LoadedCommand ?? (_LoadedCommand = new DelegateCommand(ExecuteLoadedCommand));
+        void ExecuteLoadedCommand()
+        {
+            AllProduct = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
+            AllCamera = new ObservableCollection<CameraInfo>(_configService.GetAllCameras());
+        }
+
+        private async Task ExecuteSearchCommand()
+        {
+            try
+            {
+                var start = StartDate.HasValue ? StartDate.Value : (DateTime?)null;
+                var end = EndDate.HasValue ? EndDate.Value : (DateTime?)null;
+                var res = await _systemDatabaseService.QueryPhotoCapturesAsync(SelectedProduct?.Name, SelectedCamera?.CameraName, ProductSN, start, end);
+                Results = new ObservableCollection<PhotoCaptureRecord>(res);
+                TotalCount = Results.Count;
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+        }
+
+        private async Task ExecuteExportCommand()
+        {
+            try
+            {
+                var start = StartDate.HasValue ? StartDate.Value : (DateTime?)null;
+                var end = EndDate.HasValue ? EndDate.Value : (DateTime?)null;
+                var all = await _systemDatabaseService.QueryPhotoCapturesAsync(SelectedProduct?.Name, SelectedCamera?.CameraName, ProductSN, start, end);
+                if (all == null || !all.Any()) { MessageBox.Show("没有找到符合条件的记录", "提示", MessageBoxButton.OK, MessageBoxImage.Information); return; }
+                var dlg = new Microsoft.Win32.SaveFileDialog { FileName = $"PhotoCapture_{DateTime.Now:yyyyMMddHHmmss}.csv", DefaultExt = ".csv", Filter = "CSV Files (*.csv)|*.csv" };
+                if (dlg.ShowDialog() != true) return;
+                var path = dlg.FileName;
+                using (var sw = new StreamWriter(path, false, Encoding.UTF8))
+                {
+                    sw.WriteLine("Id,CaptureTime,RecipeName,ProcessName,CameraName,ProductSN,PositionIndex,IsSuccess,RobotPosition,PixelPosition,AbsolutePosition,ImagePath,OperatorName,Remarks");
+                    foreach (var r in all)
+                    {
+                        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)
+                        ));
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                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;
+        }
+    }
+}

+ 167 - 0
TeamAAS-VM/ViewModels/Statistics/ProductionRecordQueryViewModel.cs

@@ -0,0 +1,167 @@
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.ObjectModel;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models.Product;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.ViewModels.Statistics
+{
+    public class ProductionRecordQueryViewModel : BindableBase
+    {
+        private readonly IProductService _productService;
+        private readonly ISystemDatabaseService _systemDatabaseService;
+
+        public ProductionRecordQueryViewModel(IProductService productService, ISystemDatabaseService systemDatabaseService)
+        {
+            _productService = productService;
+            _systemDatabaseService = systemDatabaseService;
+
+            PageSize = 20;
+            PageIndex = 1;
+            AllProduct = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
+            Categories = new ObservableCollection<string>();
+
+            StartDate = DateTime.Now.Date;
+            EndDate = DateTime.Now.Date.AddDays(1);
+
+            SearchCommand = new DelegateCommand(async () => await ExecuteSearchCommand()).ObservesProperty(() => SelectedProduct).ObservesProperty(() => StartDate).ObservesProperty(() => EndDate);
+            PrevPageCommand = new DelegateCommand(async () => { if (PageIndex > 1) { PageIndex--; await ExecuteSearchCommand(); } }).ObservesProperty(() => PageIndex);
+            NextPageCommand = new DelegateCommand(async () => { if (PageIndex * PageSize < TotalCount) { PageIndex++; await ExecuteSearchCommand(); } }).ObservesProperty(() => PageIndex).ObservesProperty(() => TotalCount);
+            ExportCommand = new DelegateCommand(async () => await ExecuteExportCommand()).ObservesProperty(() => Results);
+        }
+
+        public ObservableCollection<ProductModel> AllProduct { get; set; }
+        public ObservableCollection<string> Categories { get; set; }
+
+        private ProductModel _SelectedProduct;
+        public ProductModel SelectedProduct { get => _SelectedProduct; set { SetProperty(ref _SelectedProduct, value); if (value != null) LoadCategoriesForProduct(value.Name); } }
+
+        private string _SelectedCategory;
+        public string SelectedCategory { get => _SelectedCategory; set { SetProperty(ref _SelectedCategory, value); } }
+
+        private DateTime? _StartDate;
+        public DateTime? StartDate { get => _StartDate; set { SetProperty(ref _StartDate, value); } }
+
+        private DateTime? _EndDate;
+        public DateTime? EndDate { get => _EndDate; set { SetProperty(ref _EndDate, value); } }
+
+        private ObservableCollection<ProductionRecord> _Results = new ObservableCollection<ProductionRecord>();
+        public ObservableCollection<ProductionRecord> Results { get => _Results; set { SetProperty(ref _Results, value); } }
+
+        private int _PageIndex;
+        public int PageIndex
+        {
+            get { return _PageIndex; }
+            set { SetProperty(ref _PageIndex, value); }
+        }
+        private int _PageSize;
+        public int PageSize
+        {
+            get { return _PageSize; }
+            set { SetProperty(ref _PageSize, value); }
+        }
+        private int _TotalCount;
+        public int TotalCount
+        {
+            get { return _TotalCount; }
+            set { SetProperty(ref _TotalCount, value); }
+        }
+
+        public DelegateCommand SearchCommand { get; private set; }
+        public DelegateCommand PrevPageCommand { get; private set; }
+        public DelegateCommand NextPageCommand { get; private set; }
+        public DelegateCommand ExportCommand { get; private set; }
+
+        private DelegateCommand _LoadedCommand;
+        public DelegateCommand LoadedCommand =>
+            _LoadedCommand ?? (_LoadedCommand = new DelegateCommand(ExecuteLoadedCommand));
+        void ExecuteLoadedCommand()
+        {
+            AllProduct = new ObservableCollection<ProductModel>(_productService.GetAllProducts());
+        }
+
+        private async Task ExecuteSearchCommand()
+        {
+            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 res = await _systemDatabaseService.QueryProductionRecordsPagedAsync(start, end, PageIndex, PageSize, productName, SelectedCategory);
+                Results = new ObservableCollection<ProductionRecord>(res.Items);
+                TotalCount = res.TotalCount;
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message, "´íÎó", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+        }
+
+        private async Task ExecuteExportCommand()
+        {
+            try
+            {
+                // 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("Id,Timestamp,ProductName,ProductCode,DeviceId,DeviceName,Category,Quantity,UserName,Remark");
+                    foreach (var r in Results)
+                    {
+                        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)
+                        ));
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message, "´íÎó", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+            await Task.CompletedTask;
+        }
+
+        private async void LoadCategoriesForProduct(string productName)
+        {
+            try
+            {
+                Categories.Clear();
+                var cats = await _systemDatabaseService.GetProductCategoriesAsync(productName);
+                if (cats != null)
+                {
+                    foreach (var c in cats) Categories.Add(c);
+                }
+            }
+            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;
+        }
+    }
+}

+ 19 - 15
TeamAAS-VM/ViewModels/Statistics/ProductionStatementViewModel.cs

@@ -14,6 +14,7 @@ using TeamAAS_VP.Data;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.Services;
 using static MaterialDesignThemes.Wpf.Theme.ToolBar;
 
 namespace TeamAAS_VP.ViewModels.Statistics
@@ -22,8 +23,7 @@ namespace TeamAAS_VP.ViewModels.Statistics
     {
         IContainerProvider _container;
         ISystemDatabaseService _systemDatabaseService;
-
-        Management management;
+        IProductService _productService;
 
         #region 属性
         private Int64 _TotalCount;
@@ -119,27 +119,27 @@ namespace TeamAAS_VP.ViewModels.Statistics
 
         #endregion
 
-        public ProductionStatementViewModel(IContainerProvider container, ISystemDatabaseService systemDatabaseService)
+        public ProductionStatementViewModel(IContainerProvider container, ISystemDatabaseService systemDatabaseService, IProductService productService)
         {
             _container= container;
             _systemDatabaseService = systemDatabaseService;
+            _productService = productService;
         }
 
         #region 方法
         async void ExecuteLoadedCommand()
         {
-            if (management == null)
-                management = _container.Resolve<Management>();
-            if (management.CurrentProduct == null) return;
-           await  App.Current.Dispatcher.InvokeAsync(new Action(async () => {
-                YieldChartModel = CreateYieldChartModel(await _systemDatabaseService.GetProductionByCategoriesAsync(management.CurrentProduct.Name));
-               TotalCount = await _systemDatabaseService.GetOverallProductionAsync(management.CurrentProduct.Name);
-                MonthCount = await _systemDatabaseService.GetCurrentMonthProductionAsync(management.CurrentProduct.Name);
-               WeekCount = await _systemDatabaseService.GetCurrentWeekProductionAsync(management.CurrentProduct.Name);
-               DayCount = await _systemDatabaseService.GetTodayProductionAsync(management.CurrentProduct.Name);
-               MonthChartModel = CreateMonth(await _systemDatabaseService.GetMonthlyProductionByDayAndCategoryAsync(management.CurrentProduct.Name));
-                WeekChartModel = CreateWeek(await _systemDatabaseService.GetWeeklyProductionByDayAndCategoryAsync(management.CurrentProduct.Name));
-                DayChartModel = CreateDay(await _systemDatabaseService.GetDailyProductionByHourAndCategoryAsync(management.CurrentProduct.Name));
+            var currentproduct = _productService.GetCurrentProduct();
+            if (currentproduct == null) return;
+            await  App.Current.Dispatcher.InvokeAsync(new Action(async () => {
+                YieldChartModel = CreateYieldChartModel(await _systemDatabaseService.GetProductionByCategoriesAsync(currentproduct.Name));
+               TotalCount = await _systemDatabaseService.GetOverallProductionAsync(currentproduct.Name);
+                MonthCount = await _systemDatabaseService.GetCurrentMonthProductionAsync(currentproduct.Name);
+               WeekCount = await _systemDatabaseService.GetCurrentWeekProductionAsync(currentproduct.Name);
+               DayCount = await _systemDatabaseService.GetTodayProductionAsync(currentproduct.Name);
+               MonthChartModel = CreateMonth(await _systemDatabaseService.GetMonthlyProductionByDayAndCategoryAsync(currentproduct.Name));
+                WeekChartModel = CreateWeek(await _systemDatabaseService.GetWeeklyProductionByDayAndCategoryAsync(currentproduct.Name));
+                DayChartModel = CreateDay(await _systemDatabaseService.GetDailyProductionByHourAndCategoryAsync(currentproduct.Name));
             }));
             
         }
@@ -405,6 +405,10 @@ namespace TeamAAS_VP.ViewModels.Statistics
 
             model.Axes.Add(ay1);
             model.Axes.Add(ax);
+            if (Items.Count==0)
+            {
+                return model;
+            }
 
             foreach (var category in Items.First().Value.Keys)
             {

+ 64 - 10
TeamAAS-VM/Views/Home/ShowVisionRender.xaml.cs

@@ -37,6 +37,8 @@ namespace TeamAAS_VP.Views.Home
         Dictionary<Guid, TextBlock> Titles;
         IEventAggregator _eventAggregator;
         ISystemDatabaseService _systemDatabaseService;
+        IProductService _productService;
+
         public ShowVisionRender()
         {
             InitializeComponent();
@@ -45,6 +47,7 @@ namespace TeamAAS_VP.Views.Home
             viewModel = DataContext as ShowVisionRenderViewModel;
             _eventAggregator = viewModel._eventAggregator;
             _systemDatabaseService= ((Prism.PrismApplicationBase)App.Current).Container.Resolve<ISystemDatabaseService>();
+            _productService = ((Prism.PrismApplicationBase)App.Current).Container.Resolve<IProductService>();
             viewModel.UpdateLayout += ViewModel_UpdateLayout;
             _eventAggregator.GetEvent<RenderUpdateNotification>().Subscribe(UpdateRenderModuleSource);
             _eventAggregator.GetEvent<ProductChangedNotification>().Subscribe(ProductChanged);
@@ -829,16 +832,6 @@ namespace TeamAAS_VP.Views.Home
             }
         }
 
-        /// <summary>
-        /// 保存图像
-        /// </summary>
-        /// <param name="saveImageModel">要保存图像的模式</param>
-        /// <param name="saveImagePathModel">图像保存路径类型</param>
-        /// <param name="path">保存图像的文件夹路径</param>
-        /// <param name="image">原图像</param>
-        /// <param name="reimage">渲染图像</param>
-        /// <param name="result">拍照结果</param>
-        /// <param name="isCompress">是否压缩</param>
         private void SaveImage(ProcedureSaveImageModel saveImageModel, ProcedureSaveImagePathModel saveImagePathModel, string path, ICogImage image, Bitmap reimage, bool result, bool isCompress)
         {
 
@@ -889,6 +882,26 @@ namespace TeamAAS_VP.Views.Home
                                 return;
                             }
                         }
+                        else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
+                        {
+                            //当前的产品配方名
+                            string formulaName = _productService.GetCurrentProduct().Name;
+                            //如果当前产品名称存在非法字符,则替换为下划线
+                            foreach (char c in Path.GetInvalidFileNameChars())
+                            {
+                                formulaName = formulaName.Replace(c, '_');
+                            }
+                            //获取当前的产品SN
+                            string productSN = _productService.CurrentProductCode;
+                            //如果产品SN存在非法字符,则替换为下划线
+                            foreach (char c in Path.GetInvalidFileNameChars())
+                            {
+                                productSN = productSN.Replace(c, '_');
+                            }
+                            //拍照结果
+                            string resultStr = result ? "OK" : "NG";
+                            Originalpath = $"{path}\\{now.ToString("yyyy-MM")}\\{now.ToString("MM-dd")}\\{formulaName}\\{productSN}\\{productSN}-{now.ToString("yyyy-MM-dd HH_mm_ss")}-{resultStr}.bmp";
+                        }
                         if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))   //判断文件夹是否存在
                         {
                             Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));    //创建文件夹
@@ -936,6 +949,26 @@ namespace TeamAAS_VP.Views.Home
                                 return;
                             }
                         }
+                        else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
+                        {
+                            //当前的产品配方名
+                            string formulaName = _productService.GetCurrentProduct().Name;
+                            //如果当前产品名称存在非法字符,则替换为下划线
+                            foreach (char c in Path.GetInvalidFileNameChars())
+                            {
+                                formulaName = formulaName.Replace(c, '_');
+                            }
+                            //获取当前的产品SN
+                            string productSN = _productService.CurrentProductCode;
+                            //如果产品SN存在非法字符,则替换为下划线
+                            foreach (char c in Path.GetInvalidFileNameChars())
+                            {
+                                productSN = productSN.Replace(c, '_');
+                            }
+                            //拍照结果
+                            string resultStr = result ? "OK" : "NG";
+                            Recordedpath = $"{path}\\{now.ToString("yyyy-MM")}\\{now.ToString("MM-dd")}\\{formulaName}\\{productSN}\\{productSN}-{now.ToString("yyyy-MM-dd HH_mm_ss")}-{resultStr}.bmp";
+                        }
                         if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))   //判断文件夹是否存在
                         {
                             Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));    //创建文件夹
@@ -992,6 +1025,27 @@ namespace TeamAAS_VP.Views.Home
                                 return;
                             }
                         }
+                        else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
+                        {
+                            //当前的产品配方名
+                            string formulaName = _productService.GetCurrentProduct().Name;
+                            //如果当前产品名称存在非法字符,则替换为下划线
+                            foreach (char c in Path.GetInvalidFileNameChars())
+                            {
+                                formulaName = formulaName.Replace(c, '_');
+                            }
+                            //获取当前的产品SN
+                            string productSN = _productService.CurrentProductCode;
+                            //如果产品SN存在非法字符,则替换为下划线
+                            foreach (char c in Path.GetInvalidFileNameChars())
+                            {
+                                productSN = productSN.Replace(c, '_');
+                            }
+                            //拍照结果
+                            string resultStr = result ? "OK" : "NG";
+                            Originalpath = $"{path}\\Original\\{now.ToString("yyyy-MM")}\\{now.ToString("MM-dd")}\\{formulaName}\\{productSN}\\{productSN}-{now.ToString("yyyy-MM-dd HH_mm_ss")}-{resultStr}.bmp";
+                            Recordedpath = $"{path}\\Recored\\{now.ToString("yyyy-MM")}\\{now.ToString("MM-dd")}\\{formulaName}\\{productSN}\\{productSN}-{now.ToString("yyyy-MM-dd HH_mm_ss")}-{resultStr}.bmp";
+                        }
                         if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))   //判断文件夹是否存在
                         {
                             Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));    //创建文件夹

+ 15 - 19
TeamAAS-VM/Views/HomeView.xaml

@@ -132,7 +132,7 @@
                                    FontSize="{DynamicResource Font.Size.Body3}"
                                    Text="视觉引导定位数据:" />
                         <DataGrid x:Name="lockResultGrid"
-                                  ItemsSource="{Binding LockResults}"
+                                  ItemsSource="{Binding AssemblyResults}"
                                   AutoGenerateColumns="False"
                                   CanUserAddRows="False"
                                   CanUserDeleteRows="False"
@@ -145,31 +145,23 @@
                                   HorizontalAlignment="Stretch"
                                   Margin="0,8,0,0">
                             <DataGrid.Columns>
-                                <DataGridTextColumn Header="#"
-                                                    Binding="{Binding Number}"
-                                                    Width="auto"
-                                                    IsReadOnly="True" />
                                 <DataGridTextColumn Header="产品编号"
-                                                    Binding="{Binding ProductNumber}"
+                                                    Binding="{Binding ProductSN}"
                                                     Width="auto"
                                                     IsReadOnly="True" />
                                 <DataGridTextColumn Header="时间"
                                                     Binding="{Binding Timestamp, StringFormat={}{0:G}}"
                                                     Width="auto"
                                                     IsReadOnly="True" />
-                                <DataGridTextColumn Header="程序号"
-                                                    Binding="{Binding ScrewdriverProgramNumber}"
-                                                    Width="auto"
-                                                    IsReadOnly="True" />
-                                <DataGridTextColumn Header="锁付圈数"
-                                                    Binding="{Binding LockTurns, StringFormat={}{0:F1}}"
+                                <DataGridTextColumn Header="组装压力"
+                                                    Binding="{Binding AssemblyPressure, StringFormat={}{0:F3}}"
                                                     Width="auto"
                                                     IsReadOnly="True" />
-                                <DataGridTextColumn Header="锁付扭矩"
-                                                    Binding="{Binding LockTorque, StringFormat={}{0:F3}}"
+                                <DataGridTextColumn Header="组装用时(s)"
+                                                    Binding="{Binding AssemblyDurationSeconds, StringFormat={}{0:F3}}"
                                                     Width="auto"
                                                     IsReadOnly="True" />
-                                <DataGridTemplateColumn Header="锁付结果"
+                                <DataGridTemplateColumn Header="组装结果"
                                                         Width="auto"
                                                         IsReadOnly="True">
                                     <DataGridTemplateColumn.CellTemplate>
@@ -187,7 +179,7 @@
                                                            FontWeight="Bold" />
                                             </Border>
                                             <DataTemplate.Triggers>
-                                                <DataTrigger Binding="{Binding LockPassed, StringFormat={}{0:F3}}"
+                                                <DataTrigger Binding="{Binding Success, StringFormat={}{0:F3}}"
                                                              Value="True">
                                                     <Setter TargetName="bd"
                                                             Property="Background"
@@ -196,7 +188,7 @@
                                                             Property="Text"
                                                             Value="OK" />
                                                 </DataTrigger>
-                                                <DataTrigger Binding="{Binding LockPassed, StringFormat={}{0:F3}}"
+                                                <DataTrigger Binding="{Binding Success, StringFormat={}{0:F3}}"
                                                              Value="False">
                                                     <Setter TargetName="bd"
                                                             Property="Background"
@@ -209,8 +201,12 @@
                                         </DataTemplate>
                                     </DataGridTemplateColumn.CellTemplate>
                                 </DataGridTemplateColumn>
-                                <DataGridTextColumn Header="压力"
-                                                    Binding="{Binding Pressure, StringFormat={}{0:F3}}"
+                                <DataGridTextColumn Header="下相机工具坐标"
+                                                    Binding="{Binding DownCameraCoord1}"
+                                                    Width="auto"
+                                                    IsReadOnly="True" />
+                                <DataGridTextColumn Header="实际放置坐标"
+                                                    Binding="{Binding PlaceActualCoord}"
                                                     Width="auto"
                                                     IsReadOnly="True" />
                                 <DataGridTextColumn Header="详情"

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

@@ -353,6 +353,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="CAD导入点位"
                                     Margin="5,2"
                                     MinWidth="80"

+ 5 - 5
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)
@@ -73,12 +73,12 @@ namespace TeamAAS_VP.Views.Product
         {
             if (e.PropertyName == "Image")
             {
-                if (this.display.Image==null)
+                if (this.display.Image == null)
                 {
                     this.display.Image = VM.Image;
                     //图像中心点坐标
-                    _imageWidth= this.display.Image.Width;
-                    _imageHeight= this.display.Image.Height;
+                    _imageWidth = this.display.Image.Width;
+                    _imageHeight = this.display.Image.Height;
                     CogGraphicCollection graphic = new CogGraphicCollection();
                     CogCreateLineTool line1 = new CogCreateLineTool();
                     CogCreateLineTool line2 = new CogCreateLineTool();
@@ -101,7 +101,7 @@ namespace TeamAAS_VP.Views.Product
                 {
                     this.display.Image = VM.Image;
                     //如果图像的长宽发生变化,则重新绘制十字线
-                    if (_imageWidth!= this.display.Image.Width|| _imageHeight!= this.display.Image.Height)
+                    if (_imageWidth != this.display.Image.Width || _imageHeight != this.display.Image.Height)
                     {
                         _imageWidth = this.display.Image.Width;
                         _imageHeight = this.display.Image.Height;

+ 97 - 0
TeamAAS-VM/Views/Product/ProductParams.xaml

@@ -131,6 +131,10 @@
                         <RowDefinition Height="auto" />
                         <RowDefinition Height="auto" />
                         <RowDefinition Height="auto" />
+                        <RowDefinition Height="auto" />
+                        <RowDefinition Height="auto" />
+                        <RowDefinition Height="auto" />
+                        <RowDefinition Height="auto" />
                     </Grid.RowDefinitions>
                     <Grid.ColumnDefinitions>
                         <ColumnDefinition Width="auto" />
@@ -611,6 +615,99 @@
                             </DataTemplate>
                         </ComboBox.ItemTemplate>
                     </ComboBox>
+
+                    <!--独立向下相机1检测拍照流程ID-->
+                    <TextBlock Grid.Row="17"
+                               Grid.Column="0"
+                               Text="独立向下相机1检测拍照流程ID: " />
+                    <ComboBox Grid.Row="17"
+                              Grid.Column="1"
+                              ItemsSource="{Binding ProcedureModels}"
+                              SelectedItem="{Binding IndependentCamer1CheckProcedureId}"
+                              materialDesign:TextFieldAssist.HasClearButton="True"
+                              materialDesign:HintAssist.Hint="{lex:Loc 选择需要配置的流程}">
+                        <ComboBox.ItemTemplate>
+                            <DataTemplate>
+                                <StackPanel Orientation="Horizontal">
+                                    <materialDesign:PackIcon Kind="VideoOutline" />
+                                    <TextBlock Text="{Binding CameraName}"
+                                               Margin="6,0" />
+                                    <materialDesign:PackIcon Kind="ProgressWrench" />
+                                    <TextBlock Text="{Binding Name}"
+                                               Margin="6,0" />
+                                </StackPanel>
+                            </DataTemplate>
+                        </ComboBox.ItemTemplate>
+                    </ComboBox>
+                    <!--独立向下相机2检测拍照流程ID-->
+                    <TextBlock Grid.Row="18"
+                               Grid.Column="0"
+                               Text="独立向下相机2检测拍照流程ID: " />
+                    <ComboBox Grid.Row="18"
+                              Grid.Column="1"
+                              ItemsSource="{Binding ProcedureModels}"
+                              SelectedItem="{Binding IndependentCamer2CheckProcedureId}"
+                              materialDesign:TextFieldAssist.HasClearButton="True"
+                              materialDesign:HintAssist.Hint="{lex:Loc 选择需要配置的流程}">
+                        <ComboBox.ItemTemplate>
+                            <DataTemplate>
+                                <StackPanel Orientation="Horizontal">
+                                    <materialDesign:PackIcon Kind="VideoOutline" />
+                                    <TextBlock Text="{Binding CameraName}"
+                                               Margin="6,0" />
+                                    <materialDesign:PackIcon Kind="ProgressWrench" />
+                                    <TextBlock Text="{Binding Name}"
+                                               Margin="6,0" />
+                                </StackPanel>
+                            </DataTemplate>
+                        </ComboBox.ItemTemplate>
+                    </ComboBox>
+                    <!--独立向下相机3检测拍照流程ID-->
+                    <TextBlock Grid.Row="19"
+                               Grid.Column="0"
+                               Text="独立向下相机3检测拍照流程ID: " />
+                    <ComboBox Grid.Row="19"
+                              Grid.Column="1"
+                              ItemsSource="{Binding ProcedureModels}"
+                              SelectedItem="{Binding IndependentCamer3CheckProcedureId}"
+                              materialDesign:TextFieldAssist.HasClearButton="True"
+                              materialDesign:HintAssist.Hint="{lex:Loc 选择需要配置的流程}">
+                        <ComboBox.ItemTemplate>
+                            <DataTemplate>
+                                <StackPanel Orientation="Horizontal">
+                                    <materialDesign:PackIcon Kind="VideoOutline" />
+                                    <TextBlock Text="{Binding CameraName}"
+                                               Margin="6,0" />
+                                    <materialDesign:PackIcon Kind="ProgressWrench" />
+                                    <TextBlock Text="{Binding Name}"
+                                               Margin="6,0" />
+                                </StackPanel>
+                            </DataTemplate>
+                        </ComboBox.ItemTemplate>
+                    </ComboBox>
+                    <!--独立向下相机4检测拍照流程ID-->
+                    <TextBlock Grid.Row="20"
+                               Grid.Column="0"
+                               Text="独立向下相机4检测拍照流程ID: " />
+                    <ComboBox Grid.Row="20"
+                              Grid.Column="1"
+                              ItemsSource="{Binding ProcedureModels}"
+                              SelectedItem="{Binding IndependentCamer4CheckProcedureId}"
+                              materialDesign:TextFieldAssist.HasClearButton="True"
+                              materialDesign:HintAssist.Hint="{lex:Loc 选择需要配置的流程}">
+                        <ComboBox.ItemTemplate>
+                            <DataTemplate>
+                                <StackPanel Orientation="Horizontal">
+                                    <materialDesign:PackIcon Kind="VideoOutline" />
+                                    <TextBlock Text="{Binding CameraName}"
+                                               Margin="6,0" />
+                                    <materialDesign:PackIcon Kind="ProgressWrench" />
+                                    <TextBlock Text="{Binding Name}"
+                                               Margin="6,0" />
+                                </StackPanel>
+                            </DataTemplate>
+                        </ComboBox.ItemTemplate>
+                    </ComboBox>
                 </Grid>
             </Grid>
             

+ 164 - 0
TeamAAS-VM/Views/Statistics/AssemblyRecordQuery.xaml

@@ -0,0 +1,164 @@
+<UserControl x:Class="TeamAAS_VP.Views.Statistics.AssemblyRecordQuery"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:prism="http://prismlibrary.com/"
+             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.Statistics"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             HorizontalAlignment="Stretch"
+             VerticalAlignment="Stretch"
+             FontFamily="{DynamicResource DefaultFont}"
+             mc:Ignorable="d"
+             d:DataContext="{d:DesignInstance Type=vm:AssemblyRecordQueryViewModel}"
+             d:Height="600"
+             d:Width="1024"
+             d:Background="White">
+    <Grid Margin="8">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+            <RowDefinition Height="Auto" />
+        </Grid.RowDefinitions>
+        <!--标题-->
+        <TextBlock Text="组装记录查询"
+                   FontSize="20"
+                   FontWeight="Bold"
+                   Margin="0,0,0,12" />
+
+        <StackPanel Grid.Row="1"
+                    Orientation="Horizontal"
+                    VerticalAlignment="Center"
+                    Margin="0,0,0,8">
+            <TextBlock Text="产品:"
+                       VerticalAlignment="Center"
+                       Margin="0,0,8,0" />
+            <ComboBox MinWidth="100"
+                      ItemsSource="{Binding AllProduct}"
+                      DisplayMemberPath="Name"
+                      SelectedItem="{Binding SelectedProduct}" />
+
+            <TextBlock Text="产品编号:"
+                       VerticalAlignment="Center"
+                       Margin="16,0,8,0" />
+            <TextBox MinWidth="150"
+                     Text="{Binding ProductNumber, UpdateSourceTrigger=PropertyChanged}" />
+
+            <TextBlock Text="开始:"
+                       VerticalAlignment="Center"
+                       Margin="16,0,8,0" />
+            <DatePicker SelectedDate="{Binding StartDate}"
+                        MinWidth="50" />
+            <TextBlock Text="结束:"
+                       VerticalAlignment="Center"
+                       Margin="8,0,8,0" />
+            <DatePicker SelectedDate="{Binding EndDate}"
+                        MinWidth="50" />
+
+            <Button Content="查询"
+                    Command="{Binding SearchCommand}"
+                    Margin="12,0,0,0" />
+            <Button Content="导出当前页"
+                    Command="{Binding ExportCommand}"
+                    Margin="6,0,0,0" />
+        </StackPanel>
+
+        <DataGrid Grid.Row="2"
+                  ItemsSource="{Binding Results}"
+                  AutoGenerateColumns="False"
+                  CanUserAddRows="False"
+                  IsReadOnly="True">
+            <DataGrid.Columns>
+                <DataGridTextColumn Header="Id"
+                                    Binding="{Binding Id}"
+                                    Width="50" />
+                <DataGridTextColumn Header="时间"
+                                    Binding="{Binding Timestamp, StringFormat=yyyy-MM-dd HH:mm:ss}" />
+                <DataGridTextColumn Header="配方名称"
+                                    Binding="{Binding RecipeName}"/>
+                <DataGridTextColumn Header="产品序列号"
+                                    Binding="{Binding ProductSN}"/>
+                <DataGridTextColumn Header="零件序列号"
+                                    Binding="{Binding PartSN}" />
+                <DataGridTextColumn Header="是否成功"
+                                    Binding="{Binding Success}"/>
+                <DataGridTextColumn Header="组装压力"
+                                    Binding="{Binding AssemblyPressure}" />
+                <DataGridTextColumn Header="用时(秒)"
+                                    Binding="{Binding AssemblyDurationSeconds}"/>
+                <DataGridTextColumn Header="下相机坐标1"
+                                    Binding="{Binding DownCameraCoord1}"/>
+                <DataGridTextColumn Header="下相机坐标2"
+                                    Binding="{Binding DownCameraCoord2}"/>
+                <DataGridTextColumn Header="下相机坐标3"
+                                    Binding="{Binding DownCameraCoord3}"/>
+                <DataGridTextColumn Header="下相机坐标4"
+                                    Binding="{Binding DownCameraCoord4}"/>
+                <DataGridTextColumn Header="抓取运动坐标"
+                                    Binding="{Binding PickMoveCameraCoord}"/>
+                <DataGridTextColumn Header="放置运动坐标1"
+                                    Binding="{Binding PlaceMoveCameraCoord1}"/>
+                <DataGridTextColumn Header="放置运动坐标2"
+                                    Binding="{Binding PlaceMoveCameraCoord2}"/>
+                <DataGridTextColumn Header="放置运动坐标3"
+                                    Binding="{Binding PlaceMoveCameraCoord3}"/>
+                <DataGridTextColumn Header="放置运动坐标4"
+                                    Binding="{Binding PlaceMoveCameraCoord4}"/>
+                <DataGridTextColumn Header="实际放置坐标"
+                                    Binding="{Binding PlaceActualCoord}"/>
+                <DataGridTextColumn Header="设备名称"
+                                    Binding="{Binding DeviceName}" />
+                <DataGridTextColumn Header="设备Id"
+                                    Binding="{Binding DeviceId}"/>
+                <DataGridTextColumn Header="操作员"
+                                    Binding="{Binding OperatorName}"/>
+                <DataGridTextColumn Header="备注"
+                                    Binding="{Binding Remark}"/>
+            </DataGrid.Columns>
+        </DataGrid>
+        <Button Margin="16"
+                HorizontalAlignment="Left"
+                VerticalAlignment="Center"
+                Grid.RowSpan="3"
+                Command="{x:Static materialDesign:Transitioner.MovePreviousCommand}"
+                Style="{StaticResource MaterialDesignFloatingActionMiniButton}">
+            <materialDesign:PackIcon Kind="StepBackward" />
+        </Button>
+        <Button Margin="16"
+                HorizontalAlignment="Right"
+                VerticalAlignment="Center"
+                Grid.RowSpan="3"
+                Command="{x:Static materialDesign:Transitioner.MoveNextCommand}"
+                Style="{StaticResource MaterialDesignFloatingActionSecondaryButton}">
+            <materialDesign:PackIcon Kind="StepForward" />
+        </Button>
+        <StackPanel Grid.Row="3"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Center"
+                    Margin="0,8,0,0">
+            <Button Content="上一页"
+                    Command="{Binding PrevPageCommand}"
+                    Margin="4" />
+            <TextBlock VerticalAlignment="Center"
+                       Margin="4">第</TextBlock>
+            <TextBox Width="50"
+                     Text="{Binding PageIndex, UpdateSourceTrigger=PropertyChanged}"
+                     HorizontalContentAlignment="Center" />
+            <TextBlock VerticalAlignment="Center"
+                       Margin="4">页 / 共</TextBlock>
+            <TextBlock VerticalAlignment="Center"
+                       Text="{Binding TotalCount}"
+                       Margin="4" />
+            <Button Content="下一页"
+                    Command="{Binding NextPageCommand}"
+                    Margin="4" />
+        </StackPanel>
+    </Grid>
+</UserControl>

+ 15 - 0
TeamAAS-VM/Views/Statistics/AssemblyRecordQuery.xaml.cs

@@ -0,0 +1,15 @@
+using System.Windows.Controls;
+
+namespace TeamAAS_VP.Views.Statistics
+{
+    /// <summary>
+    /// Interaction logic for AssemblyRecordQuery
+    /// </summary>
+    public partial class AssemblyRecordQuery : UserControl
+    {
+        public AssemblyRecordQuery()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 7 - 5
TeamAAS-VM/Views/Statistics/LockResultRecoredQuery.xaml

@@ -33,7 +33,7 @@
             <TextBlock Text="产品:"
                        VerticalAlignment="Center"
                        Margin="0,0,8,0" />
-            <ComboBox Width="200"
+            <ComboBox MinWidth="100"
                       ItemsSource="{Binding AllProduct}"
                       DisplayMemberPath="Name"
                       SelectedItem="{Binding SelectedProduct}" />
@@ -41,23 +41,25 @@
             <TextBlock Text="产品编号:"
                        VerticalAlignment="Center"
                        Margin="16,0,8,0" />
-            <TextBox Width="150"
+            <TextBox MinWidth="150"
                      Text="{Binding ProductNumber, UpdateSourceTrigger=PropertyChanged}" />
 
             <TextBlock Text="螺丝编号:"
                        VerticalAlignment="Center"
                        Margin="16,0,8,0" />
-            <TextBox Width="80"
+            <TextBox MinWidth="80"
                      Text="{Binding ScrewNumber, UpdateSourceTrigger=PropertyChanged}" />
 
             <TextBlock Text="开始:"
                        VerticalAlignment="Center"
                        Margin="16,0,8,0" />
-            <DatePicker SelectedDate="{Binding StartDate}" />
+            <DatePicker SelectedDate="{Binding StartDate}"
+                        MinWidth="50" />
             <TextBlock Text="结束:"
                        VerticalAlignment="Center"
                        Margin="8,0,8,0" />
-            <DatePicker SelectedDate="{Binding EndDate}" />
+            <DatePicker SelectedDate="{Binding EndDate}"
+                        MinWidth="50" />
 
             <Button Content="查询"
                     Command="{Binding SearchCommand}"

+ 190 - 0
TeamAAS-VM/Views/Statistics/PhotoCaptureQuery.xaml

@@ -0,0 +1,190 @@
+<UserControl x:Class="TeamAAS_VP.Views.Statistics.PhotoCaptureQuery"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:prism="http://prismlibrary.com/"
+             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.Statistics"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             HorizontalAlignment="Stretch"
+             VerticalAlignment="Stretch"
+             FontFamily="{DynamicResource DefaultFont}"
+             mc:Ignorable="d"
+             d:DataContext="{d:DesignInstance Type=vm:PhotoCaptureQueryViewModel}"
+             d:Height="600"
+             d:Width="1024"
+             d:Background="White">
+    <b:Interaction.Triggers>
+        <b:EventTrigger EventName="Loaded">
+            <b:InvokeCommandAction Command="{Binding LoadedCommand}" />
+        </b:EventTrigger>
+    </b:Interaction.Triggers>
+    <Grid Margin="8">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+            <RowDefinition Height="Auto" />
+        </Grid.RowDefinitions>
+        <!--标题-->
+        <TextBlock Text="拍照记录查询"
+                   FontSize="20"
+                   FontWeight="Bold"
+                   Margin="0,0,0,12" />
+
+        <StackPanel Grid.Row="1"
+                    Orientation="Horizontal"
+                    Margin="0,0,0,8">
+            <TextBlock Text="产品"
+                       VerticalAlignment="Center"
+                       Margin="0,0,8,0" />
+            <ComboBox MinWidth="100"
+                      ItemsSource="{Binding AllProduct}"
+                      DisplayMemberPath="Name"
+                      SelectedItem="{Binding SelectedProduct}" />
+            <TextBlock Text="相机"
+                       VerticalAlignment="Center"
+                       Margin="16,0,8,0" />
+            <ComboBox MinWidth="100"
+                      ItemsSource="{Binding AllCamera}"
+                      DisplayMemberPath="CameraName"
+                      SelectedItem="{Binding SelectedCamera}" />
+            <TextBlock Text="产品SN"
+                       VerticalAlignment="Center"
+                       Margin="16,0,8,0" />
+            <TextBox Width="150"
+                     Text="{Binding ProductSN}" />
+            <TextBlock Text="开始"
+                       VerticalAlignment="Center"
+                       Margin="16,0,8,0" />
+            <DatePicker SelectedDate="{Binding StartDate}"
+                        MinWidth="100" />
+            <TextBlock Text="结束"
+                       VerticalAlignment="Center"
+                       Margin="8,0,8,0" />
+            <DatePicker SelectedDate="{Binding EndDate}"
+                        MinWidth="100" />
+            <Button Content="查询"
+                    Command="{Binding SearchCommand}"
+                    Margin="12,0,0,0" />
+            <Button Content="导出当前页"
+                    Command="{Binding ExportCommand}"
+                    Margin="6,0,0,0" />
+        </StackPanel>
+        <DataGrid Grid.Row="2"
+                  ItemsSource="{Binding Results}"
+                  AutoGenerateColumns="False"
+                  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="配方名"
+                                    Binding="{Binding RecipeName}" />
+                <DataGridTextColumn Header="流程名"
+                                    Binding="{Binding ProcessName}" />
+                <DataGridTextColumn Header="相机名"
+                                    Binding="{Binding CameraName}" />
+                <DataGridTextColumn Header="产品SN"
+                                    Binding="{Binding ProductSN}" />
+                <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"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Center"
+                    Margin="0,8,0,0">
+            <Button Content="上一页"
+                    Command="{Binding PrevPageCommand}"
+                    Margin="4" />
+            <TextBlock VerticalAlignment="Center"
+                       Margin="4">第</TextBlock>
+            <TextBox Width="50"
+                     Text="{Binding PageIndex, UpdateSourceTrigger=PropertyChanged}"
+                     HorizontalContentAlignment="Center" />
+            <TextBlock VerticalAlignment="Center"
+                       Margin="4">页 / 共</TextBlock>
+            <TextBlock VerticalAlignment="Center"
+                       Text="{Binding TotalCount}"
+                       Margin="4" />
+            <Button Content="下一页"
+                    Command="{Binding NextPageCommand}"
+                    Margin="4" />
+        </StackPanel>
+
+        <Button Margin="16"
+                HorizontalAlignment="Left"
+                VerticalAlignment="Center"
+                Grid.RowSpan="3"
+                Command="{x:Static materialDesign:Transitioner.MovePreviousCommand}"
+                Style="{StaticResource MaterialDesignFloatingActionMiniButton}">
+            <materialDesign:PackIcon Kind="StepBackward" />
+        </Button>
+        <Button Margin="16"
+                HorizontalAlignment="Right"
+                VerticalAlignment="Center"
+                Grid.RowSpan="3"
+                Command="{x:Static materialDesign:Transitioner.MoveNextCommand}"
+                Style="{StaticResource MaterialDesignFloatingActionSecondaryButton}">
+            <materialDesign:PackIcon Kind="StepForward" />
+        </Button>
+    </Grid>
+</UserControl>

+ 28 - 0
TeamAAS-VM/Views/Statistics/PhotoCaptureQuery.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.Statistics
+{
+    /// <summary>
+    /// PhotoCaptureQuery.xaml 的交互逻辑
+    /// </summary>
+    public partial class PhotoCaptureQuery : UserControl
+    {
+        public PhotoCaptureQuery()
+        {
+            InitializeComponent();
+        }
+    }
+}

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

@@ -0,0 +1,142 @@
+<UserControl x:Class="TeamAAS_VP.Views.Statistics.ProductionRecordQuery"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:prism="http://prismlibrary.com/"
+             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.Statistics"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             HorizontalAlignment="Stretch"
+             VerticalAlignment="Stretch"
+             FontFamily="{DynamicResource DefaultFont}"
+             mc:Ignorable="d"
+             d:DataContext="{d:DesignInstance Type=vm:ProductionRecordQueryViewModel}"
+             d:Height="600"
+             d:Width="1024"
+             d:Background="White">
+    <b:Interaction.Triggers>
+        <b:EventTrigger EventName="Loaded">
+            <b:InvokeCommandAction Command="{Binding LoadedCommand}" />
+        </b:EventTrigger>
+    </b:Interaction.Triggers>
+    <Grid Margin="8">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+            <RowDefinition Height="Auto" />
+        </Grid.RowDefinitions>
+        <!--标题-->
+        <TextBlock Text="生产记录查询"
+                   FontSize="20"
+                   FontWeight="Bold"
+                   Margin="0,0,0,12" />
+
+        <StackPanel Grid.Row="1"
+                    Orientation="Horizontal"
+                    Margin="0,0,0,8">
+            <TextBlock Text="产品"
+                       VerticalAlignment="Center"
+                       Margin="0,0,8,0" />
+            <ComboBox Width="200"
+                      ItemsSource="{Binding AllProduct}"
+                      DisplayMemberPath="Name"
+                      SelectedItem="{Binding SelectedProduct}" />
+            <TextBlock Text="类别"
+                       VerticalAlignment="Center"
+                       Margin="16,0,8,0" />
+            <ComboBox Width="150"
+                      ItemsSource="{Binding Categories}"
+                      SelectedItem="{Binding SelectedCategory}" />
+            <TextBlock Text="开始"
+                       VerticalAlignment="Center"
+                       Margin="16,0,8,0" />
+            <DatePicker SelectedDate="{Binding StartDate}"
+                        MinWidth="100" />
+            <TextBlock Text="结束"
+                       VerticalAlignment="Center"
+                       Margin="8,0,8,0" />
+            <DatePicker SelectedDate="{Binding EndDate}"
+                        MinWidth="100" />
+            <Button Content="查询"
+                    Command="{Binding SearchCommand}"
+                    Margin="12,0,0,0" />
+            <Button Content="导出当前页"
+                    Command="{Binding ExportCommand}"
+                    Margin="6,0,0,0" />
+        </StackPanel>
+        <DataGrid Grid.Row="2"
+                  ItemsSource="{Binding Results}"
+                  AutoGenerateColumns="False"
+                  CanUserAddRows="False"
+                  IsReadOnly="True">
+            <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="数量"
+                                    Binding="{Binding Quantity}" />
+                <DataGridTextColumn Header="操作员"
+                                    Binding="{Binding UserName}" />
+                <DataGridTextColumn Header="备注"
+                                    Binding="{Binding Remark}" />
+            </DataGrid.Columns>
+        </DataGrid>
+        <StackPanel Grid.Row="3"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Center"
+                    Margin="0,8,0,0">
+            <Button Content="上一页"
+                    Command="{Binding PrevPageCommand}"
+                    Margin="4" />
+            <TextBlock VerticalAlignment="Center"
+                       Margin="4">第</TextBlock>
+            <TextBox Width="50"
+                     Text="{Binding PageIndex, UpdateSourceTrigger=PropertyChanged}"
+                     HorizontalContentAlignment="Center" />
+            <TextBlock VerticalAlignment="Center"
+                       Margin="4">页 / 共</TextBlock>
+            <TextBlock VerticalAlignment="Center"
+                       Text="{Binding TotalCount}"
+                       Margin="4" />
+            <Button Content="下一页"
+                    Command="{Binding NextPageCommand}"
+                    Margin="4" />
+        </StackPanel>
+
+        <Button Margin="16"
+                HorizontalAlignment="Left"
+                VerticalAlignment="Center"
+                Grid.RowSpan="3"
+                Command="{x:Static materialDesign:Transitioner.MovePreviousCommand}"
+                Style="{StaticResource MaterialDesignFloatingActionMiniButton}">
+            <materialDesign:PackIcon Kind="StepBackward" />
+        </Button>
+        <Button Margin="16"
+                HorizontalAlignment="Right"
+                VerticalAlignment="Center"
+                Grid.RowSpan="3"
+                Command="{x:Static materialDesign:Transitioner.MoveNextCommand}"
+                Style="{StaticResource MaterialDesignFloatingActionSecondaryButton}">
+            <materialDesign:PackIcon Kind="StepForward" />
+        </Button>
+    </Grid>
+</UserControl>

+ 28 - 0
TeamAAS-VM/Views/Statistics/ProductionRecordQuery.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.Statistics
+{
+    /// <summary>
+    /// ProductionRecordQuery.xaml 的交互逻辑
+    /// </summary>
+    public partial class ProductionRecordQuery : UserControl
+    {
+        public ProductionRecordQuery()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 6 - 2
TeamAAS-VM/Views/StatisticsView.xaml

@@ -26,8 +26,12 @@
                 <local:ProductionStatement />
             </materialDesign:TransitionerSlide>
 
-            <local:LockResultRecoredQuery />
-            
+            <local:AssemblyRecordQuery />
+
+            <local:PhotoCaptureQuery />
+
+            <local:ProductionRecordQuery />
+
             <local:StatisticalQuery />
 
             <local:AlarmQuery />