wanghan vor 10 Monaten
Ursprung
Commit
79cfc9712b
68 geänderte Dateien mit 4866 neuen und 764 gelöschten Zeilen
  1. 30 5
      TeamAAS-VM/App.config
  2. 33 5
      TeamAAS-VM/App.xaml.cs
  3. 0 5
      TeamAAS-VM/Core/FilePath.cs
  4. 4 0
      TeamAAS-VM/Core/Lights/KCSLightController.cs
  5. 4 0
      TeamAAS-VM/Core/Lights/LightModel.cs
  6. 5 0
      TeamAAS-VM/Core/Lights/SerialPortProtocol.cs
  7. 394 41
      TeamAAS-VM/Core/Management.cs
  8. 10 4
      TeamAAS-VM/Core/ScrewDriver/XYD_ScrewDriver.cs
  9. 18 1
      TeamAAS-VM/Data/DatabaseInitializer.cs
  10. 273 3
      TeamAAS-VM/Data/SystemDatabaseService.cs
  11. 5 0
      TeamAAS-VM/Enums/ProcedureSaveImagePathModel.cs
  12. 25 5
      TeamAAS-VM/Interfaces/IConfigService.cs
  13. 69 7
      TeamAAS-VM/Interfaces/IMesService.cs
  14. 2 2
      TeamAAS-VM/Interfaces/IRemoteCommandService.cs
  15. 105 2
      TeamAAS-VM/Interfaces/ISystemDatabaseService.cs
  16. 8 0
      TeamAAS-VM/LogHelper.cs
  17. 34 0
      TeamAAS-VM/Models/HeadChangeRecord.cs
  18. 123 60
      TeamAAS-VM/Models/Lights/LightControllerConfig.cs
  19. 87 27
      TeamAAS-VM/Models/LockResult.cs
  20. 34 0
      TeamAAS-VM/Models/NozzleChangeRecord.cs
  21. 0 20
      TeamAAS-VM/Models/NumberStatistics.cs
  22. 157 7
      TeamAAS-VM/Models/PLC/PlcPoint.cs
  23. 79 0
      TeamAAS-VM/Models/PhotoCaptureRecord.cs
  24. 10 0
      TeamAAS-VM/Models/ScrewFeederBatchRecord.cs
  25. 20 0
      TeamAAS-VM/Models/SystemConfiguration.cs
  26. 9 0
      TeamAAS-VM/Resources/Languages/Lang.Designer.cs
  27. 3 0
      TeamAAS-VM/Resources/Languages/Lang.resx
  28. 170 32
      TeamAAS-VM/Services/ConfigService.cs
  29. 8 0
      TeamAAS-VM/Services/LightManagerService.cs
  30. 144 73
      TeamAAS-VM/Services/MesService.cs
  31. 84 8
      TeamAAS-VM/Services/RemoteCommandService.cs
  32. 39 3
      TeamAAS-VM/TeamAAS-VP.csproj
  33. 199 0
      TeamAAS-VM/ViewModels/Home/AddScrewViewModel.cs
  34. 101 0
      TeamAAS-VM/ViewModels/Home/ChangeHeaderViewModel.cs
  35. 100 0
      TeamAAS-VM/ViewModels/Home/ChangeNozzleViewModel.cs
  36. 0 99
      TeamAAS-VM/ViewModels/Home/SetAlarmValueViewModel.cs
  37. 94 42
      TeamAAS-VM/ViewModels/HomeViewModel.cs
  38. 12 53
      TeamAAS-VM/ViewModels/MainWindowViewModel.cs
  39. 124 0
      TeamAAS-VM/ViewModels/Product/PlcPointOffserParamsViewModel.cs
  40. 109 19
      TeamAAS-VM/ViewModels/Product/PlcPointParamsViewModel.cs
  41. 3 0
      TeamAAS-VM/ViewModels/Product/ProcedureParamsViewModel.cs
  42. 82 18
      TeamAAS-VM/ViewModels/Product/VisionDynamicAccuracyAnalyzerViewModel.cs
  43. 28 2
      TeamAAS-VM/ViewModels/Product/VisionStaticAccuracyAnalyzerViewModel.cs
  44. 2 2
      TeamAAS-VM/ViewModels/Setting/AddLightControllerViewModel.cs
  45. 124 37
      TeamAAS-VM/ViewModels/SettingViewModel.cs
  46. 16 11
      TeamAAS-VM/ViewModels/Statistics/LockResultRecoredQueryViewModel.cs
  47. 287 0
      TeamAAS-VM/ViewModels/User/CardLoginWindowViewModel.cs
  48. 32 14
      TeamAAS-VM/ViewModels/User/LoginViewModel.cs
  49. 145 0
      TeamAAS-VM/Views/Home/AddScrew.xaml
  50. 15 0
      TeamAAS-VM/Views/Home/AddScrew.xaml.cs
  51. 123 0
      TeamAAS-VM/Views/Home/ChangeHeader.xaml
  52. 15 0
      TeamAAS-VM/Views/Home/ChangeHeader.xaml.cs
  53. 123 0
      TeamAAS-VM/Views/Home/ChangeNozzle.xaml
  54. 15 0
      TeamAAS-VM/Views/Home/ChangeNozzle.xaml.cs
  55. 0 94
      TeamAAS-VM/Views/Home/SetAlarmValue.xaml
  56. 0 28
      TeamAAS-VM/Views/Home/SetAlarmValue.xaml.cs
  57. 65 0
      TeamAAS-VM/Views/Home/ShowVisionRender.xaml.cs
  58. 14 7
      TeamAAS-VM/Views/HomeView.xaml
  59. 319 0
      TeamAAS-VM/Views/Product/PlcPointOffserParams.xaml
  60. 15 0
      TeamAAS-VM/Views/Product/PlcPointOffserParams.xaml.cs
  61. 60 7
      TeamAAS-VM/Views/Product/PlcPointParams.xaml
  62. 42 0
      TeamAAS-VM/Views/Product/PlcPointParams.xaml.cs
  63. 40 5
      TeamAAS-VM/Views/Product/VisionDynamicAccuracyAnalyzer.xaml
  64. 15 1
      TeamAAS-VM/Views/Product/VisionStaticAccuracyAnalyzer.xaml
  65. 138 15
      TeamAAS-VM/Views/SettingView.xaml
  66. 373 0
      TeamAAS-VM/Views/User/CardLoginWindow.xaml
  67. 34 0
      TeamAAS-VM/Views/User/CardLoginWindow.xaml.cs
  68. 16 0
      TeamAAS-VM/Views/User/LoginView.xaml

+ 30 - 5
TeamAAS-VM/App.config

@@ -75,6 +75,11 @@
       <level value="ALL" />
       <appender-ref ref="CTAppender" />
     </logger>
+	  <!--mes日志类-->
+	  <logger name="logMes">
+		  <level value="ALL" />
+		  <appender-ref ref="MesAppender" />
+	  </logger>
     <!--定义输出到文件中-->
     <!--错误日志附加介质-->
     <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
@@ -122,7 +127,7 @@
     </appender>
     <!--信息日志附加介质-->
     <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
-      <param name="File" value="..\\Log\\LogInfo\\" />
+      <param name="File" value="E:\\Data\\Log\\LogInfo\\" />
       <param name="AppendToFile" value="true" />
       <param name="MaxFileSize" value="10240" />
       <param name="MaxSizeRollBackups" value="100" />
@@ -137,7 +142,7 @@
     </appender>
     <!--调试日志附加介质-->
     <appender name="DebugAppender" type="log4net.Appender.RollingFileAppender">
-      <param name="File" value="..\\Log\\LogDebug\\" />
+      <param name="File" value="E:\\Data\\Log\\LogDebug\\" />
       <param name="AppendToFile" value="true" />
       <param name="MaxFileSize" value="10240" />
       <param name="MaxSizeRollBackups" value="100" />
@@ -152,7 +157,7 @@
     </appender>
     <!--警告日志附加介质-->
     <appender name="WarnAppender" type="log4net.Appender.RollingFileAppender">
-      <param name="File" value="..\\Log\\LogWarn\\" />
+      <param name="File" value="E:\\Data\\Log\\LogWarn\\" />
       <param name="AppendToFile" value="true" />
       <param name="MaxFileSize" value="10240" />
       <param name="MaxSizeRollBackups" value="100" />
@@ -168,7 +173,7 @@
     <!--动态日志附加介质-->
     <appender name="DynamicAppender" type="log4net.Appender.RollingFileAppender">
       <!--输出日志文件的路径-->
-      <param name="File" value="..\\Log\\LogOther\\" />
+      <param name="File" value="E:\\Data\\Log\\LogOther\\" />
       <!--输出日志时自动向后追加-->
       <param name="AppendToFile" value="true" />
       <!--防止多线程时不能写Log,官方说线程非安全,但实际使用时,本地测试正常,部署后有不能写日志的情况-->
@@ -187,7 +192,7 @@
     </appender>
     <!--CT日志附加介质-->
     <appender name="CTAppender" type="log4net.Appender.RollingFileAppender">
-      <param name="File" value="..\\Log\\LogCT\\" />
+      <param name="File" value="E:\\Data\\Log\\LogCT\\" />
       <param name="AppendToFile" value="true" />
       <param name="MaxFileSize" value="10240" />
       <param name="MaxSizeRollBackups" value="100" />
@@ -200,6 +205,26 @@
         <param name="ConversionPattern" value="[日志时间:%d] [%t] [%-5p]:%m%n" />
       </layout>
     </appender>
+	  <!--mes日志-->
+	  <appender name="MesAppender" type="log4net.Appender.RollingFileAppender">
+		  <!--输出日志文件的路径-->
+		  <param name="File" value="E:\\Data\\Log\\LogMes\\" />
+		  <!--输出日志时自动向后追加-->
+		  <param name="AppendToFile" value="true" />
+		  <!--防止多线程时不能写Log,官方说线程非安全,但实际使用时,本地测试正常,部署后有不能写日志的情况-->
+		  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
+		  <param name="MaxFileSize" value="10240" />
+		  <param name="MaxSizeRollBackups" value="100" />
+		  <param name="StaticLogFileName" value="false" />
+		  <param name="DatePattern" value="yyyy-MM\\yyyy-MM-dd&quot;.txt&quot;" />
+		  <param name="RollingStyle" value="Date" />
+		  <!--输出格式-->
+		  <!--样例:[日志时间:2023-11-08 10:56:12,247] [1] [INFO ]:系统启动!-->
+		  <!--信息日志布局-->
+		  <layout type="log4net.Layout.PatternLayout">
+			  <param name="ConversionPattern" value="[日志时间:%d] [%t] [%-5p]:%m%n" />
+		  </layout>
+	  </appender>
   </log4net>
   <system.web>
     <membership defaultProvider="ClientAuthenticationMembershipProvider">

+ 33 - 5
TeamAAS-VM/App.xaml.cs

@@ -33,6 +33,7 @@ using TeamAAS_VP.ViewModels.Calibration;
 using TeamAAS_VP.ViewModels.DebugMod;
 using TeamAAS_VP.ViewModels.Home;
 using TeamAAS_VP.ViewModels.Product;
+using TeamAAS_VP.ViewModels.User;
 using TeamAAS_VP.Views;
 using TeamAAS_VP.Views.Calibration;
 using TeamAAS_VP.Views.DebugMod;
@@ -54,7 +55,29 @@ namespace TeamAAS_VP
         protected override Window CreateShell()
         {
             Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
-            return base.Container.Resolve<MainWindowView>();
+            var mainWindow = this.Container.Resolve<MainWindowView>();
+            var _configService = this.Container.Resolve<IConfigService>();
+            var _databaseInitializer = this.Container.Resolve<IDatabaseInitializer>();
+            // 1. 读取配置参数
+            _configService.LoadAll();
+            try
+            {
+                _databaseInitializer.InitializeDatabase();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Database initialization failed during application startup", ex);
+            }
+            // 设置语言
+            var currentlanguage = _configService.GetSystemConfiguration().CurrentLanguage;
+            _configService.SetCurrentLanguage(currentlanguage);
+            var cardLogin = this.Container.Resolve<CardLoginWindow>();
+            var result = cardLogin.ShowDialog();
+            if (result is bool st1 && !st1)
+            {
+                this.Shutdown();
+            }
+            return mainWindow;
         }
 
         protected override void RegisterTypes(IContainerRegistry containerRegistry)
@@ -94,7 +117,7 @@ namespace TeamAAS_VP
             containerRegistry.RegisterForNavigation<ProductParams>();
             containerRegistry.RegisterForNavigation<ProcedureParams>();
             containerRegistry.RegisterForNavigation<AfagFeederParams>();
-            
+
             //校准
             containerRegistry.RegisterForNavigation<CalibrationAuto>();
             containerRegistry.RegisterForNavigation<CalibrationBasics>();
@@ -119,7 +142,9 @@ namespace TeamAAS_VP
             containerRegistry.RegisterSingleton<IRemoteCommandService, RemoteCommandService>();
             containerRegistry.RegisterSingleton<ILightManagerService, LightManagerService>();
             containerRegistry.RegisterSingleton<ICameraCalibrationService, CameraCalibrationService>();
+            containerRegistry.RegisterSingleton<IMesService, MesService>();
             containerRegistry.RegisterSingleton<Management>();
+            containerRegistry.RegisterSingleton<CardLoginWindowViewModel>();
             containerRegistry.RegisterSingleton<TorqueService>();
 
             // Register system database service and initializer
@@ -183,9 +208,12 @@ namespace TeamAAS_VP
             containerRegistry.RegisterDialog<AutoCorrectLockPoint>();
             containerRegistry.RegisterDialog<ImageDisplay>();
             containerRegistry.RegisterDialog<TorqueCheck>();
-            containerRegistry.RegisterDialog<SetAlarmValue>();
             containerRegistry.RegisterDialog<VisionStaticAccuracyAnalyzer>();
             containerRegistry.RegisterDialog<VisionDynamicAccuracyAnalyzer>();
+            containerRegistry.RegisterDialog<AddScrew>();
+            containerRegistry.RegisterDialog<ChangeHeader>();
+            containerRegistry.RegisterDialog<ChangeNozzle>();
+            containerRegistry.RegisterDialog<PlcPointOffserParams>();
             //**************************************************************************************
 
             // 注册 SQLSugar 客户端(单例模式)
@@ -272,7 +300,7 @@ namespace TeamAAS_VP
             }
             else
             {
-                MessageBox.Show(Lang.程序已经在运行, "AAS",MessageBoxButton.OK,MessageBoxImage.Asterisk);
+                MessageBox.Show(Lang.程序已经在运行, "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                 this.Shutdown();
             }
         }
@@ -288,7 +316,7 @@ namespace TeamAAS_VP
             //可以记录日志并转向错误bug窗口友好提示用户
             e.Handled = true;
             LogHelper.WriteLogFatal("Application has crashed", e.Exception);
-            MessageBox.Show("Error:" + e.Exception.Message + " " + e.Exception.StackTrace,"AAS",MessageBoxButton.OK,MessageBoxImage.Asterisk);
+            MessageBox.Show("Error:" + e.Exception.Message + " " + e.Exception.StackTrace, "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
         }
 
         private static void UnhandledExceptionOccured(object sender, UnhandledExceptionEventArgs args)

+ 0 - 5
TeamAAS-VM/Core/FilePath.cs

@@ -67,11 +67,6 @@ namespace TeamAAS_VP.Core
         /// </summary>
         public static string TorqueCheckPath = "..//Config//TorqueCheckParam.cfg";
 
-        /// <summary>
-        /// 数量参数
-        /// </summary>
-        public static string NumberStatisticsPath = "..//Config//NumberStatisticsParam.cfg";
-
         /// <summary>
         /// 扭力测量仪路径
         /// </summary>

+ 4 - 0
TeamAAS-VM/Core/Lights/KCSLightController.cs

@@ -161,6 +161,10 @@ namespace TeamAAS_VP.Core.Lights
         {
             // 通道字母从 'A' 开始递增
             string command = $"S{(char)('A' + channelIndex)}#";
+            if (_config.LightModel == LightModel.KCS_KDC3_24V300W_8T)
+            {
+                command = $"SR{(char)('A' + channelIndex)}#";
+            }
             var response = await SendCommandAsync(command);
 
             // 响应示例(假设):?XDDD(总长度 5),亮度在索引 2 开始的 3 个字符

+ 4 - 0
TeamAAS-VM/Core/Lights/LightModel.cs

@@ -15,5 +15,9 @@ namespace TeamAAS_VP.Core.Lights
         /// 顺尚信KDC-12V60W-4T
         /// </summary>
         KCS_KDC_12V60W_4T,
+        /// <summary>
+        /// 顺尚信KDC3-24V300W-8T
+        /// </summary>
+        KCS_KDC3_24V300W_8T,
     }
 }

+ 5 - 0
TeamAAS-VM/Core/Lights/SerialPortProtocol.cs

@@ -132,7 +132,12 @@ namespace TeamAAS_VP.Core.Lights
                     {
                         CacheTimeout = TimeSpan.FromMilliseconds(100)
                     });
+                _client.Received = async (c, e) =>
+                {
 
+                    string Data = e.ByteBlock.Span.ToString(Encoding); //接收到数据
+                    DataReceived?.Invoke(this, Data.Trim());
+                };
                 _client.Setup(config);
 
                 var result = await _client.TryConnectAsync();

+ 394 - 41
TeamAAS-VM/Core/Management.cs

@@ -2,14 +2,17 @@
 using Cognex.VisionPro;
 using Cognex.VisionPro.ToolBlock;
 using CSScripting;
+using CSScriptLib;
 using MathNet.Numerics.Distributions;
 using MathNet.Numerics.LinearAlgebra;
 using MathNet.Numerics.RootFinding;
+using Newtonsoft.Json;
 using NPOI.SS.Formula.Functions;
 using NPOI.Util;
 using Opc.Ua;
 using OpenCvSharp;
 using OpenCvSharp.Flann;
+using Org.BouncyCastle.Crypto;
 using Prism.Events;
 using Prism.Ioc;
 using Prism.Mvvm;
@@ -20,6 +23,8 @@ using System.Collections;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.ComponentModel;
+using System.Data;
+using System.Diagnostics;
 using System.Drawing;
 using System.IO;
 using System.Linq;
@@ -52,6 +57,7 @@ using TeamAAS_VP.Models.Product;
 using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.Services;
 using TeamAAS_VP.ViewModels.Home;
+using TeamAAS_VP.Views.Product;
 using TouchSocket.Core;
 using TouchSocket.SerialPorts;
 using TouchSocket.Sockets;
@@ -78,10 +84,38 @@ namespace TeamAAS_VP.Core
         ICalibrationService _calibrationService;
         IRemoteCommandService _remoteCommandService;
         ISystemDatabaseService _systemDatabaseService;
+        IMesService _mesService;
 
         Timer yieldtimer;
         private DateTime StartTime = DateTime.Now;
         SerialPortClient client;
+        // Pressure collection
+        /// <summary>
+        /// 压力采集信号控制CTS
+        /// </summary>
+        private CancellationTokenSource _pressureCts;
+        /// <summary>
+        /// 压力采集超时CTS
+        /// </summary>
+        private CancellationTokenSource _pressureTimeoutCts;
+        /// <summary>
+        /// 压力采集CTS
+        /// </summary>
+        private CancellationTokenSource _pressureLinkedCts;
+        /// <summary>
+        /// 压力数据集合
+        /// </summary>
+        private List<(DateTime Timestamp, float Value)> _pressureSamples = new List<(DateTime, float)>();
+        /// <summary>
+        /// 采样间隔毫秒
+        /// </summary>
+        private int _pressureSampleIntervalMs = 50; //采样间隔毫秒
+        /// <summary>
+        /// 超时自动停止秒数
+        /// </summary>
+        private int _pressureMaxDurationSeconds = 30; //超时自动停止秒数
+        Stopwatch swCT = new Stopwatch();
+        List<LockResult> lockResultsAll = new List<LockResult>();//一个产品的总结果
         #endregion
 
         #region 属性
@@ -200,6 +234,16 @@ namespace TeamAAS_VP.Core
             get { return _NumStatistics; }
             set { SetProperty(ref _NumStatistics, value); }
         }
+
+        private double _CTtime;
+        /// <summary>
+        /// ct
+        /// </summary>
+        public double CTtime
+        {
+            get { return _CTtime; }
+            set { SetProperty(ref _CTtime, value); }
+        }
         #endregion
 
         #region 命令
@@ -212,7 +256,8 @@ namespace TeamAAS_VP.Core
 
         public Management(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IConfigService configService,
             IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService, IProductService productService,
-            ICalibrationService calibrationService, IRemoteCommandService remoteCommandService, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService)
+            ICalibrationService calibrationService, IRemoteCommandService remoteCommandService, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService,
+            IMesService mesService)
         {
             _regionManager = regionManager;
             _eventAggregator = ea;
@@ -229,29 +274,37 @@ namespace TeamAAS_VP.Core
             _remoteCommandService = remoteCommandService;
             _systemDatabaseService = systemDatabaseService;
             _lightManagerService = lightManagerService;
+            _mesService = mesService;
         }
 
         #region 读取配置参数
-        public void ReadConfig()
+        public async Task ReadConfig()
         {
-            ReadNumber();
+            await ReadNumber();
         }
         /// <summary>
         /// 读取数量配置
         /// </summary>
-        public void ReadNumber()
+        public async Task ReadNumber()
         {
             try
             {
-                if (File.Exists(FilePath.NumberStatisticsPath))
+                NumStatistics = new NumberStatistics();
+                var latestHeadChangeRecord = await _systemDatabaseService.GetLatestHeadChangeRecordAsync();
+                if (latestHeadChangeRecord != null)
                 {
-                    NumStatistics = FileHelper.ReadJsonFile<NumberStatistics>(FilePath.NumberStatisticsPath);
+                    NumStatistics.HeaderNum = latestHeadChangeRecord.CurrentLockCount;
                 }
-                else
+
+                var latestNozzleChangeRecord = await _systemDatabaseService.GetLatestNozzleChangeRecordAsync();
+                if (latestNozzleChangeRecord != null)
                 {
-                    NumStatistics = new NumberStatistics();
-                    FileHelper.WriteJsonFile(NumStatistics, FilePath.NumberStatisticsPath);
+                    NumStatistics.NozzleNum = latestNozzleChangeRecord.CurrentLockCount;
                 }
+
+                NumStatistics.Feeder1Num = _configService.GetRemainingCountByFeederNumber(1);
+                NumStatistics.Feeder2Num = _configService.GetRemainingCountByFeederNumber(2);
+
             }
             catch (Exception ex)
             {
@@ -617,7 +670,7 @@ namespace TeamAAS_VP.Core
             }
             catch (Exception ex)
             {
-                SendTaskMessage(string.Format(Lang.电批连接失败0,ex.Message), MessageLevel.Alarm);
+                SendTaskMessage(string.Format(Lang.电批连接失败0, ex.Message), MessageLevel.Alarm);
                 LogHelper.WriteLogError(Lang.连接电批时出错, ex);
             }
         }
@@ -665,7 +718,7 @@ namespace TeamAAS_VP.Core
                 catch (Exception ex)
                 {
                     LogHelper.WriteLogError("初始化扭力测量仪时出错!", ex);
-                    SendTaskMessage("初始化扭力测量仪时出错!"+ex.Message, MessageLevel.Error);
+                    SendTaskMessage("初始化扭力测量仪时出错!" + ex.Message, MessageLevel.Error);
                 }
             }
             else
@@ -1218,7 +1271,7 @@ namespace TeamAAS_VP.Core
                 }
 
                 //获取产品编码
-                _productService.CurrentProductCode = plc.ReadNode<string>(addressConfig.In_Code.Address);
+                _productService.CurrentProductCode = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, 0));
                 //如果产品编码为空,则以当前的时间戳作为编码
                 if (string.IsNullOrEmpty(_productService.CurrentProductCode))
                 {
@@ -1268,7 +1321,7 @@ namespace TeamAAS_VP.Core
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token);
+                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token, null);
                             if (visionResult.IsSucceed)
                             {
                                 //披头偏差
@@ -1311,7 +1364,7 @@ namespace TeamAAS_VP.Core
                             SendTaskMessage(Lang.触发下相机拍照, MessageLevel.Debug);
                             //相机的编号
                             Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_DowmCameraNum.Address);
-                            SendTaskMessage(string.Format(Lang.编号0,cameraIndex), MessageLevel.Info);
+                            SendTaskMessage(string.Format(Lang.编号0, cameraIndex), MessageLevel.Info);
 
                             // 获取流程
                             var process = _productService.GetCurrentProductProcedureModelById(currentProduct.FixedUpCamera1ProcedureId);
@@ -1335,7 +1388,7 @@ namespace TeamAAS_VP.Core
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token);
+                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token, null);
                             if (visionResult.IsSucceed)
                             {
                                 //披头偏差
@@ -1410,11 +1463,21 @@ namespace TeamAAS_VP.Core
                             Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_UpCameraPutNum.Address);
                             SendTaskMessage(string.Format(Lang.编号0, cameraIndex), MessageLevel.Info);
 
+                            //视觉流程ID
+                            Guid procedureId = currentProduct.MoveDownCameraLockPhotoProcedureId;
+
+                            //获取锁付拍照的点位
+                            var pos = currentProduct.ScrewCameraPoints.FirstOrDefault(p => p.Number == cameraIndex);
+                            if (pos != null)
+                            {
+                                procedureId = pos.VisionProcessID;
+                            }
+
                             // 获取流程
-                            var process = _productService.GetCurrentProductProcedureModelById(currentProduct.MoveDownCameraLockPhotoProcedureId);
+                            var process = _productService.GetCurrentProductProcedureModelById(procedureId);
                             if (process == null)
                             {
-                                SendTaskMessage(string.Format(Lang.未找到上相机锁附组装拍照对应的视觉流程流程ID0,currentProduct.MoveDownCameraLockPhotoProcedureId), MessageLevel.Alarm);
+                                SendTaskMessage(string.Format(Lang.未找到上相机锁附组装拍照对应的视觉流程流程ID0, procedureId), MessageLevel.Alarm);
                                 await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)2);
                                 return;
                             }
@@ -1432,7 +1495,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, null);
                             if (visionResult.IsSucceed)
                             {
                                 UpCameraPutResults[cameraIndex] = new PointF((float)visionResult.X, (float)visionResult.Y);
@@ -1588,7 +1651,9 @@ namespace TeamAAS_VP.Core
                             SendTaskMessage(Lang.收到开始锁付信号, MessageLevel.Debug);
                             //位置编号
                             Int16 positionIndex = plc.ReadNode<Int16>(addressConfig.In_ProductNum.Address);
-                            SendTaskMessage(string.Format(Lang.编号0,positionIndex), MessageLevel.Info);
+                            SendTaskMessage(string.Format(Lang.编号0, positionIndex), MessageLevel.Info);
+                            // 开始采集压力值
+                            StartPressureCollection(currentProduct.Name, _productService.CurrentProductCode, positionIndex);
                         }
                         else
                         {
@@ -1615,7 +1680,7 @@ namespace TeamAAS_VP.Core
                             SendTaskMessage(Lang.收到停止锁付信号, MessageLevel.Debug);
                             //位置编号
                             Int16 positionIndex = plc.ReadNode<Int16>(addressConfig.In_ProductNum.Address);
-                            SendTaskMessage(string.Format(Lang.编号0,positionIndex), MessageLevel.Info);
+                            SendTaskMessage(string.Format(Lang.编号0, positionIndex), MessageLevel.Info);
                             //获取当前锁付点
                             var screwPoint = currentProduct.ScrewPoints.FirstOrDefault(p => p.Number == positionIndex);
                             //获取当前的机器人点位
@@ -1623,7 +1688,17 @@ namespace TeamAAS_VP.Core
                             var currentPosition = robot.GetRobotPos();
                             //读取压力值
                             float pressure = plc.ReadNode<float>(addressConfig.In_PressureValue.Address);
-
+                            //当前用户名
+                            string currentUserName = _systemDatabaseService.GetCurrentUser().UserName;
+
+                            //吸嘴最后一次的记录
+                            var nozzleRecord = await _systemDatabaseService.GetLatestNozzleChangeRecordAsync();
+                            //最后一次的吸嘴编号
+                            string nozzleNumber = nozzleRecord != null ? nozzleRecord.NozzleBatchNumber : "N/A";
+                            //披头最后一次的记录
+                            var headRecord = await _systemDatabaseService.GetLatestHeadChangeRecordAsync();
+                            //最后一次的披头编号
+                            string headNumber = headRecord != null ? headRecord.HeadBatchNumber : "N/A";
 
                             await Task.Delay(60);
                             //获取电批结果
@@ -1640,26 +1715,54 @@ namespace TeamAAS_VP.Core
                             lockResult.ScrewdriverProgramNumber = ScrewDriver.ProgramNumber;
                             lockResult.ResultDetails = ScrewDriver.ErrorInfo;
                             lockResult.Pressure = pressure;
-                            lockResult.TargetTorque = ScrewDriver.TargetTorque;
+                            lockResult.TargetTorqueUpperLimit = ScrewDriver.TargetTorqueUpperLimit;
+                            lockResult.TargetTorqueLowerLimit = ScrewDriver.TargetTorqueLowerLimit;
                             lockResult.TargetTurnsUpperLimit = ScrewDriver.TargetTurnsUpperLimit;
                             lockResult.TargetTurnsLowerLimit = ScrewDriver.TargetTurnsLowerLimit;
                             lockResult.TargetLockSpeed = ScrewDriver.TargetLockSpeed;
-                            lockResult.StartPositionX = currentPosition.X;
-                            lockResult.StartPositionY = currentPosition.Y;
+                            lockResult.PositionX = currentPosition.X;
+                            lockResult.PositionY = currentPosition.Y;
                             lockResult.StartPositionZ = screwPoint.Z_Position_Start;
                             lockResult.EndPositionZ = currentPosition.Z;
                             lockResult.LockDescentSpeed = screwPoint.Z_Velocity_Stop;
                             lockResult.FeederNumber = screwPoint != null ? screwPoint.Feeder : 0;
-                            lockResult.NozzleNumber = "";
-                            lockResult.OperatorName = _systemDatabaseService.GetCurrentUser().UserName;
+                            lockResult.NozzleNumber = nozzleNumber;
+                            lockResult.HeadNumber = headNumber;
+                            lockResult.OperatorName = currentUserName;
                             lockResult.ProductImagePath = "";
                             lockResult.WaveDatas = ScrewDriver.WaveDatas;
+                            //获取系统参数
+                            var systemConfig = _configService.GetSystemConfiguration();
+                            //判断是否保存锁付曲线
+                            if (systemConfig.IsSaveScrewCurve)
+                            {
+                                //锁付曲线的保存路径为:systemConfig.ScrewCurvePath//年月//年月日//配方名//产品SN//产品SN+螺丝索引
+                                string datePath = DateTime.Now.ToString("yyyy-MM") + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
+                                string dirPath = System.IO.Path.Combine(systemConfig.ScrewCurvePath, datePath, currentProduct.Name, lockResult.ProductNumber);
+                                if (!Directory.Exists(dirPath))
+                                {
+                                    Directory.CreateDirectory(dirPath);
+                                }
+                                string curveFileName = $"{lockResult.ProductNumber}-{lockResult.Number}.png";
+                                //锁付CSV保存路径
+                                string curveFileFullPath = System.IO.Path.Combine(dirPath, $"{lockResult.ProductNumber}-{lockResult.Number}.csv");
+
+                                //锁付曲线保存路径
+                                lockResult.LockCurveImagePath = System.IO.Path.Combine(dirPath, curveFileName);
+                                var _ = lockResult.SaveToCsvAsync(curveFileFullPath);
+                            }
+
+                            lockResultsAll.Add(lockResult);
                             App.Current.Dispatcher.Invoke(() =>
                             {
                                 _eventAggregator.GetEvent<LockFinishNotification>().Publish(lockResult);
                             });
+                            //记录锁付结果至数据库
                             await _systemDatabaseService.RecordLockResultAsync(lockResult);
-                            await plc.WriteNodeAsync(addressConfig.In_WorkDone.Address, (Int16)0);
+                            //披头数量+1
+                            NumStatistics.HeaderNum = await _systemDatabaseService.IncrementLatestHeadLockCountAsync(currentUserName);
+                            //吸嘴数量+1
+                            NumStatistics.NozzleNum = await _systemDatabaseService.IncrementLatestNozzleLockCountAsync(currentUserName);
 
                             //电批吸嘴报警
                             NumStatistics.HeaderNum++;//批头数量
@@ -1673,6 +1776,10 @@ namespace TeamAAS_VP.Core
                             {
                                 System.Windows.MessageBox.Show("Nozzle Alarm!", "Alarm", MessageBoxButton.OK, MessageBoxImage.Warning);
                             }
+                        }
+                            await plc.WriteNodeAsync(addressConfig.In_WorkDone.Address, (Int16)0);
+                            // 停止采集压力并保存
+                            await StopAndSavePressureCollectionAsync(currentProduct.Name, _productService.CurrentProductCode, positionIndex);
                         }
                         else
                         {
@@ -1717,9 +1824,14 @@ namespace TeamAAS_VP.Core
 
                                 for (int i = 0; i < currentProduct.ScrewPoints.Count; i++)
                                 {
-                                    var localPoint = new PointF(currentProduct.ScrewPoints[i].X_Position, currentProduct.ScrewPoints[i].Y_Position);
+                                    var localPoint = new PointF(currentProduct.ScrewPoints[i].X_Position + currentProduct.ScrewPoints[i].X_Offset,
+                                        currentProduct.ScrewPoints[i].Y_Position + currentProduct.ScrewPoints[i].Y_Offset);
                                     var worldPoint = local.ToOldCoord(localPoint.X, localPoint.Y);
                                     var point = currentProduct.ScrewPoints[i].Clone();
+
+                                    //锁付点位在Local中已经加了偏移,这里写回PLC时需要将偏移清零,否则写入PLC端时会重复计算偏移
+                                    point.X_Offset = 0;
+                                    point.Y_Offset = 0;
                                     point.X_Position = (float)worldPoint[0];
                                     point.Y_Position = (float)worldPoint[1];
                                     SendTaskMessage($"点:{i},{point.X_Position:F3},{point.Y_Position:F4}", MessageLevel.Info);
@@ -1731,12 +1843,11 @@ namespace TeamAAS_VP.Core
                         }
                         else
                         {
-                            SendTaskMessage(string.Format(Lang.多相机坐标合并请求已结束或被取消state0,state), MessageLevel.Alarm);
+                            SendTaskMessage(string.Format(Lang.多相机坐标合并请求已结束或被取消state0, state), MessageLevel.Alarm);
                             await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)0);
                         }
                     }
                 }
-                
                 // 螺丝供料器螺丝递减
                 else if (addressConfig.In_PickINC.Address.Contains(tuple.nodeId))
                 {
@@ -1758,11 +1869,11 @@ namespace TeamAAS_VP.Core
                             var feeders = _configService.GetRemainingCountByFeederNumber(state);
                             if (state == 1)
                             {
-                                NumStatistics.Feeder1Num = feeders;
+                                NumStatistics.Feeder1Num = _configService.DecrementScrewCountByFeederNumber(feeders);
                             }
                             else if (state == 2)
                             {
-                                NumStatistics.Feeder2Num = feeders;
+                                NumStatistics.Feeder2Num = _configService.DecrementScrewCountByFeederNumber(feeders);
                             }
                             FileHelper.WriteJsonFile(NumStatistics, FilePath.NumberStatisticsPath);
                             var res = _configService.CheckAlarm(state);
@@ -1775,11 +1886,11 @@ namespace TeamAAS_VP.Core
                 }
                 
                 // 过站检查
-                else 
+                else
                 {
                     for (int i = 0; i < 10; i++)
                     {
-                        if (string.Format(addressConfig.In_MesCheck.Address,i).Contains(tuple.nodeId))
+                        if (string.Format(addressConfig.In_MesCheck.Address, i).Contains(tuple.nodeId))
                         {
                             if (tuple.value is Int16 state)
                             {
@@ -1791,28 +1902,54 @@ namespace TeamAAS_VP.Core
                                 {
                                     return;
                                 }
-
+                                var code = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, i));
+                                //询问mes
                                 if (state == 1)
                                 {
-                                    if(i == 0)
+                                    swCT.Restart();
+                                    //这里缺少从MES获取产品配方的内容,需要补充
+
+
+
+                                    (bool isSuccess, string response) = await _mesService.StationGetAsync(code, 2);
+                                    if (i == 0)
                                     {
                                         SendTaskMessage($"收到当前过站检查请求(当站是否生产)...", MessageLevel.Debug);
                                     }
                                     else
                                     {
                                         SendTaskMessage($"收到{i}过站检查请求(当站是否生产)...", MessageLevel.Debug);
-                                    }                                    
+                                    }
+                                    if (isSuccess)
+                                    {
+                                        //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+                                        await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
 
-                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
-                                    await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
+                                        await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
+                                    }
+                                    else
+                                    {
+                                        //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+                                        await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
 
-                                    await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address,i), (Int16)1);
+                                        await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)0);
+                                    }
                                 }
                                 // 上传本站数据
                                 else if (state == 2)
                                 {
                                     SendTaskMessage($"收到{i}上传本站数据请求...", MessageLevel.Debug);
+
+                                    //这里缺少上传MES的本站数据结果及开始和结束时间,需要补充
+
+                                    (bool isSuccess, string response) = await _mesService.SubmitGetAsync(code, true, DateTime.Now, DateTime.Now);
+                                    //假设上传成功,这里缺少上传失败的处理
+
                                     await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)3);
+                                    swCT.Stop();
+                                    CTtime = Math.Round(swCT.Elapsed.TotalSeconds, 3);
+                                    WriteProductLog(lockResultsAll, code, CTtime);
+                                    lockResultsAll.Clear();
                                 }
                                 else
                                 {
@@ -1822,7 +1959,7 @@ namespace TeamAAS_VP.Core
                             }
                         }
                     }
-                    
+
                 }
             }
             catch (Exception ex)
@@ -1843,6 +1980,147 @@ namespace TeamAAS_VP.Core
             });
         }
 
+        #region Pressure collection helpers
+        /// <summary>
+        /// 开始采集压力值
+        /// </summary>
+        /// <param name="productName">配方名称</param>
+        /// <param name="productCode">产品编号</param>
+        /// <param name="positionIndex">锁付点编号</param>
+        private void StartPressureCollection(string productName,string productCode, int positionIndex)
+        {
+            try
+            {
+                // cancel existing if any
+                _pressureCts?.Cancel();
+                _pressureTimeoutCts?.Cancel();
+                _pressureLinkedCts?.Dispose();
+                _pressureSamples.Clear();
+
+                _pressureCts = new CancellationTokenSource();
+                _pressureTimeoutCts = new CancellationTokenSource();
+
+                // timeout after configured seconds
+                _pressureTimeoutCts.CancelAfter(TimeSpan.FromSeconds(_pressureMaxDurationSeconds));
+
+                // link tokens so either stop or timeout cancels
+                _pressureLinkedCts = CancellationTokenSource.CreateLinkedTokenSource(_pressureCts.Token, _pressureTimeoutCts.Token);
+
+                var token = _pressureLinkedCts.Token;
+                var addressConfig = _configService.GetPlcAddresses();
+                var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
+                if (plc == null || !plc.IsConnected) return;
+                Task.Run(async () =>
+                {
+                    SendTaskMessage($"Pressure collection started for position {positionIndex}", MessageLevel.Debug);
+                    while (!token.IsCancellationRequested)
+                    {
+                        try
+                        {
+                            float pressure = plc.ReadNode<float>(addressConfig.In_PressureValue.Address);
+                            lock (_pressureSamples)
+                            {
+                                _pressureSamples.Add((DateTime.Now, pressure));
+                            }
+                        }
+                        catch (Exception ex)
+                        {
+                            LogHelper.WriteLogError("采集压力值时出错", ex);
+                        }
+                        await Task.Delay(_pressureSampleIntervalMs);
+                    }
+                    // if cancelled due to timeout
+                    if (_pressureTimeoutCts.IsCancellationRequested && !_pressureCts.IsCancellationRequested)
+                    {
+                        SendTaskMessage("Pressure collection timed out, saving collected data.", MessageLevel.Alarm);
+                        await StopAndSavePressureCollectionAsync(productName, productCode,positionIndex);
+                    }
+                }, token);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("StartPressureCollection error", ex);
+            }
+        }
+
+        /// <summary>
+        /// 停止采集并保存压力数据
+        /// </summary>
+        /// <param name="productName"></param>
+        /// <param name="productCode"></param>
+        /// <param name="positionIndex"></param>
+        /// <returns></returns>
+        private async Task StopAndSavePressureCollectionAsync(string productName, string productCode, int positionIndex)
+        {
+            try
+            {
+                // cancel sampling
+                _pressureCts?.Cancel();
+                // allow worker to observe cancel
+                await Task.Delay(50);
+
+                List<(DateTime Timestamp, float Value)> snapshot;
+                lock (_pressureSamples)
+                {
+                    snapshot = new List<(DateTime, float)>(_pressureSamples);
+                }
+
+                if (snapshot.Count == 0)
+                {
+                    SendTaskMessage("No pressure samples collected.", MessageLevel.Info);
+                    return;
+                }
+
+                // save to file under configured path
+                try
+                {
+                    //获取系统参数
+                    var systemConfig = _configService.GetSystemConfiguration();
+                    //判断是否保存锁付曲线
+                    if (systemConfig.IsSaveScrewCurve)
+                    {
+                        string basePath = systemConfig?.ScrewCurvePath ?? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
+                        string datePath = DateTime.Now.ToString("yyyy-MM") + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
+                        string dirPath = Path.Combine(basePath, datePath, productName ?? "UnknownProduct", productCode ?? DateTime.Now.ToString("yyyyMMddHHmmssfff"));
+                        if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
+                        string fileName = $"pressure-{productCode}-{positionIndex}-{DateTime.Now.ToString("HHmmss")}.csv";
+                        string fullPath = Path.Combine(dirPath, fileName);
+                        var sb = new StringBuilder();
+                        sb.AppendLine("Timestamp,Value");
+                        foreach (var s in snapshot)
+                        {
+                            sb.AppendLine($"{s.Timestamp:O},{s.Value}");
+                        }
+
+                        File.WriteAllText(fullPath, sb.ToString());
+                        SendTaskMessage($"Pressure samples saved to {fullPath}", MessageLevel.Debug);
+                    }
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("保存压力采样文件时出错", ex);
+                    SendTaskMessage("保存压力采样文件时出错: " + ex.Message, MessageLevel.Error);
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("StopAndSavePressureCollectionAsync error", ex);
+            }
+            finally
+            {
+                try
+                {
+                    _pressureLinkedCts?.Cancel();
+                    _pressureLinkedCts?.Dispose();
+                    _pressureTimeoutCts?.Dispose();
+                    _pressureCts?.Dispose();
+                    _pressureSamples.Clear();
+                }
+                catch { }
+            }
+        }
+        #endregion
+
         private async void DoYieldTime(object state)
         {
             try
@@ -1897,6 +2175,81 @@ namespace TeamAAS_VP.Core
         }
         #endregion
 
+
+        #region 产品锁付记录进行存储
+        /// <summary>
+        /// 产品锁付记录进行存储
+        /// </summary>
+        /// <param name="result">结果</param>
+        public void WriteProductLog(List<LockResult> lockResults,string rfid,double ct)
+        {
+            try
+            {
+                string result = "";//产品的总结果
+                foreach (var item in lockResults)
+                {
+                    result = "OK";
+                    if (!item.LockPassed)
+                    {
+                        result = "NG";
+                        break;
+                    }
+                }
+                DateTime dt = DateTime.Now;
+                int number = lockResults.Count;//螺丝数量
+                string path = $"E:\\Data\\生产数据\\{dt.ToString("yyyy-MM")}\\{dt.ToString("yyyy-MM-dd")}.csv";
+                StringBuilder sb = new StringBuilder();
+                //具体的ct需要优化
+                sb.Append($"{dt.ToString("yyyy-MM-dd HH:mm:ss")},{lockResults[0].ProductName},{Math.Round(ct, 3)},{rfid},{result},{lockResults[number-1].NozzleNumber},{lockResults[number - 1].HeadNumber},");
+                foreach (var item in lockResults)
+                {
+                    try
+                    {
+                        sb.Append($"{item.LockPassed},{item.ResultDetails},{item.LockTorque},{item.TargetTorqueUpperLimit},{item.TargetTorqueLowerLimit},{item.LockTurns},{item.TargetTurnsUpperLimit},{item.TargetTurnsLowerLimit},{item.Pressure},{item.PositionX},{item.PositionY},{item.StartPositionZ},{item.EndPositionZ},{item.LockDescentSpeed},");
+                    }
+                    catch (Exception)
+                    {
+                        sb.Append($",,,,,,,,,,,,,,");
+                    }
+                }
+                //========================
+                if (!Directory.Exists(Path.GetDirectoryName(path)))   //判断文件夹是否
+                {
+                    Directory.CreateDirectory(Path.GetDirectoryName(path));    //创建文件夹
+                }
+
+                if (File.Exists(path))
+                {
+                    // 使用 StreamWriter 以追加模式打开文件
+                    StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8);
+                    sw.WriteLine(sb.ToString().TrimEnd(','));
+                    sw.Close();
+                    sw.Dispose();
+                }
+                else
+                {
+                    StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8);
+                    StringBuilder sb1 = new StringBuilder();
+                    StringBuilder sb_up = new StringBuilder();
+                    StringBuilder sb_down = new StringBuilder();
+                    sb1.Append("时间,产品名称,CT,RFID,产品结果,吸嘴数量,披头数量,");
+                    for (int i = 0; i < number; i++)
+                    {
+                        sb1.Append($"螺丝{i + 1}结果,螺丝{i + 1}结果详情,螺丝{i + 1}扭矩,螺丝{i + 1}扭矩上限,螺丝{i + 1}扭矩下限,螺丝{i + 1}圈数,螺丝{i + 1}圈数上限,螺丝{i + 1}圈数下限,螺丝{i + 1}压力值,螺丝{i + 1}锁附X,螺丝{i + 1}锁附Y,螺丝{i + 1}开始位置Z,螺丝{i + 1}结束位置Z,螺丝{i + 1}锁附下降速度,");
+                    }
+                    sw.WriteLine(sb1.ToString().TrimEnd(','));
+                    sw.WriteLine(sb.ToString().TrimEnd(','));
+                    sw.Close();
+                    sw.Dispose();
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("写入产品记录时出错!", ex);
+            }
+        }
+        #endregion
+
         #endregion
     }
 }

+ 10 - 4
TeamAAS-VM/Core/ScrewDriver/XYD_ScrewDriver.cs

@@ -173,9 +173,14 @@ namespace TeamAAS_VP.Core.ScrewDriver
 
         //设定值
         /// <summary>
-        /// 目标扭矩
+        /// 目标扭矩上限
         /// </summary>
-        public float TargetTorque { get; private set; }
+        public float TargetTorqueUpperLimit { get; private set; }
+
+        /// <summary>
+        /// 目标扭矩下限
+        /// </summary>
+        public float TargetTorqueLowerLimit { get; private set; }
 
         /// <summary>
         /// 目标圈数上限
@@ -525,8 +530,9 @@ namespace TeamAAS_VP.Core.ScrewDriver
                 SectionOverLock = ToInt16(data, 100);
                 SectionFinalEnd = ToInt16(data, 102);
 
-                TargetTorque = ToInt16(data, 238) * 0.001f;//目标扭矩
-                TargetTurnsUpperLimit= ToInt16(data, 246);//最终旋转角度上限
+                TargetTorqueUpperLimit = ToInt16(data, 386) * 0.001f;//结果扭矩上限
+                TargetTorqueLowerLimit = ToInt16(data, 388) * 0.001f;//结果扭矩下限
+                TargetTurnsUpperLimit = ToInt16(data, 246);//最终旋转角度上限
                 TargetTurnsLowerLimit= ToInt16(data, 248);//最终旋转角度下限
                 TargetLockSpeed= ToInt16(data, 394);//停止速度
 

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

@@ -27,7 +27,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(ScrewFeederBatchRecord), typeof(PhotoCaptureRecord), typeof(HeadChangeRecord),typeof(NozzleChangeRecord));
 
                 // 创建索引
                 CreateIndexes();
@@ -74,6 +74,23 @@ namespace TeamAAS_VP.Data
 
                 // 你可以在这里为其他表添加索引,例如 ProductionRecord 的 Timestamp 或 ProductName
                 try { _db.DbMaintenance.CreateIndex("ProductionRecord", new string[] { "ProductName", "Timestamp" }, "IX_ProductionRecord_ProductName_Timestamp", false); } catch { }
+                // Screw feeder batch records indexes
+                try { _db.DbMaintenance.CreateIndex("ScrewFeederBatchRecord", new string[] { "ChangeTime" }, "IX_ScrewFeederBatchRecord_ChangeTime", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("ScrewFeederBatchRecord", new string[] { "FeederNumber" }, "IX_ScrewFeederBatchRecord_FeederNumber", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("ScrewFeederBatchRecord", new string[] { "BatchNumber" }, "IX_ScrewFeederBatchRecord_BatchNumber", 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 { }
+
+                // Head change records indexes
+                try { _db.DbMaintenance.CreateIndex("HeadChangeRecord", new string[] { "ChangeTime" }, "IX_HeadChangeRecord_ChangeTime", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("HeadChangeRecord", new string[] { "HeadBatchNumber" }, "IX_HeadChangeRecord_HeadBatchNumber", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("PhotoCaptureRecord", new string[] { "CameraName" }, "IX_PhotoCaptureRecord_CameraName", false); } catch { }
+                // Nozzle change records indexes (same as head)
+                try { _db.DbMaintenance.CreateIndex("NozzleChangeRecord", new string[] { "ChangeTime" }, "IX_NozzleChangeRecord_ChangeTime", false); } catch { }
+                try { _db.DbMaintenance.CreateIndex("NozzleChangeRecord", new string[] { "NozzleBatchNumber" }, "IX_NozzleChangeRecord_NozzleBatchNumber", false); } catch { }
             }
             catch
             {

+ 273 - 3
TeamAAS-VM/Data/SystemDatabaseService.cs

@@ -26,6 +26,8 @@ namespace TeamAAS_VP.Data
             _db = db;
         }
 
+        
+
         #region 用户
         // User CRUD
 
@@ -133,6 +135,25 @@ namespace TeamAAS_VP.Data
             await RecordUserLoginAsync(rec);
         }
 
+        /// <summary>
+        /// 将指定用户设为当前用户(会写入一条登录记录,标记为成功)
+        /// </summary>
+        /// <param name="user"></param>
+        /// <returns></returns>
+        public async Task SetCurrentUserAsync(User user)
+        {
+            CurrentUser = user;
+            // 记录一条成功的登录记录
+            var rec = new UserLoginRecord
+            {
+                UserId = user.Id,
+                Success = true,
+                Time = DateTime.UtcNow,
+                Message = user.UserName
+            };
+            await RecordUserLoginAsync(rec);
+        }
+
         /// <summary>
         /// 获取最近一次成功登录的用户(视为当前用户)。
         /// </summary>
@@ -603,6 +624,7 @@ namespace TeamAAS_VP.Data
 
         #endregion
 
+        #region 锁付结果记录
         // Lock result methods
         /// <summary>
         /// 记录单次锁付结果(WaveDatas 不写入数据库)
@@ -625,7 +647,7 @@ namespace TeamAAS_VP.Data
         /// <summary>
         /// 分页查询锁付结果
         /// </summary>
-        public async Task<(IEnumerable<LockResult> Items, int TotalCount)> QueryLockResultsAsync(DateTime start, DateTime end, int pageIndex, int pageSize, string productNumber = null, int? screwNumber = null, bool? lockPassed = null)
+        public async Task<(IEnumerable<LockResult> Items, int TotalCount)> QueryLockResultsAsync(DateTime start, DateTime end, int pageIndex, int pageSize, string productNumber = null, string productName = null, int? screwNumber = null, bool? lockPassed = null)
         {
             if (pageIndex < 1) pageIndex = 1;
             if (pageSize < 1) pageSize = 20;
@@ -634,6 +656,7 @@ namespace TeamAAS_VP.Data
             if (!string.IsNullOrEmpty(productNumber)) q = q.Where(r => r.ProductNumber == productNumber);
             if (screwNumber.HasValue) q = q.Where(r => r.Number == screwNumber.Value);
             if (lockPassed.HasValue) q = q.Where(r => r.LockPassed == lockPassed.Value);
+            if (!string.IsNullOrEmpty(productName)) q = q.Where(r => r.ProductName == productName);
 
             var total = await q.CountAsync();
             var list = await q.OrderBy(r => r.Timestamp, OrderByType.Desc).ToPageListAsync(pageIndex, pageSize);
@@ -643,25 +666,272 @@ namespace TeamAAS_VP.Data
         /// <summary>
         /// 查询所有符合条件的锁付结果(不分页)。
         /// </summary>
-        public async Task<IEnumerable<LockResult>> QueryAllLockResultsAsync(DateTime start, DateTime end, string productNumber = null, int? screwNumber = null, bool? lockPassed = null)
+        public async Task<IEnumerable<LockResult>> QueryAllLockResultsAsync(DateTime start, DateTime end, string productNumber = null, string productName= null, int? screwNumber = null, bool? lockPassed = null)
         {
             var q = _db.Queryable<LockResult>().Where(r => r.Timestamp >= start && r.Timestamp < end);
             if (!string.IsNullOrEmpty(productNumber)) q = q.Where(r => r.ProductNumber == productNumber);
             if (screwNumber.HasValue) q = q.Where(r => r.Number == screwNumber.Value);
             if (lockPassed.HasValue) q = q.Where(r => r.LockPassed == lockPassed.Value);
+            if (!string.IsNullOrEmpty(productName)) q = q.Where(r => r.ProductName == productName);
 
             var list = await q.OrderBy(r => r.Timestamp, OrderByType.Desc).ToListAsync();
             return list;
         }
-        
+
+        #endregion
+
+        #region 螺丝供料器批次记录
         /// <summary>
         /// 记录一次螺丝供料器批次更换记录
         /// </summary>
+        /// <param name="record"></param>
+        /// <returns></returns>
         public async Task RecordScrewFeederBatchAsync(ScrewFeederBatchRecord record)
         {
             if (record == null) throw new ArgumentNullException(nameof(record));
             if (record.ChangeTime == default(DateTime)) record.ChangeTime = DateTime.UtcNow;
+            record.Id = record.Id == Guid.Empty ? Guid.NewGuid() : record.Id;
             await _db.Insertable(record).ExecuteCommandAsync();
         }
+
+        /// <summary>
+        /// 查询螺丝供料器批次记录。
+        /// 可按时间段、批次号精确匹配及供料器编号过滤。所有参数均为可选,传入 null 表示不作为过滤条件。
+        /// </summary>
+        /// <param name="start">可选:起始时间(包含)</param>
+        /// <param name="end">可选:结束时间(包含)</param>
+        /// <param name="batchNumber">可选:批次号(精确匹配)</param>
+        /// <param name="feederNumber">可选:供料器编号</param>
+        /// <returns>满足条件的记录集合(按 ChangeTime 降序)。</returns>
+        public async Task<IEnumerable<ScrewFeederBatchRecord>> QueryScrewFeederBatchRecordsAsync(DateTime? start = null, DateTime? end = null, string batchNumber = null, int? feederNumber = null)
+        {
+            var q = _db.Queryable<ScrewFeederBatchRecord>();
+            if (start.HasValue)
+                q = q.Where(r => r.ChangeTime >= start.Value);
+            if (end.HasValue)
+                q = q.Where(r => r.ChangeTime <= end.Value);
+            if (!string.IsNullOrEmpty(batchNumber))
+                q = q.Where(r => r.BatchNumber == batchNumber);
+            if (feederNumber.HasValue)
+                q = q.Where(r => r.FeederNumber == feederNumber.Value);
+
+            var list = await q.OrderBy(r => r.ChangeTime, OrderByType.Desc).ToListAsync();
+            return list;
+        }
+
+        /// <summary>
+        /// 获取指定供料器编号的最新一条批次更换记录
+        /// </summary>
+        /// <param name="feederNumber"></param>
+        /// <returns></returns>
+        public async Task<ScrewFeederBatchRecord> GetLatestScrewFeederBatchRecordAsync(int feederNumber)
+        {
+            var recs = await _db.Queryable<ScrewFeederBatchRecord>()
+                .Where(r => r.FeederNumber == feederNumber)
+                .OrderBy(r => r.ChangeTime, OrderByType.Desc)
+                .Take(1)
+                .ToListAsync();
+            return recs.FirstOrDefault();
+        }
+
+        #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;
+        }
+        #endregion
+
+        #region 披头更换记录
+        /// <summary>
+        /// 记录披头更换
+        /// </summary>
+        /// <param name="record"></param>
+        /// <returns></returns>
+        /// <exception cref="ArgumentNullException"></exception>
+        public async Task RecordHeadChangeAsync(HeadChangeRecord record)
+        {
+            if (record == null) throw new ArgumentNullException(nameof(record));
+            if (record.ChangeTime == default(DateTime)) record.ChangeTime = DateTime.UtcNow;
+            record.Id = record.Id == Guid.Empty ? Guid.NewGuid() : record.Id;
+            await _db.Insertable(record).ExecuteCommandAsync();
+        }
+
+        /// <summary>
+        /// 查询披头更换记录
+        /// </summary>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <param name="headBatchNumber"></param>
+        /// <returns></returns>
+        public async Task<IEnumerable<HeadChangeRecord>> QueryHeadChangeRecordsAsync(DateTime? start = null, DateTime? end = null, string headBatchNumber = null)
+        {
+            var q = _db.Queryable<HeadChangeRecord>();
+            if (start.HasValue) q = q.Where(r => r.ChangeTime >= start.Value);
+            if (end.HasValue) q = q.Where(r => r.ChangeTime <= end.Value);
+            if (!string.IsNullOrEmpty(headBatchNumber)) q = q.Where(r => r.HeadBatchNumber == headBatchNumber);
+            var list = await q.OrderBy(r => r.ChangeTime, OrderByType.Desc).ToListAsync();
+            return list;
+        }
+
+        /// <summary>
+        /// 获取最新的一条披头更换记录
+        /// </summary>
+        /// <returns></returns>
+        public async Task<HeadChangeRecord> GetLatestHeadChangeRecordAsync()
+        {
+            var recs = await _db.Queryable<HeadChangeRecord>().OrderBy(r => r.ChangeTime, OrderByType.Desc).Take(1).ToListAsync();
+            return recs.FirstOrDefault();
+        }
+
+        /// <summary>
+        /// 对最新披头的锁付次数进行递增并返回更新后的次数(原子操作)。
+        /// 若不存在记录则创建一条新记录并返回 1。
+        /// </summary>
+        public async Task<int> IncrementLatestHeadLockCountAsync(string operatorName = null)
+        {
+            // 使用事务保证原子性
+            try
+            {
+                _db.Ado.BeginTran();
+                // 获取最新记录(排他查询)
+                var latest = _db.Queryable<HeadChangeRecord>().OrderBy(r => r.ChangeTime, OrderByType.Desc).Take(1).First();
+                if (latest == null)
+                {
+                    var newRec = new HeadChangeRecord
+                    {
+                        ChangeTime = DateTime.UtcNow,
+                        HeadBatchNumber = string.Empty,
+                        CurrentLockCount = 1,
+                        OperatorName = operatorName
+                    };
+                    await _db.Insertable(newRec).ExecuteCommandAsync();
+                    _db.Ado.CommitTran();
+                    return 1;
+                }
+
+                latest.CurrentLockCount += 1;
+                if (!string.IsNullOrEmpty(operatorName)) latest.OperatorName = operatorName;
+                await _db.Updateable(latest).ExecuteCommandAsync();
+                _db.Ado.CommitTran();
+                return latest.CurrentLockCount;
+            }
+            catch
+            {
+                try { _db.Ado.RollbackTran(); } catch { }
+                throw;
+            }
+        }
+        #endregion
+
+        #region 吸嘴更换记录
+        /// <summary>
+        /// 记录喷嘴更换记录。
+        /// </summary>
+        /// <param name="record"></param>
+        /// <returns></returns>
+        public async Task RecordNozzleChangeAsync(NozzleChangeRecord record)
+        {
+            if (record == null) throw new ArgumentNullException(nameof(record));
+            if (record.ChangeTime == default(DateTime)) record.ChangeTime = DateTime.UtcNow;
+            record.Id = record.Id == Guid.Empty ? Guid.NewGuid() : record.Id;
+            await _db.Insertable(record).ExecuteCommandAsync();
+        }
+
+        /// <summary>
+        /// 查询喷嘴更换记录,可按时间段或喷嘴批号过滤(所有参数可选)。
+        /// </summary>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <param name="nozzleBatchNumber"></param>
+        /// <returns></returns>
+        public async Task<IEnumerable<NozzleChangeRecord>> QueryNozzleChangeRecordsAsync(DateTime? start = null, DateTime? end = null, string nozzleBatchNumber = null)
+        {
+            var q = _db.Queryable<NozzleChangeRecord>();
+            if (start.HasValue) q = q.Where(r => r.ChangeTime >= start.Value);
+            if (end.HasValue) q = q.Where(r => r.ChangeTime <= end.Value);
+            if (!string.IsNullOrEmpty(nozzleBatchNumber)) q = q.Where(r => r.NozzleBatchNumber == nozzleBatchNumber);
+            var list = await q.OrderBy(r => r.ChangeTime, OrderByType.Desc).ToListAsync();
+            return list;
+        }
+
+        /// <summary>
+        /// 获取最新的一条喷嘴更换记录(按 ChangeTime 降序)。
+        /// </summary>
+        /// <returns></returns>
+        public async Task<NozzleChangeRecord> GetLatestNozzleChangeRecordAsync()
+        {
+            var recs = await _db.Queryable<NozzleChangeRecord>().OrderBy(r => r.ChangeTime, OrderByType.Desc).Take(1).ToListAsync();
+            return recs.FirstOrDefault();
+        }
+
+        /// <summary>
+        /// 吸嘴的锁付次数进行递增并返回更新后的次数(如果不存在最新记录,则创建一条新的记录并返回 1)。
+        /// </summary>
+        /// <param name="operatorName"></param>
+        /// <returns></returns>
+        public async Task<int> IncrementLatestNozzleLockCountAsync(string operatorName = null)
+        {
+            try
+            {
+                _db.Ado.BeginTran();
+                var latest = _db.Queryable<NozzleChangeRecord>().OrderBy(r => r.ChangeTime, OrderByType.Desc).Take(1).First();
+                if (latest == null)
+                {
+                    var newRec = new NozzleChangeRecord
+                    {
+                        ChangeTime = DateTime.UtcNow,
+                        NozzleBatchNumber = string.Empty,
+                        CurrentLockCount = 1,
+                        OperatorName = operatorName
+                    };
+                    await _db.Insertable(newRec).ExecuteCommandAsync();
+                    _db.Ado.CommitTran();
+                    return 1;
+                }
+
+                latest.CurrentLockCount += 1;
+                if (!string.IsNullOrEmpty(operatorName)) latest.OperatorName = operatorName;
+                await _db.Updateable(latest).ExecuteCommandAsync();
+                _db.Ado.CommitTran();
+                return latest.CurrentLockCount;
+            }
+            catch
+            {
+                try { _db.Ado.RollbackTran(); } catch { }
+                throw;
+            }
+        }
+        #endregion
     }
 }

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

+ 25 - 5
TeamAAS-VM/Interfaces/IConfigService.cs

@@ -2,6 +2,7 @@ using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Threading.Tasks;
+using TeamAAS_VP.Enums;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Models.Calibration;
 using TeamAAS_VP.Models.Feeder;
@@ -268,6 +269,18 @@ namespace TeamAAS_VP.Interfaces
         /// </summary>
         void SaveSystemConfiguration(SystemConfiguration systemConfiguration);
 
+        /// <summary>
+        /// 获取当前语言
+        /// </summary>
+        /// <returns></returns>
+        Language GetCurrentLanguage();
+
+        /// <summary>
+        /// 设置当前语言
+        /// </summary>
+        /// <param name="language"></param>
+        void SetCurrentLanguage(Language language);
+
         //清料任务
 
         /// <summary>
@@ -446,7 +459,7 @@ namespace TeamAAS_VP.Interfaces
         /// <summary>
         /// 为指定供料器编号递减指定数量(通常为 1),若数量不足返回 false
         /// </summary>
-        bool DecrementScrewCountByFeederNumber(int feederNumber, int decrement = 1);
+        int DecrementScrewCountByFeederNumber(int feederNumber, int decrement = 1);
 
         /// <summary>
         /// 清除指定供料器编号的螺丝信息(批次号与剩余数量置空/置0)
@@ -474,13 +487,20 @@ namespace TeamAAS_VP.Interfaces
         event Action<ScrewFeederInfo> ScrewFeederLowLevelAlarmTriggered;
 
         /// <summary>
-        /// 记录一次螺丝供料器批次更换记录(写入数据库)。
+        /// 检查剩余螺丝是否报警
         /// </summary>
-        Task RecordScrewFeederBatchAsync(ScrewFeederBatchRecord record);
+        bool CheckAlarm(int feederNumber);
 
+        //刷卡登录
         /// <summary>
-        /// 检查剩余螺丝是否报警
+        /// 获取刷卡器配置
         /// </summary>
-        bool CheckAlarm(int feederNumber);
+        /// <returns></returns>
+        SerialPortConfig GetCardReaderConfig();
+        /// <summary>
+        /// 保存刷卡器配置
+        /// </summary>
+        /// <param name="config"></param>
+        void SaveCardReaderConfig(SerialPortConfig config);
     }
 }

+ 69 - 7
TeamAAS-VM/Interfaces/IMesService.cs

@@ -6,20 +6,82 @@ using System.Threading.Tasks;
 namespace TeamAAS_VP.Interfaces
 {
     /// <summary>
-    /// MES 通信服务接口,提供通过配置的 URL 执行过站及提交信息的 GET 请求。
+    /// MES 通信服务接口。
+    /// 提供通过配置的 URL 发起 GET 请求的抽象,用于执行过站(Station)与提交结果(Submit)操作。
+    /// 实现者应负责管理内部 HTTP 客户端或通信资源,并在 Dispose 中释放这些资源。
     /// </summary>
     public interface IMesService : IDisposable
     {
         /// <summary>
-        /// 使用配置的过站 URL 发起 GET 请求。可传入额外的查询参数。
-        /// 返回 (IsSuccess, ResponseString)。
+        /// 使用配置的过站(Station)URL 发起 GET 请求,携带序列号(sn)作为查询参数进行过站。
         /// </summary>
-        Task<(bool IsSuccess, string Response)> StationGetAsync(IDictionary<string, string> queryParameters = null, CancellationToken cancellationToken = default);
+        /// <param name="sn">要过站的产品序列号,不能为空或空白。</param>
+        /// <param name="cancellationToken">用于在外部请求取消时中止异步请求的 <see cref="CancellationToken"/>。默认值为 <see cref="CancellationToken.None"/>。</param>
+        /// <returns>
+        /// 一个包含请求结果的元组:
+        /// IsSuccess 表示请求并解析 MES 响应是否被认为成功(由实现定义,例如 HTTP 200 且业务状态正常)。
+        /// Response 为 MES 返回的原始响应字符串或描述错误的信息(不为 null,可为空字符串)。
+        /// </returns>
+        /// <remarks>
+        /// - 实现应从配置中读取过站 URL 并将 sn 作为查询参数附加到 URL。
+        /// - 实现应尊重 <paramref name="cancellationToken"/>,在取消时尽早抛出 <see cref="OperationCanceledException"/> 或返回失败结果。
+        /// - 若 <paramref name="sn"/> 无效,应抛出 <see cref="ArgumentNullException"/> 或 <see cref="ArgumentException"/>。
+        /// </remarks>
+        Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, CancellationToken cancellationToken = default);
 
         /// <summary>
-        /// 使用配置的提交 URL 发起 GET 请求。可传入额外的查询参数。
-        /// 返回 (IsSuccess, ResponseString)。
+        /// 使用配置的过站(Station)URL 发起 GET 请求,携带序列号(sn)作为查询参数进行过站,并使用指定的超时时间(秒)。
         /// </summary>
-        Task<(bool IsSuccess, string Response)> SubmitGetAsync(IDictionary<string, string> queryParameters = null, CancellationToken cancellationToken = default);
+        /// <param name="sn">要过站的产品序列号,不能为空或空白。</param>
+        /// <param name="timeoutInSeconds">请求超时时间,单位为秒。应为正数;实现可以将其应用到 HTTP 客户端或请求级别超时。</param>
+        /// <returns>
+        /// 一个包含请求结果的元组:
+        /// IsSuccess 表示请求并解析 MES 响应是否被认为成功。
+        /// Response 为 MES 返回的原始响应字符串或描述错误的信息。
+        /// </returns>
+        /// <remarks>
+        /// - 此重载方便在不使用 <see cref="CancellationToken"/> 的场景中指定超时时间。
+        /// - 实现应验证 <paramref name="timeoutInSeconds"/> 为合理值(例如 > 0),否则可抛出 <see cref="ArgumentOutOfRangeException"/>。
+        /// </remarks>
+        Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, double timeoutInSeconds);
+
+        /// <summary>
+        /// 使用配置的提交(Submit)URL 发起 GET 请求,提交过站结果及时间信息。
+        /// </summary>
+        /// <param name="sn">待提交的产品序列号,不能为空或空白。</param>
+        /// <param name="isSuccess">表示该序列号对应的过站是否成功(业务层面的成功标志)。</param>
+        /// <param name="start_time">过程开始时间(本地时间或 UTC,取决于与 MES 的约定)。实现方应按与 MES 约定的时区/格式发送。</param>
+        /// <param name="stop_time">过程结束时间,语义同 <paramref name="start_time"/>。</param>
+        /// <param name="cancellationToken">用于在外部请求取消时中止异步请求的 <see cref="CancellationToken"/>。默认值为 <see cref="CancellationToken.None"/>。</param>
+        /// <returns>
+        /// 一个包含请求结果的元组:
+        /// IsSuccess 表示提交请求及解析 MES 响应是否被认为成功。
+        /// Response 为 MES 返回的原始响应字符串或描述错误的信息。
+        /// </returns>
+        /// <remarks>
+        /// - 实现应将时间参数按 MES 要求格式化为查询字符串或适当的请求参数。
+        /// - 若 <paramref name="start_time"/> 晚于 <paramref name="stop_time"/>,实现应记录并视情况返回失败或抛出异常。
+        /// - 实现应尊重 <paramref name="cancellationToken"/>,并在取消时尽早中止请求。
+        /// </remarks>
+        Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default);
+
+        /// <summary>
+        /// 使用配置的提交(Submit)URL 发起 GET 请求,提交过站结果及时间信息,并使用指定的超时时间(秒)。
+        /// </summary>
+        /// <param name="sn">待提交的产品序列号,不能为空或空白。</param>
+        /// <param name="isSuccess">表示该序列号对应的过站是否成功。</param>
+        /// <param name="start_time">过程开始时间。</param>
+        /// <param name="stop_time">过程结束时间。</param>
+        /// <param name="timeoutInSeconds">请求超时时间,单位为秒。应为正数。</param>
+        /// <returns>
+        /// 一个包含请求结果的元组:
+        /// IsSuccess 指示提交是否被认为成功。
+        /// Response 包含 MES 的原始响应或错误信息。
+        /// </returns>
+        /// <remarks>
+        /// - 此重载用于在不传入 <see cref="CancellationToken"/> 的场景中指定超时时间。
+        /// - 实现应确保对时间参数与布尔参数进行适当的 URL 编码或格式化。
+        /// </remarks>
+        Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, bool isSuccess, DateTime start_time, DateTime stop_time, double timeoutInSeconds);
     }
 }

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

@@ -202,7 +202,7 @@ namespace TeamAAS_VP.Interfaces
         /// </summary>
         /// <param name="cancellationToken"></param>
         /// <returns></returns>
-        Task<bool> IsRobotInDebugModeAsync(int robotNumber,CancellationToken cancellationToken);
+        Task<bool> IsRobotInDebugModeAsync(int robotNumber, CancellationToken cancellationToken);
 
         /// <summary>
         /// 执行视觉任务
@@ -249,7 +249,7 @@ namespace TeamAAS_VP.Interfaces
         /// <param name="robotCoord"></param>
         /// <param name="cancellationToken"></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, string remark);
 
         /// <summary>
         /// 执行相机拍照获取单个点位结果,并且返回图像和图形

+ 105 - 2
TeamAAS-VM/Interfaces/ISystemDatabaseService.cs

@@ -123,6 +123,13 @@ namespace TeamAAS_VP.Interfaces
         /// </remarks>
         Task SetCurrentUserAsync(int userId);
 
+        /// <summary>
+        /// 将指定用户设为当前用户(会写入一条登录记录,标记为成功)
+        /// </summary>
+        /// <param name="user"></param>
+        /// <returns></returns>
+        Task SetCurrentUserAsync(User user);
+
         /// <summary>
         /// 获取当前(最近一次成功登录的)用户。
         /// </summary>
@@ -305,7 +312,7 @@ namespace TeamAAS_VP.Interfaces
         /// <param name="screwNumber">可选的螺丝编号(Number)过滤</param>
         /// <param name="lockPassed">可选的是否通过过滤</param>
         /// <returns>返回一个元组,包含记录集合和总记录数</returns>
-        Task<(IEnumerable<LockResult> Items, int TotalCount)> QueryLockResultsAsync(DateTime start, DateTime end, int pageIndex, int pageSize, string productNumber = null, int? screwNumber = null, bool? lockPassed = null);
+        Task<(IEnumerable<LockResult> Items, int TotalCount)> QueryLockResultsAsync(DateTime start, DateTime end, int pageIndex, int pageSize, string productNumber = null, string productName = null, int? screwNumber = null, bool? lockPassed = null);
 
         /// <summary>
         /// 查询所有符合条件的锁付结果(不分页)。
@@ -316,11 +323,107 @@ namespace TeamAAS_VP.Interfaces
         /// <param name="screwNumber">可选的螺丝编号过滤</param>
         /// <param name="lockPassed">可选的是否通过过滤</param>
         /// <returns>符合条件的锁付结果集合。</returns>
-        Task<IEnumerable<LockResult>> QueryAllLockResultsAsync(DateTime start, DateTime end, string productNumber = null, int? screwNumber = null, bool? lockPassed = null);
+        Task<IEnumerable<LockResult>> QueryAllLockResultsAsync(DateTime start, DateTime end, string productNumber = null, string productName = null, int? screwNumber = null, bool? lockPassed = null);
 
         /// <summary>
         /// 记录一次螺丝供料器批次更换记录
         /// </summary>
+        /// <param name="record"></param>
+        /// <returns></returns>
         Task RecordScrewFeederBatchAsync(ScrewFeederBatchRecord record);
+
+        /// <summary>
+        /// 查询螺丝供料器批次记录。
+        /// 可按时间段、批次号精确匹配及供料器编号过滤。所有参数均为可选,传入 null 表示不作为过滤条件。
+        /// </summary>
+        /// <param name="start">可选:起始时间(包含)</param>
+        /// <param name="end">可选:结束时间(包含)</param>
+        /// <param name="batchNumber">可选:批次号(精确匹配)</param>
+        /// <param name="feederNumber">可选:供料器编号</param>
+        /// <returns>满足条件的记录集合(按 ChangeTime 降序)。</returns>
+        Task<IEnumerable<ScrewFeederBatchRecord>> QueryScrewFeederBatchRecordsAsync(DateTime? start = null, DateTime? end = null, string batchNumber = null, int? feederNumber = null);
+
+        /// <summary>
+        /// 获取指定供料器编号的最新一条批次更换记录
+        /// </summary>
+        /// <param name="feederNumber"></param>
+        /// <returns></returns>
+        Task<ScrewFeederBatchRecord> GetLatestScrewFeederBatchRecordAsync(int feederNumber);
+
+        /// <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="record"></param>
+        /// <returns></returns>
+        Task RecordHeadChangeAsync(HeadChangeRecord record);
+
+        /// <summary>
+        /// 查询披头更换记录,可按时间段或披头批号过滤(所有参数可选)。
+        /// </summary>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <param name="headBatchNumber"></param>
+        /// <returns></returns>
+        Task<IEnumerable<HeadChangeRecord>> QueryHeadChangeRecordsAsync(DateTime? start = null, DateTime? end = null, string headBatchNumber = null);
+
+        /// <summary>
+        /// 获取最新的一条披头更换记录(按 ChangeTime 降序)。
+        /// </summary>
+        /// <returns></returns>
+        Task<HeadChangeRecord> GetLatestHeadChangeRecordAsync();
+
+        /// <summary>
+        /// 对最新披头的锁付次数进行递增并返回更新后的次数(如果不存在最新记录,则创建一条新的记录并返回 1)。
+        /// </summary>
+        /// <param name="operatorName"></param>
+        /// <returns></returns>
+        Task<int> IncrementLatestHeadLockCountAsync(string operatorName = null);
+
+        /// <summary>
+        /// 记录喷嘴更换记录。
+        /// </summary>
+        /// <param name="record"></param>
+        /// <returns></returns>
+        Task RecordNozzleChangeAsync(NozzleChangeRecord record);
+
+        /// <summary>
+        /// 查询喷嘴更换记录,可按时间段或喷嘴批号过滤(所有参数可选)。
+        /// </summary>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <param name="nozzleBatchNumber"></param>
+        /// <returns></returns>
+        Task<IEnumerable<NozzleChangeRecord>> QueryNozzleChangeRecordsAsync(DateTime? start = null, DateTime? end = null, string nozzleBatchNumber = null);
+
+        /// <summary>
+        /// 获取最新的一条喷嘴更换记录(按 ChangeTime 降序)。
+        /// </summary>
+        /// <returns></returns>
+        Task<NozzleChangeRecord> GetLatestNozzleChangeRecordAsync();
+
+        /// <summary>
+        /// 吸嘴的锁付次数进行递增并返回更新后的次数(如果不存在最新记录,则创建一条新的记录并返回 1)。
+        /// </summary>
+        /// <param name="operatorName"></param>
+        /// <returns></returns>
+        Task<int> IncrementLatestNozzleLockCountAsync(string operatorName = null);
     }
 }

+ 8 - 0
TeamAAS-VM/LogHelper.cs

@@ -17,6 +17,7 @@ namespace TeamAAS_VP
         public static readonly ILog logfatal = LogManager.GetLogger("logfatal");
         public static readonly ILog logDynamic = LogManager.GetLogger("logDynamic");
         public static readonly ILog logCT = LogManager.GetLogger("logCT");
+        public static readonly ILog logmes = LogManager.GetLogger("logMes");
         public static void WriteLogInfo(string info)
         {
             if (loginfo.IsInfoEnabled)
@@ -76,7 +77,14 @@ namespace TeamAAS_VP
                 logCT.Info(info);
             }
         }
+        public static void WriteLogMes(string info)
+        {
+            if (logmes.IsInfoEnabled)
+            {
+                logmes.Info(info);
 
+            }
+        }
         internal static void WriteLogError(Lang lang, double v, object 点校准界面加载时出错, Exception ex)
         {
             throw new NotImplementedException();

+ 34 - 0
TeamAAS-VM/Models/HeadChangeRecord.cs

@@ -0,0 +1,34 @@
+using SqlSugar;
+using System;
+
+namespace TeamAAS_VP.Models
+{
+    [SugarTable("HeadChangeRecord")]
+    public class HeadChangeRecord
+    {
+        [SugarColumn(IsPrimaryKey = true)]
+        public Guid Id { get; set; } = Guid.NewGuid();
+
+        /// <summary>
+        /// 更换时间
+        /// </summary>
+        public DateTime ChangeTime { get; set; } = DateTime.UtcNow;
+
+        /// <summary>
+        /// 披头批号
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string HeadBatchNumber { get; set; }
+
+        /// <summary>
+        /// 当前披头锁付次数
+        /// </summary>
+        public int CurrentLockCount { get; set; }
+
+        /// <summary>
+        /// 操作员名称
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string OperatorName { get; set; }
+    }
+}

+ 123 - 60
TeamAAS-VM/Models/Lights/LightControllerConfig.cs

@@ -15,7 +15,7 @@ namespace TeamAAS_VP.Models.Lights
     /// 根据所选的 <see cref="LightModel"/> 执行不同的初始化逻辑(如通道数量、串口或 TCP 配置等)。
     /// 该类继承自 Prism 的 <see cref="BindableBase"/>,支持属性变更通知,适用于 WPF MVVM 绑定。
     /// </summary>
-    public class LightControllerConfig: BindableBase
+    public class LightControllerConfig : BindableBase
     {
         private int _Id;
         /// <summary>
@@ -56,52 +56,7 @@ namespace TeamAAS_VP.Models.Lights
         public LightModel LightModel
         {
             get { return _LightModel; }
-            set {
-                if (SetProperty(ref _LightModel, value))
-                {
-                    // 当 LightModel 发生变化时,根据不同型号初始化相关字段与集合。
-                    switch (value)
-                    {
-                        case LightModel.KCS_KDC_12V60W_4T:
-                            // 该型号为 4 通道的串口控制器(示例)
-                            ChannelCount = 4;
-                            // 对于串口型号,清空/禁用 TCP 配置
-                            TcpConfig = null;
-                            // 如果尚未创建串口配置则初始化
-                            if (SerialPortConfig == null)
-                            {
-                                SerialPortConfig = new SerialPortConfig();
-                            }
-
-                            // 初始化通道集合,确保包含正确数量的 ChannelConfig
-                            ChannelConfigs = new ObservableCollection<ChannelConfig>();
-                            if (ChannelConfigs.Count != ChannelCount)
-                            {
-                                ChannelConfigs.Clear();
-                                for (int i = 0; i < ChannelCount; i++)
-                                {
-                                    // 为每个通道创建默认配置:本地索引/全局索引、名称、描述和默认亮度
-                                    ChannelConfigs.Add(new ChannelConfig()
-                                    {
-                                        LocalIndex = i,
-                                        GlobalIndex = i,
-                                        Name = $"Channel {i + 1}",
-                                        Description = $"Description for Channel {i + 1}",
-                                        DefaultBrightness = 100
-                                    });
-                                }
-                            }
-
-                            break;
-                        default:
-                            // 对于未知或未实现的型号,清理所有特定配置并使用默认空集合
-                            ChannelConfigs = new ObservableCollection<ChannelConfig>();
-                            SerialPortConfig = null;
-                            TcpConfig = null;
-                            break;
-                    }
-                }
-            }
+            set { SetProperty(ref _LightModel, value); }
         }
 
         private ObservableCollection<ChannelConfig> _ChannelConfigs;
@@ -160,30 +115,138 @@ namespace TeamAAS_VP.Models.Lights
             switch (LightModel)
             {
                 case LightModel.KCS_KDC_12V60W_4T:
-                    // 该型号为 4 通道的串口控制器(示例),与 setter 中保持一致的初始化
+                    // 该型号为 4 通道的串口控制器(示例)
                     ChannelCount = 4;
                     TcpConfig = null;
-                    SerialPortConfig = new SerialPortConfig();
-                    ChannelConfigs = new ObservableCollection<ChannelConfig>();
-                    for (int i = 0; i < ChannelCount; i++)
+                    if (SerialPortConfig == null)
+                    {
+                        SerialPortConfig = new SerialPortConfig();
+                    }
+                    // 调整通道集合,保留已有配置,若不足则追加,若过多则裁剪
+                    ResizeChannelConfigs(ChannelCount);
+                    break;
+                case LightModel.KCS_KDC3_24V300W_8T:
+                    // 该型号为 8 通道的串口控制器(示例)
+                    ChannelCount = 8;
+                    TcpConfig = null;
+                    if (SerialPortConfig == null)
                     {
-                        ChannelConfigs.Add(new ChannelConfig()
-                        {
-                            LocalIndex = i,
-                            GlobalIndex = i,
-                            Name = $"Channel {i + 1}",
-                            Description = $"Description for Channel {i + 1}",
-                            DefaultBrightness = 100
-                        });
+                        SerialPortConfig = new SerialPortConfig();
                     }
+                    ResizeChannelConfigs(ChannelCount);
                     break;
                 default:
                     // 未知型号:初始化空集合并清空通信配置
-                    ChannelConfigs = new ObservableCollection<ChannelConfig>();
+                    ChannelCount = 0;
+                    if (ChannelConfigs == null)
+                        ChannelConfigs = new ObservableCollection<ChannelConfig>();
+                    else
+                        ResizeChannelConfigs(0);
+                    SerialPortConfig = null;
+                    TcpConfig = null;
+                    break;
+            }
+        }
+
+        public LightControllerConfig Init()
+        {
+            // 当 LightModel 发生变化时,根据不同型号初始化相关字段与集合。
+            switch (LightModel)
+            {
+                case LightModel.KCS_KDC_12V60W_4T:
+                    // 该型号为 4 通道的串口控制器(示例)
+                    ChannelCount = 4;
+                    TcpConfig = null;
+                    if (SerialPortConfig == null)
+                    {
+                        SerialPortConfig = new SerialPortConfig();
+                    }
+                    ResizeChannelConfigs(ChannelCount);
+                    break;
+                case LightModel.KCS_KDC3_24V300W_8T:
+                    // 该型号为 8 通道的串口控制器(示例)
+                    ChannelCount = 8;
+                    TcpConfig = null;
+                    if (SerialPortConfig == null)
+                    {
+                        SerialPortConfig = new SerialPortConfig();
+                    }
+                    ResizeChannelConfigs(ChannelCount);
+                    break;
+                default:
+                    // 对于未知或未实现的型号,清理所有特定配置并使用默认空集合
+                    ChannelCount = 0;
+                    if (ChannelConfigs == null)
+                        ChannelConfigs = new ObservableCollection<ChannelConfig>();
+                    else
+                        ResizeChannelConfigs(0);
                     SerialPortConfig = null;
                     TcpConfig = null;
                     break;
             }
+            return this;
+        }
+
+        /// <summary>
+        /// 调整 ChannelConfigs 的数量以匹配 desiredCount:
+        /// - 保留已有前段配置;
+        /// - 若不足则追加新配置;
+        /// - 若过多则从末尾裁剪;
+        /// - 最后规范化每个通道的 LocalIndex/GlobalIndex,并在 Name/Description 为空时填默认值。
+        /// </summary>
+        /// <param name="desiredCount">期望的通道数量</param>
+        private void ResizeChannelConfigs(int desiredCount)
+        {
+            if (ChannelConfigs == null)
+            {
+                ChannelConfigs = new ObservableCollection<ChannelConfig>();
+            }
+
+            int current = ChannelConfigs.Count;
+
+            if (current < desiredCount)
+            {
+                for (int i = current; i < desiredCount; i++)
+                {
+                    ChannelConfigs.Add(new ChannelConfig()
+                    {
+                        LocalIndex = i,
+                        GlobalIndex = i,
+                        Name = $"Channel {i + 1}",
+                        Description = $"Description for Channel {i + 1}",
+                        DefaultBrightness = 100
+                    });
+                }
+            }
+            else if (current > desiredCount)
+            {
+                // 从末尾删除多余通道,保留前面的配置
+                for (int i = current - 1; i >= desiredCount; i--)
+                {
+                    ChannelConfigs.RemoveAt(i);
+                }
+            }
+
+            // 规范化索引与默认文本(不覆盖已有非空 Name/Description)
+            for (int i = 0; i < ChannelConfigs.Count; i++)
+            {
+                var cfg = ChannelConfigs[i];
+                if (cfg == null)
+                    continue;
+
+                cfg.LocalIndex = i;
+                cfg.GlobalIndex = i;
+
+                if (string.IsNullOrWhiteSpace(cfg.Name))
+                    cfg.Name = $"Channel {i + 1}";
+
+                if (string.IsNullOrWhiteSpace(cfg.Description))
+                    cfg.Description = $"Description for Channel {i + 1}";
+
+                // 如果需要可以在此处保留或调整 DefaultBrightness 等字段,但默认不覆盖已有值
+                if (cfg.DefaultBrightness <= 0)
+                    cfg.DefaultBrightness = 100;
+            }
         }
     }
 }

+ 87 - 27
TeamAAS-VM/Models/LockResult.cs

@@ -124,14 +124,24 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref __Pressure, value); }
         }
 
-        private float __TargetTorque;
+        private float __TargetTorqueUpperLimit;
         /// <summary>
-        /// 目标扭矩
+        /// 目标扭矩上限
         /// </summary>
-        public float TargetTorque
+        public float TargetTorqueUpperLimit
         {
-            get { return __TargetTorque; }
-            set { SetProperty(ref __TargetTorque, value); }
+            get { return __TargetTorqueUpperLimit; }
+            set { SetProperty(ref __TargetTorqueUpperLimit, value); }
+        }
+
+        private float __TargetTorqueLowerLimit;
+        /// <summary>
+        /// 目标扭矩下限
+        /// </summary>
+        public float TargetTorqueLowerLimit
+        {
+            get { return __TargetTorqueLowerLimit; }
+            set { SetProperty(ref __TargetTorqueLowerLimit, value); }
         }
 
         private float __TargetTurnsUpperLimit;
@@ -174,24 +184,24 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref _ScrewdriverGetDataSucceed, value); }
         }
 
-        private float __StartPositionX;
+        private float __PositionX;
         /// <summary>
-        /// 锁付位置坐标 X 起始值
+        /// 锁付位置坐标 X 值
         /// </summary>
-        public float StartPositionX
+        public float PositionX
         {
-            get { return __StartPositionX; }
-            set { SetProperty(ref __StartPositionX, value); }
+            get { return __PositionX; }
+            set { SetProperty(ref __PositionX, value); }
         }
 
-        private float __StartPositionY;
+        private float __PositionY;
         /// <summary>
-        /// 锁付位置坐标 Y 起始值
+        /// 锁付位置坐标 Y 值
         /// </summary>
-        public float StartPositionY
+        public float PositionY
         {
-            get { return __StartPositionY; }
-            set { SetProperty(ref __StartPositionY, value); }
+            get { return __PositionY; }
+            set { SetProperty(ref __PositionY, value); }
         }
 
         private float __StartPositionZ;
@@ -206,7 +216,7 @@ namespace TeamAAS_VP.Models
 
         private float __EndPositionZ;
         /// <summary>
-        /// Z 终点值
+        /// 锁付位置坐标 Z 终点值
         /// </summary>
         public float EndPositionZ
         {
@@ -246,7 +256,7 @@ namespace TeamAAS_VP.Models
 
         private string __NozzleNumber;
         /// <summary>
-        /// 披头编号
+        /// 吸嘴编号
         /// </summary>
         [SugarColumn(IsNullable = true)]
         public string NozzleNumber
@@ -255,6 +265,17 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref __NozzleNumber, value); }
         }
 
+        private string _HeadNumber;
+        /// <summary>
+        /// 披头编号
+        /// </summary>
+        [SugarColumn(IsNullable = true)]
+        public string HeadNumber
+            {
+            get { return _HeadNumber; }
+            set { SetProperty(ref _HeadNumber, value); }
+        }
+
         //当前的操作员名称
         private string _OperatorName;
         [SugarColumn(IsNullable = true)]
@@ -275,6 +296,17 @@ namespace TeamAAS_VP.Models
             set { SetProperty(ref _ProductImagePath, value); }
         }
 
+        private string _LockCurveImagePath;
+        /// <summary>
+        /// 锁付曲线图路径
+        /// </summary>
+        [SugarColumn(IsNullable = true)]
+        public string LockCurveImagePath
+        {
+            get { return _LockCurveImagePath; }
+            set { SetProperty(ref _LockCurveImagePath, value); }
+        }
+
         /// <summary>
         /// 锁付曲线数据列表
         /// </summary>
@@ -302,6 +334,7 @@ namespace TeamAAS_VP.Models
             return new LockResult
             {
                 Number = this.Number,
+                ProductName = this.ProductName,
                 ProductNumber = this.ProductNumber,
                 Timestamp = this.Timestamp,
                 LockTurns = this.LockTurns,
@@ -310,21 +343,24 @@ namespace TeamAAS_VP.Models
                 LockPassed = this.LockPassed,
                 ScrewdriverProgramNumber = this.ScrewdriverProgramNumber,
                 Pressure = this.Pressure,
-                TargetTorque = this.TargetTorque,
+                TargetTorqueUpperLimit = this.TargetTorqueUpperLimit,
+                TargetTorqueLowerLimit = this.TargetTorqueLowerLimit,
                 TargetTurnsUpperLimit = this.TargetTurnsUpperLimit,
                 TargetTurnsLowerLimit = this.TargetTurnsLowerLimit,
                 TargetLockSpeed = this.TargetLockSpeed,
-                StartPositionX = this.StartPositionX,
-                StartPositionY = this.StartPositionY,
+                PositionX = this.PositionX,
+                PositionY = this.PositionY,
                 StartPositionZ = this.StartPositionZ,
                 EndPositionZ = this.EndPositionZ,
                 LockDescentSpeed = this.LockDescentSpeed,
                 FeederNumber = this.FeederNumber,
                 NozzleNumber = this.NozzleNumber,
+                HeadNumber= this.HeadNumber,
                 OperatorName = this.OperatorName,
                 ProductImagePath = this.ProductImagePath,
                 ScrewdriverGetDataSucceed = this.ScrewdriverGetDataSucceed,
-                WaveDatas = new List<WaveData>(this.WaveDatas)
+                WaveDatas = new List<WaveData>(this.WaveDatas),
+                LockCurveImagePath = this.LockCurveImagePath,
             };
         }
 
@@ -353,11 +389,12 @@ namespace TeamAAS_VP.Models
             using (var writer = new System.IO.StreamWriter(filePath, false, System.Text.Encoding.UTF8))
             {
                 // 写入锁付结果信息表头(已新增字段)
-                writer.WriteLine("Number,ProductNumber,Timestamp,LockTurns,LockTorque,LockDuration,LockPassed,ScrewdriverProgramNumber,Pressure,TargetTorque,TargetTurnsUpperLimit,TargetTurnsLowerLimit,TargetLockSpeed,StartPositionX,StartPositionY,StartPositionZ,EndPositionZ,LockDescentSpeed,FeederNumber,FeederBatchNumber,NozzleNumber,ResultDetails,ScrewdriverGetDataSucceed,OperatorName,ProductImagePath");
-                
+                writer.WriteLine("Number,ProductName,ProductNumber,Timestamp,LockTurns,LockTorque,LockDuration,LockPassed,ScrewdriverProgramNumber,Pressure,TargetTorque,TargetTurnsUpperLimit,TargetTurnsLowerLimit,TargetLockSpeed,StartPositionX,StartPositionY,StartPositionZ,EndPositionZ,LockDescentSpeed,FeederNumber,FeederBatchNumber,NozzleNumber,HeadNumber,ResultDetails,ScrewdriverGetDataSucceed,OperatorName,ProductImagePath,LockCurveImagePath");
+
                 // 写入锁付结果数据行(所有字段均做 CSV 转义)
                 writer.WriteLine(string.Join(",",
                     EscapeCsv(Number),
+                    EscapeCsv(ProductName),
                     EscapeCsv(ProductNumber),
                     EscapeCsv(Timestamp),
                     EscapeCsv(LockTurns),
@@ -366,22 +403,25 @@ namespace TeamAAS_VP.Models
                     EscapeCsv(LockPassed),
                     EscapeCsv(ScrewdriverProgramNumber),
                     EscapeCsv(Pressure),
-                    EscapeCsv(TargetTorque),
+                    EscapeCsv(TargetTorqueUpperLimit),
+                    EscapeCsv(TargetTorqueLowerLimit),
                     EscapeCsv(TargetTurnsUpperLimit),
                     EscapeCsv(TargetTurnsLowerLimit),
                     EscapeCsv(TargetLockSpeed),
-                    EscapeCsv(StartPositionX),
-                    EscapeCsv(StartPositionY),
+                    EscapeCsv(PositionX),
+                    EscapeCsv(PositionY),
                     EscapeCsv(StartPositionZ),
                     EscapeCsv(EndPositionZ),
                     EscapeCsv(LockDescentSpeed),
                     EscapeCsv(FeederNumber),
                     EscapeCsv(FeederBatchNumber),
                     EscapeCsv(NozzleNumber),
+                    EscapeCsv(HeadNumber),
                     EscapeCsv(ResultDetails),
                     EscapeCsv(ScrewdriverGetDataSucceed),
                     EscapeCsv(OperatorName),
-                    EscapeCsv(ProductImagePath)
+                    EscapeCsv(ProductImagePath),
+                    EscapeCsv(LockCurveImagePath)
                 ));
 
                 // 写入波形数据
@@ -402,5 +442,25 @@ namespace TeamAAS_VP.Models
             }
         }
 
+        /// <summary>
+        /// 异步保存到csv
+        /// </summary>
+        /// <param name="filePath"></param>
+        /// <returns></returns>
+        public async System.Threading.Tasks.Task SaveToCsvAsync(string filePath)
+        {
+            await System.Threading.Tasks.Task.Run(() =>
+            {
+                try
+                {
+                    SaveToCsv(filePath);
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("保存锁付数据至CSV时出错!", ex);
+                }
+            });
+        }
+
     }
 }

+ 34 - 0
TeamAAS-VM/Models/NozzleChangeRecord.cs

@@ -0,0 +1,34 @@
+using SqlSugar;
+using System;
+
+namespace TeamAAS_VP.Models
+{
+    [SugarTable("NozzleChangeRecord")]
+    public class NozzleChangeRecord
+    {
+        [SugarColumn(IsPrimaryKey = true)]
+        public Guid Id { get; set; } = Guid.NewGuid();
+
+        /// <summary>
+        /// 更换时间
+        /// </summary>
+        public DateTime ChangeTime { get; set; } = DateTime.UtcNow;
+
+        /// <summary>
+        /// 吸嘴批号
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string NozzleBatchNumber { get; set; }
+
+        /// <summary>
+        /// 当前吸嘴锁付次数
+        /// </summary>
+        public int CurrentLockCount { get; set; }
+
+        /// <summary>
+        /// 操作员名称
+        /// </summary>
+        [SugarColumn(Length = 255, IsNullable = true)]
+        public string OperatorName { get; set; }
+    }
+}

+ 0 - 20
TeamAAS-VM/Models/NumberStatistics.cs

@@ -52,25 +52,5 @@ namespace TeamAAS_VP.Models
             get { return _Feeder2Num; }
             set { SetProperty(ref _Feeder2Num, value); }
         }
-
-        private int _NozzleAlarmValue;
-        /// <summary>
-        /// 吸嘴报警值
-        /// </summary>
-        public int NozzleAlarmValue
-        {
-            get { return _NozzleAlarmValue; }
-            set { SetProperty(ref _NozzleAlarmValue, value); }
-        }
-
-        private int _HeaderAlarmValue;
-        /// <summary>
-        /// 批头报警值
-        /// </summary>
-        public int HeaderAlarmValue
-        {
-            get { return _HeaderAlarmValue; }
-            set { SetProperty(ref _HeaderAlarmValue, value); }
-        }
     }
 }

+ 157 - 7
TeamAAS-VM/Models/PLC/PlcPoint.cs

@@ -13,6 +13,9 @@ namespace TeamAAS_VP.Models.PLC
     public class PlcPoint : BindableBase
     {
         private int _Number;
+        /// <summary>
+        /// 点位编号
+        /// </summary>
         public int Number
         {
             get { return _Number; }
@@ -20,6 +23,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private string _Label;
+        /// <summary>
+        /// 点位标签
+        /// </summary>
         public string Label
         {
             get { return _Label; }
@@ -27,6 +33,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _X_Position;
+        /// <summary>
+        /// X轴位置
+        /// </summary>
         public float X_Position
         {
             get { return _X_Position; }
@@ -34,6 +43,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _X_Velocity;
+        /// <summary>
+        /// X轴速度
+        /// </summary>
         public float X_Velocity
         {
             get { return _X_Velocity; }
@@ -41,6 +53,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _Y_Position;
+        /// <summary>
+        /// Y轴位置
+        /// </summary>
         public float Y_Position
         {
             get { return _Y_Position; }
@@ -48,6 +63,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _Y_Velocity;
+        /// <summary>
+        /// Y轴速度
+        /// </summary>
         public float Y_Velocity
         {
             get { return _Y_Velocity; }
@@ -55,6 +73,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _Z_Position_Start;
+        /// <summary>
+        /// Z轴起点位置
+        /// </summary>
         public float Z_Position_Start
         {
             get { return _Z_Position_Start; }
@@ -62,6 +83,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _Z_Velocity_Start;
+        /// <summary>
+        /// Z轴起点速度
+        /// </summary>
         public float Z_Velocity_Start
         {
             get { return _Z_Velocity_Start; }
@@ -69,6 +93,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _Z_Position_Stop;
+        /// <summary>
+        /// Z轴终点位置
+        /// </summary>
         public float Z_Position_Stop
         {
             get { return _Z_Position_Stop; }
@@ -76,6 +103,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _Z_Velocity_Stop;
+        /// <summary>
+        /// Z轴终点速度
+        /// </summary>
         public float Z_Velocity_Stop
         {
             get { return _Z_Velocity_Stop; }
@@ -83,6 +113,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _U_Position;
+        /// <summary>
+        /// U轴位置
+        /// </summary>
         public float U_Position
         {
             get { return _U_Position; }
@@ -90,6 +123,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _U_Velocity;
+        /// <summary>
+        /// U轴速度
+        /// </summary>
         public float U_Velocity
         {
             get { return _U_Velocity; }
@@ -97,6 +133,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _R_Position;
+        /// <summary>
+        /// R轴位置
+        /// </summary>
         public float R_Position
         {
             get { return _R_Position; }
@@ -104,6 +143,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _R_Velocity;
+        /// <summary>
+        /// R轴速度
+        /// </summary>
         public float R_Velocity
         {
             get { return _R_Velocity; }
@@ -111,6 +153,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private float _Torque;
+        /// <summary>
+        /// 扭矩值
+        /// </summary>
         public float Torque
         {
             get { return _Torque; }
@@ -118,6 +163,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private Int16 _Feeder;
+        /// <summary>
+        /// Feeder编号
+        /// </summary>
         public Int16 Feeder
         {
             get { return _Feeder; }
@@ -125,6 +173,9 @@ namespace TeamAAS_VP.Models.PLC
         }
 
         private Int16 _ScrewProNum;
+        /// <summary>
+        /// 电批程序号
+        /// </summary>
         public Int16 ScrewProNum
         {
             get { return _ScrewProNum; }
@@ -133,12 +184,95 @@ namespace TeamAAS_VP.Models.PLC
 
         //描述
         private string _Description;
+        /// <summary>
+        /// 点位描述
+        /// </summary>
         public string Description
         {
             get { return _Description; }
             set { SetProperty(ref _Description, value); }
         }
 
+        private Guid _VisionProcessID;
+        /// <summary>
+        /// 视觉流程ID
+        /// </summary>
+        public Guid VisionProcessID
+        {
+            get { return _VisionProcessID; }
+            set { SetProperty(ref _VisionProcessID, value); }
+        }
+
+        private string _VisionProcessName;
+        /// <summary>
+        /// 视觉流程名称
+        /// </summary>
+        public string VisionProcessName
+        {
+            get { return _VisionProcessName; }
+            set { SetProperty(ref _VisionProcessName, value); }
+        }
+
+        private float _X_Offset;
+        /// <summary>
+        /// X轴补偿值
+        /// </summary>
+        public float X_Offset
+        {
+            get { return _X_Offset; }
+            set { SetProperty(ref _X_Offset, value); }
+        }
+
+        private float _Y_Offset;
+        /// <summary>
+        /// Y轴补偿值
+        /// </summary>
+        public float Y_Offset
+        {
+            get { return _Y_Offset; }
+            set { SetProperty(ref _Y_Offset, value); }
+        }
+
+        private float _Z_Start_Offset;
+        /// <summary>
+        /// Z轴起点补偿值
+        /// </summary>
+        public float Z_Start_Offset
+        {
+            get { return _Z_Start_Offset; }
+            set { SetProperty(ref _Z_Start_Offset, value); }
+        }
+
+        private float _Z_Stop_Offset;
+        /// <summary>
+        /// Z轴终点补偿值
+        /// </summary>
+        public float Z_Stop_Offset
+        {
+            get { return _Z_Stop_Offset; }
+            set { SetProperty(ref _Z_Stop_Offset, value); }
+        }
+
+        private float _U_Offset;
+        /// <summary>
+        /// U轴补偿值
+        /// </summary>
+        public float U_Offset
+        {
+            get { return _U_Offset; }
+            set { SetProperty(ref _U_Offset, value); }
+        }
+
+        private float _R_Offset;
+        /// <summary>
+        /// R轴补偿值
+        /// </summary>
+        public float R_Offset
+        {
+            get { return _R_Offset; }
+            set { SetProperty(ref _R_Offset, value); }
+        }
+
         public PlcPoint()
         {
             Number = 0;
@@ -157,6 +291,14 @@ namespace TeamAAS_VP.Models.PLC
             Torque = 0;
             Feeder = 0;
             ScrewProNum = 0;
+            Description = string.Empty;
+            X_Offset = 0;
+            Y_Offset = 0;
+            Z_Start_Offset = 0;
+            Z_Stop_Offset = 0;
+            U_Offset = 0;
+            R_Offset = 0;
+
         }
 
         public PlcPoint Clone()
@@ -180,7 +322,15 @@ namespace TeamAAS_VP.Models.PLC
                 Torque = this.Torque,
                 Feeder = this.Feeder,
                 ScrewProNum = this.ScrewProNum,
-                Description = this.Description
+                Description = this.Description,
+                VisionProcessID = this.VisionProcessID,
+                VisionProcessName = this.VisionProcessName,
+                X_Offset = this.X_Offset,
+                Y_Offset = this.Y_Offset,
+                Z_Start_Offset = this.Z_Start_Offset,
+                Z_Stop_Offset = this.Z_Stop_Offset,
+                U_Offset = this.U_Offset,
+                R_Offset = this.R_Offset
             };
         }
 
@@ -193,17 +343,17 @@ namespace TeamAAS_VP.Models.PLC
         public async Task<bool> WriteToPlcAddress(PlcPointAddress plcAddress, OpcUaClientPLC pLC)
         {
             Dictionary<string, object> nodeValues = new Dictionary<string, object>();
-            nodeValues.Add(string.Format(plcAddress.X_Position.Address, Number), X_Position);
+            nodeValues.Add(string.Format(plcAddress.X_Position.Address, Number), X_Position + X_Offset);
             nodeValues.Add(string.Format(plcAddress.X_Velocity.Address, Number), X_Velocity);
-            nodeValues.Add(string.Format(plcAddress.Y_Position.Address, Number), Y_Position);
+            nodeValues.Add(string.Format(plcAddress.Y_Position.Address, Number), Y_Position + Y_Offset);
             nodeValues.Add(string.Format(plcAddress.Y_Velocity.Address, Number), Y_Velocity);
-            nodeValues.Add(string.Format(plcAddress.Z_Position_Start.Address, Number), Z_Position_Start);
+            nodeValues.Add(string.Format(plcAddress.Z_Position_Start.Address, Number), Z_Position_Start + Z_Start_Offset);
             nodeValues.Add(string.Format(plcAddress.Z_Velocity_Start.Address, Number), Z_Velocity_Start);
-            nodeValues.Add(string.Format(plcAddress.Z_Position_Stop.Address, Number), Z_Position_Stop);
+            nodeValues.Add(string.Format(plcAddress.Z_Position_Stop.Address, Number), Z_Position_Stop + Z_Stop_Offset);
             nodeValues.Add(string.Format(plcAddress.Z_Velocity_Stop.Address, Number), Z_Velocity_Stop);
-            nodeValues.Add(string.Format(plcAddress.U_Position.Address, Number), U_Position);
+            nodeValues.Add(string.Format(plcAddress.U_Position.Address, Number), U_Position + U_Offset);
             nodeValues.Add(string.Format(plcAddress.U_Velocity.Address, Number), U_Velocity);
-            nodeValues.Add(string.Format(plcAddress.R_Position.Address, Number), R_Position);
+            nodeValues.Add(string.Format(plcAddress.R_Position.Address, Number), R_Position + R_Offset);
             nodeValues.Add(string.Format(plcAddress.R_Velocity.Address, Number), R_Velocity);
             nodeValues.Add(string.Format(plcAddress.Torque.Address, Number), Torque);
             nodeValues.Add(string.Format(plcAddress.Feeder.Address, Number), Feeder);

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

@@ -0,0 +1,79 @@
+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 bool IsSuccess { get; set; }
+
+        /// <summary>
+        /// 机器人拍照位置
+        /// </summary>
+        public string RobotPosition { get; set; }
+
+        /// <summary>
+        /// 像素坐标
+        /// </summary>
+        public string PixelPosition { get; set; }
+
+        /// <summary>
+        /// 绝对坐标
+        /// </summary>
+        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; }
+    }
+}

+ 10 - 0
TeamAAS-VM/Models/ScrewFeederBatchRecord.cs

@@ -31,6 +31,9 @@ namespace TeamAAS_VP.Models
         [SugarColumn(Length = 255, IsNullable = true)]
         public string OperatorName { get; set; }
 
+        //添加前的螺丝供料器中螺丝数量
+        public int PreviousCount { get; set; }
+
         /// <summary>
         /// 添加后的螺丝供料器中螺丝数量
         /// </summary>
@@ -46,5 +49,12 @@ namespace TeamAAS_VP.Models
         /// </summary>
         [SugarColumn(Length = 255, IsNullable = true)]
         public string FeederName { get; set; }
+
+        /// <summary>
+        /// 备注
+        /// </summary>
+        [SugarColumn(Length = 500, IsNullable = true)]
+        public string Remarks { get; set; }
+
     }
 }

+ 20 - 0
TeamAAS-VM/Models/SystemConfiguration.cs

@@ -196,6 +196,26 @@ namespace TeamAAS_VP.Models
             set => SetProperty(ref _ScrewTeachNum, value);
         }
 
+        private bool _IsSaveScrewCurve = false;
+        /// <summary>
+        /// 是否保存锁付曲线图
+        /// </summary>
+        public bool IsSaveScrewCurve
+        {
+            get => _IsSaveScrewCurve;
+            set => SetProperty(ref _IsSaveScrewCurve, value);
+        }
+
+        private string _ScrewCurvePath = "";
+        /// <summary>
+        /// 锁付曲线图保存的文件夹路径
+        /// </summary>
+        public string ScrewCurvePath
+        {
+            get => _ScrewCurvePath;
+            set => SetProperty(ref _ScrewCurvePath, value);
+        }
+
         /// <summary>
         /// 字体大小子设置
         /// </summary>

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

@@ -915,6 +915,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
         }
         
+        /// <summary>
+        ///   查找类似 年月/日/配方名/产品SN/产品SN+时间 的本地化字符串。
+        /// </summary>
+        public static string ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time {
+            get {
+                return ResourceManager.GetString("ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   查找类似 /年月/日/NG/时间 的本地化字符串。
         /// </summary>

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

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

+ 170 - 32
TeamAAS-VM/Services/ConfigService.cs

@@ -4,10 +4,14 @@ using SqlSugar;
 using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
+using System.Globalization;
 using System.IO;
 using System.Linq;
+using System.Threading;
 using System.Threading.Tasks;
 using TeamAAS_VP.Core;
+using TeamAAS_VP.Data; // for ISystemDatabaseService (if used)
+using TeamAAS_VP.Enums;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Models.Calibration;
@@ -15,8 +19,8 @@ using TeamAAS_VP.Models.Feeder;
 using TeamAAS_VP.Models.Lights;
 using TeamAAS_VP.Models.PLC;
 using TeamAAS_VP.Models.ScrewDriver;
-using TeamAAS_VP.Data; // for ISystemDatabaseService (if used)
-using System.Threading;
+using TeamAAS_VP.Resources.Languages;
+using WPFLocalizeExtension.Engine;
 
 namespace TeamAAS_VP.Services
 {
@@ -46,7 +50,8 @@ namespace TeamAAS_VP.Services
             public static readonly string ScrewDriverConfigurationPath = "..//Config//ScrewDriverConfiguration.cfg";
             // 螺丝供料器(物料)配置路径
             public static readonly string ScrewFeedersConfigurationPath = "..//Config//ScrewFeedersConfiguration.cfg";
-
+            // 刷卡器配置路径
+            public static readonly string CardReaderConfigurationPath = "..//Config//CardReaderConfiguration.cfg";
         }
 
         private readonly object _sync = new object();
@@ -68,10 +73,13 @@ namespace TeamAAS_VP.Services
         private PlcAddressConfig PlcAddressConfig { get; set; }
         // 单个电批配置
         private TeamAAS_VP.Models.ScrewDriver.ScrewDriverConfig _screwDriverConfig;
-        public TeamAAS_VP.Models.ScrewDriver.ScrewDriverConfig ScrewDriverConfig { get { lock(_sync) { return _screwDriverConfig; } } }
+        public TeamAAS_VP.Models.ScrewDriver.ScrewDriverConfig ScrewDriverConfig { get { lock (_sync) { return _screwDriverConfig; } } }
 
         private ISystemDatabaseService _systemDatabaseService;
 
+        // 刷卡器配置
+        private SerialPortConfig _cardReaderConfig;
+
         /// <summary>
         /// 注入系统数据库服务(可选),用于记录螺丝批次变更等记录。
         /// </summary>
@@ -84,25 +92,6 @@ namespace TeamAAS_VP.Services
             }
         }
 
-        /// <summary>
-        /// 将螺丝供料器批次变更记录写入数据库(若已注入 ISystemDatabaseService)。
-        /// </summary>
-        public async System.Threading.Tasks.Task RecordScrewFeederBatchAsync(ScrewFeederBatchRecord record)
-        {
-            if (record == null) throw new ArgumentNullException(nameof(record));
-            try
-            {
-                if (_systemDatabaseService != null)
-                {
-                    await _systemDatabaseService.RecordScrewFeederBatchAsync(record);
-                }
-            }
-            catch
-            {
-                // 忽略数据库写入错误,记录可添加日志
-            }
-        }
-
         /// <summary>
         /// 初始化一个新的 <see cref="ConfigService"/> 实例。
         /// 构造函数不会自动加载配置文件(避免在构造期间进行 I/O 操作);可调用 <see cref="LoadAll"/> 或 <see cref="LoadAllAsync"/> 显式加载。
@@ -143,7 +132,7 @@ namespace TeamAAS_VP.Services
                     Feeders = new ObservableCollection<FeederInfo>();
                     FileHelper.WriteJsonFile(Feeders, ConfigPaths.FeedersConfigurationPath);
                 }
-                
+
                 // load screw feeders (material) configuration
                 if (File.Exists(ConfigPaths.ScrewFeedersConfigurationPath))
                     ScrewFeeders = FileHelper.ReadJsonFile<ObservableCollection<ScrewFeederInfo>>(ConfigPaths.ScrewFeedersConfigurationPath);
@@ -223,6 +212,16 @@ namespace TeamAAS_VP.Services
                     _deviceInfo = new DeviceInfo();
                     FileHelper.WriteJsonFile(_deviceInfo, ConfigPaths.DeviceInfoConfigurationPath);
                 }
+
+                // load card reader configuration
+                if (File.Exists(ConfigPaths.CardReaderConfigurationPath))
+                    _cardReaderConfig = FileHelper.ReadJsonFile<SerialPortConfig>(ConfigPaths.CardReaderConfigurationPath);
+                else
+                {
+                    _cardReaderConfig = new SerialPortConfig();
+                    FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
+                }
+
             }
         }
 
@@ -261,6 +260,9 @@ namespace TeamAAS_VP.Services
                 // save device info
                 if (_deviceInfo != null)
                     FileHelper.WriteJsonFile(_deviceInfo, ConfigPaths.DeviceInfoConfigurationPath);
+                // save card reader config
+                if (_cardReaderConfig != null)
+                    FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
             }
         }
 
@@ -763,6 +765,69 @@ namespace TeamAAS_VP.Services
                 FileHelper.WriteJsonFile(systemConfiguration, ConfigPaths.SystemConfigurationPath);
             }
         }
+
+        /// <summary>
+        /// 获取当前语言
+        /// </summary>
+        /// <returns></returns>
+        public Language GetCurrentLanguage()
+        {
+            lock (_sync)
+            {
+                var config = GetSystemConfiguration();
+                return config.CurrentLanguage;
+            }
+        }
+
+        /// <summary>
+        /// 设置当前语言
+        /// </summary>
+        /// <param name="language"></param>
+        public void SetCurrentLanguage(Language language)
+        {
+            lock (_sync)
+            {
+                var config = GetSystemConfiguration();
+                config.CurrentLanguage = language;
+                if (language == Enums.Language.ChineseSimplified)
+                {
+                    var culture = new CultureInfo("zh-CN");
+                    App.Current.Dispatcher.Thread.CurrentCulture = culture;
+                    App.Current.Dispatcher.Thread.CurrentUICulture = culture;
+                    LocalizeDictionary.Instance.Culture = culture;
+                    Lang.Culture = culture;
+                    System.Windows.Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Microsoft YaHei");
+                }
+                else if (language == Enums.Language.ChineseTraditional)
+                {
+                    var culture = new CultureInfo("zh-TW");
+                    App.Current.Dispatcher.Thread.CurrentCulture = culture;
+                    App.Current.Dispatcher.Thread.CurrentUICulture = culture;
+                    LocalizeDictionary.Instance.Culture = culture;
+                    Lang.Culture = culture;
+                    System.Windows.Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Microsoft YaHei");
+                }
+                else if (language == Enums.Language.English)
+                {
+                    var culture = new CultureInfo("en");
+                    App.Current.Dispatcher.Thread.CurrentCulture = culture;
+                    App.Current.Dispatcher.Thread.CurrentUICulture = culture;
+                    LocalizeDictionary.Instance.Culture = culture;
+                    Lang.Culture = culture;
+                    System.Windows.Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Segoe UI");
+                }
+                else if (language == Enums.Language.Japanese)
+                {
+                    var culture = new CultureInfo("ja-JP");
+                    App.Current.Dispatcher.Thread.CurrentCulture = culture;
+                    App.Current.Dispatcher.Thread.CurrentUICulture = culture;
+                    LocalizeDictionary.Instance.Culture = culture;
+                    Lang.Culture = culture;
+                    System.Windows.Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Segoe UI");
+                }
+                SaveSystemConfiguration(config);
+            }
+        }
         #endregion
 
         #region Feeder清料任务
@@ -1193,21 +1258,21 @@ namespace TeamAAS_VP.Services
         }
 
         /// <summary>
-        /// 为指定供料器编号递减指定数量,若数量不足返回 false
+        /// 为指定供料器编号递减指定数量,若数量不足返回 -1
         /// </summary>
-        public bool DecrementScrewCountByFeederNumber(int feederNumber, int decrement = 1)
+        public int DecrementScrewCountByFeederNumber(int feederNumber, int decrement = 1)
         {
             lock (_sync)
             {
                 var f = ScrewFeeders.FirstOrDefault(s => s.FeederNumber == feederNumber);
-                if (f == null) return false;
+                if (f == null) return -1;
                 if (decrement <= 0) decrement = 1;
-                if (f.RemainingCount < decrement) return false;
+                if (f.RemainingCount < decrement) return -1;
                 f.RemainingCount -= decrement;
                 // check alarm
                 CheckAndTriggerLowLevelAlarm(f);
                 FileHelper.WriteJsonFile(ScrewFeeders, ConfigPaths.ScrewFeedersConfigurationPath);
-                return true;
+                return f.RemainingCount;
             }
         }
 
@@ -1235,16 +1300,21 @@ namespace TeamAAS_VP.Services
         {
             if (string.IsNullOrWhiteSpace(batchNumber)) return;
 
+            //获取当前的操作员用户名
+            string operatorName = _systemDatabaseService.GetCurrentUser()?.UserName;
+
             // capture values under lock, then record to DB outside lock
             ScrewFeederInfo target = null;
             int remainingAfter = 0;
             int packSize = 0;
             string feederName = null;
+            int previousCount = 0;
             lock (_sync)
             {
                 var f = ScrewFeeders.FirstOrDefault(s => s.FeederNumber == feederNumber);
                 if (f == null) return;
                 f.BatchNumber = batchNumber;
+                previousCount = f.RemainingCount;
                 f.RemainingCount += Math.Max(0, f.PackSize);
 
                 // prepare capture values
@@ -1267,7 +1337,9 @@ namespace TeamAAS_VP.Services
                     ChangeTime = DateTime.UtcNow,
                     RemainingCount = remainingAfter,
                     FeederNumber = feederNumber,
-                    FeederName = feederName
+                    FeederName = feederName,
+                    PreviousCount = previousCount,
+                    OperatorName = operatorName,
                 };
 
                 // try get operator name from system database service if available
@@ -1282,8 +1354,17 @@ namespace TeamAAS_VP.Services
                     // ignore getting user failure
                 }
 
-                // fire-and-forget recording (ConfigService will forward to DB service if set)
-                _ = RecordScrewFeederBatchAsync(record);
+                try
+                {
+                    if (_systemDatabaseService != null)
+                    {
+                        _ = _systemDatabaseService.RecordScrewFeederBatchAsync(record);
+                    }
+                }
+                catch
+                {
+                    // 忽略数据库写入错误,记录可添加日志
+                }
             }
             catch
             {
@@ -1307,6 +1388,63 @@ namespace TeamAAS_VP.Services
         }
         #endregion
 
+        #region 用户登录刷卡器
+        /// <summary>
+        /// 获取刷卡器配置
+        /// </summary>
+        /// <returns></returns>
+        public SerialPortConfig GetCardReaderConfig()
+        {
+            lock (_sync)
+            {
+                if (_cardReaderConfig != null)
+                    return _cardReaderConfig;
+
+                if (File.Exists(ConfigPaths.CardReaderConfigurationPath))
+                {
+                    try
+                    {
+                        _cardReaderConfig = FileHelper.ReadJsonFile<SerialPortConfig>(ConfigPaths.CardReaderConfigurationPath);
+                    }
+                    catch
+                    {
+                        // 若读取失败,创建默认配置并覆盖文件(与项目中其他配置策略一致)
+                        _cardReaderConfig = new SerialPortConfig();
+                        try { FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath); } catch { }
+                    }
+                }
+                else
+                {
+                    _cardReaderConfig = new SerialPortConfig();
+                    try { FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath); } catch { }
+                }
+
+                return _cardReaderConfig;
+            }
+        }
+
+        /// <summary>
+        /// 保存刷卡器配置
+        /// </summary>
+        /// <param name="config"></param>
+        public void SaveCardReaderConfig(SerialPortConfig config)
+        {
+            if (config == null) return;
+            lock (_sync)
+            {
+                _cardReaderConfig = config;
+                try
+                {
+                    FileHelper.WriteJsonFile(_cardReaderConfig, ConfigPaths.CardReaderConfigurationPath);
+                }
+                catch
+                {
+                    // 忽略持久化错误(与项目中其它保存方法一致),可在需要时添加日志记录
+                }
+            }
+        }
+        #endregion
+
         /// <summary>
         /// 释放资源并保存当前内存中的所有配置到文件。
         /// </summary>

+ 8 - 0
TeamAAS-VM/Services/LightManagerService.cs

@@ -88,6 +88,14 @@ namespace TeamAAS_VP.Services
                 var protocol = new SerialPortProtocol(config.SerialPortConfig);
                 return new KCSLightController(id, protocol, config.ChannelCount,config);
             });
+            // 注册KCS控制器工厂
+            RegisterControllerFactory(LightModel.KCS_KDC3_24V300W_8T, (id, config) =>
+            {
+                if (config == null) throw new ArgumentNullException(nameof(config));
+                // 使用配置里的串口配置创建协议实现,再创建控制器实例
+                var protocol = new SerialPortProtocol(config.SerialPortConfig);
+                return new KCSLightController(id, protocol, config.ChannelCount, config);
+            });
         }
 
         /// <summary>

+ 144 - 73
TeamAAS-VM/Services/MesService.cs

@@ -11,23 +11,30 @@ namespace TeamAAS_VP.Services
 {
     /// <summary>
     /// 基于 <see cref="HttpClient"/> 的 MES 通信服务实现。
-    /// 该服务通过 <see cref="IConfigService"/> 获取设备配置中的 MES 接口地址,
-    /// 提供对站点查询(StationGetAsync)和提交(SubmitGetAsync)的 GET 请求封装。
+    /// <para>
+    /// 本服务通过注入的 <see cref="IConfigService"/> 获取设备配置(包含 MES 接口地址),
+    /// 提供对站点查询(StationGetAsync)和提交(SubmitGetAsync)的 GET 请求封装并带有重试逻辑。
+    /// </para>
+    /// <para>
+    /// 注意:
+    /// - <see cref="_httpClient"/> 为可复用的单一实例,建议在服务生命周期内重用以避免端口耗尽。
+    /// - 本类实现了显式的 <see cref="Dispose"/> 方法以释放内部 <see cref="HttpClient"/> 资源,调用后实例不可再用。
+    /// </para>
     /// </summary>
     public class MesService : IMesService
     {
         /// <summary>
-        /// 用于执行 HTTP 请求的客户端实例。建议在服务生命周期内重用。
+        /// 用于执行 HTTP 请求的客户端实例。建议在服务生命周期内重用,避免频繁创建导致套接字/端口耗尽。
         /// </summary>
         private readonly HttpClient _httpClient;
 
         /// <summary>
-        /// 配置服务,用于获取设备信息(包含 MES URL)。
+        /// 配置服务,用于获取设备信息(包含 MES URL、是否启用 MES 等)。
         /// </summary>
         private readonly IConfigService _configService;
 
         /// <summary>
-        /// 标记实例是否已释放,防止重复释放。
+        /// 标记实例是否已释放,防止重复释放和在释放后继续使用导致未定义行为。
         /// </summary>
         private bool _disposed;
 
@@ -43,112 +50,176 @@ namespace TeamAAS_VP.Services
             _disposed = false;
         }
 
-        /// <summary>
-        /// 根据基地址和查询参数构建完整 URL。
-        /// - 如果 <paramref name="baseUrl"/> 为空或空白,返回 null。
-        /// - 如果 <paramref name="queryParameters"/> 为空或不包含元素,返回原始 <paramref name="baseUrl"/>。
-        /// - 否则对键和值进行 URL 编码并拼接为查询字符串(以 '?' 或 '&amp;' 作为分隔)。
-        /// </summary>
-        /// <param name="baseUrl">基础 URL,例如 "http://example.com/api"。</param>
-        /// <param name="queryParameters">要附加的查询参数字典,可为 null。</param>
-        /// <returns>生成的完整 URL 字符串,或在无效 baseUrl 时返回 null。</returns>
-        private static string BuildUrl(string baseUrl, IDictionary<string, string> queryParameters)
-        {
-            if (string.IsNullOrWhiteSpace(baseUrl)) return null;
-            if (queryParameters == null || queryParameters.Count == 0) return baseUrl;
-            var sb = new StringBuilder();
-            sb.Append(baseUrl);
-            if (!baseUrl.Contains("?")) sb.Append('?');
-            else if (!baseUrl.EndsWith("?") && !baseUrl.EndsWith("&")) sb.Append('&');
-            foreach (var kv in queryParameters)
-            {
-                sb.Append(Uri.EscapeDataString(kv.Key)).Append('=').Append(Uri.EscapeDataString(kv.Value ?? string.Empty)).Append('&');
-            }
-            if (sb.Length > 0 && sb[sb.Length - 1] == '&') sb.Length--;
-            return sb.ToString();
-        }
 
         /// <summary>
         /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
-        /// 返回一个元组,<c>IsSuccess</c> 表示 HTTP 状态码是否为成功,<c>Response</c> 包含响应文本或错误信息。
         /// </summary>
-        /// <param name="queryParameters">可选的查询参数字典,将附加到 MES 站点 URL 上。</param>
-        /// <param name="cancellationToken">用于取消请求的令牌。</param>
+        /// <param name="sn">要查询的序列号(SN)。</param>
+        /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
         /// <returns>
-        /// 异步任务,结果为 (<c>IsSuccess</c>, <c>Response</c>)。
-        /// - 当缺少配置或 URL 无效时返回 (false, 错误说明)。
-        /// - 当请求被取消时返回 (false, "Canceled")。
-        /// - 其他异常返回 (false, 异常消息)。
+        /// 返回元组 (IsSuccess, Response):
+        /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
+        /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
         /// </returns>
-        public async Task<(bool IsSuccess, string Response)> StationGetAsync(IDictionary<string, string> queryParameters = null, CancellationToken cancellationToken = default)
+        /// <remarks>
+        /// 行为说明:
+        /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
+        /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
+        /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
+        /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
+        /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
+        /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
+        /// </remarks>
+        public async Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, CancellationToken cancellationToken = default)
         {
+            // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
+            if (_disposed) throw new ObjectDisposedException(nameof(MesService));
+
             var device = _configService.GetDeviceInfo();
-            if (device == null || string.IsNullOrWhiteSpace(device.MesStationUrl))
+            if (device == null || !device.EnableMES)
+            {
+                return (true, "MES功能未启用!");
+            }
+            if (string.IsNullOrWhiteSpace(device.MesStationUrl))
                 return (false, "Missing MES station URL");
 
-            var url = BuildUrl(device.MesStationUrl, queryParameters);
-            if (string.IsNullOrWhiteSpace(url)) return (false, "Invalid station URL");
+            var url = string.Format(device.MesStationUrl, sn);
 
-            try
+            (bool IsSuccess, string Response) result = (false, string.Empty);
+            for (int i = 0; i < 5; i++)
             {
-                using (var rsp = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false))
+                try
                 {
-                    var text = await rsp.Content.ReadAsStringAsync().ConfigureAwait(false);
-                    return (rsp.IsSuccessStatusCode, text);
+                    using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
+                    {
+                        var text = await rsp.Content.ReadAsStringAsync();
+                        // "SFC_OK" 代表和 MES 连接成功
+                        if (text.Contains("SFC_OK"))
+                        {
+                            if (text.Contains("unit_process_check=OK"))
+                            {
+                                return (true, text);
+                            }
+                        }
+                        result = (false, text);
+                    }
+                }
+                catch (OperationCanceledException)
+                {
+                    result = (false, "Canceled");
+                }
+                catch (Exception ex)
+                {
+                    result = (false, ex.Message);
                 }
             }
-            catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
-            {
-                return (false, "Canceled");
-            }
-            catch (Exception ex)
+            return result;
+        }
+
+        /// <summary>
+        /// 向 MES 发起站点查询请求,使用超时(秒)作为便捷重载。
+        /// </summary>
+        /// <param name="sn">序列号(SN)。</param>
+        /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
+        /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
+        public async Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, double timeoutInSeconds)
+        {
+            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
             {
-                return (false, ex.Message);
+                return await StationGetAsync(sn, cts.Token);
             }
         }
 
         /// <summary>
-        /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交数据/记录)。
-        /// 返回一个元组,<c>IsSuccess</c> 表示 HTTP 状态码是否为成功,<c>Response</c> 包含响应文本或错误信息。
+        /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
         /// </summary>
-        /// <param name="queryParameters">可选的查询参数字典,将附加到 MES 提交 URL 上。</param>
-        /// <param name="cancellationToken">用于取消请求的令牌。</param>
+        /// <param name="sn">要提交的序列号(SN)。</param>
+        /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
+        /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
+        /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
+        /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
         /// <returns>
-        /// 异步任务,结果为 (<c>IsSuccess</c>, <c>Response</c>)。
-        /// - 当缺少配置或 URL 无效时返回 (false, 错误说明)。
-        /// - 当请求被取消时返回 (false, "Canceled")。
-        /// - 其他异常返回 (false, 异常消息)。
+        /// 返回元组 (IsSuccess, Response):
+        /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
+        /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
         /// </returns>
-        public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(IDictionary<string, string> queryParameters = null, CancellationToken cancellationToken = default)
+        /// <remarks>
+        /// 行为说明:
+        /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
+        /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
+        /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
+        /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
+        /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
+        /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
+        /// </remarks>
+        public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
         {
+            // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
+            if (_disposed) throw new ObjectDisposedException(nameof(MesService));
+
             var device = _configService.GetDeviceInfo();
-            if (device == null || string.IsNullOrWhiteSpace(device.MesSubmitUrl))
+            if (device == null || !device.EnableMES)
+            {
+                return (true, "MES功能未启用!");
+            }
+            if (string.IsNullOrWhiteSpace(device.MesStationUrl))
                 return (false, "Missing MES submit URL");
 
-            var url = BuildUrl(device.MesSubmitUrl, queryParameters);
-            if (string.IsNullOrWhiteSpace(url)) return (false, "Invalid submit URL");
+            var url = string.Format(device.MesStationUrl, sn, isSuccess ? "PASS" : "FAIL", start_time.ToString("yyyy-MM-dd HH:mm:ss"), stop_time.ToString("yyyy-MM-dd HH:mm:ss"));
 
-            try
+            (bool IsSuccess, string Response) result = (false, string.Empty);
+            for (int i = 0; i < 5; i++)
             {
-                using (var rsp = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false))
+                try
                 {
-                    var text = await rsp.Content.ReadAsStringAsync().ConfigureAwait(false);
-                    return (rsp.IsSuccessStatusCode, text);
+                    using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
+                    {
+                        var text = await rsp.Content.ReadAsStringAsync();
+                        // "SFC_OK" 代表和 MES 连接成功
+                        if (text.Contains("SFC_OK"))
+                        {
+                            // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
+                            if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
+                            {
+                                return (false, text);
+                            }
+                            return (true, text);
+                        }
+                        result = (false, text);
+                    }
+                }
+                catch (OperationCanceledException)
+                {
+                    result = (false, "Canceled");
+                }
+                catch (Exception ex)
+                {
+                    result = (false, ex.Message);
                 }
             }
-            catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
-            {
-                return (false, "Canceled");
-            }
-            catch (Exception ex)
+            return result;
+        }
+
+        /// <summary>
+        /// 向 MES 提交请求的超时重载,使用超时(秒)作为便捷参数。
+        /// </summary>
+        /// <param name="sn">序列号(SN)。</param>
+        /// <param name="isSuccess">是否通过(PASS/FAIL)。</param>
+        /// <param name="start_time">开始时间。</param>
+        /// <param name="stop_time">结束时间。</param>
+        /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
+        /// <returns>与 <see cref="SubmitGetAsync(string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
+        public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, bool isSuccess, DateTime start_time, DateTime stop_time, double timeoutInSeconds)
+        {
+            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
             {
-                return (false, ex.Message);
+                return await SubmitGetAsync(sn, isSuccess, start_time, stop_time, cts.Token);
             }
         }
 
         /// <summary>
         /// 释放服务占用的托管资源(当前仅 <see cref="_httpClient"/>)。
-        /// 本方法为幂等操作,重复调用不会产生异常。
+        /// <para>本方法为幂等操作,重复调用不会产生异常。调用后实例不可再用于发起请求,尝试使用将抛出 <see cref="ObjectDisposedException"/>。</para>
         /// </summary>
         public void Dispose()
         {

+ 84 - 8
TeamAAS-VM/Services/RemoteCommandService.cs

@@ -1571,13 +1571,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);
@@ -1600,7 +1600,7 @@ namespace TeamAAS_VP.Services
                     outputCollection = null;
                     return false;
                 }
-                outImage= image;
+                outImage = image;
                 procedure.ToolBlock.Inputs["InputImage"].Value = image;
                 LogHelper.WriteLogInfo(string.Format(Lang.采集图像完成用时0ms, (DateTime.Now - nowtime).Milliseconds));
 
@@ -1638,7 +1638,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
@@ -1667,7 +1667,7 @@ namespace TeamAAS_VP.Services
         /// <param name="robotCoord"></param>
         /// <param name="cancellationToken"></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, string remark)
         {
             DateTime nowtime = DateTime.Now;
             await SetLightBeforePhoto(procedure);
@@ -1689,6 +1689,7 @@ namespace TeamAAS_VP.Services
                     if (!outputCollection.Contains("Found"))
                     {
                         SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
+                        await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, remark);
                         return (false, 0, 0, 0);
                     }
 
@@ -1717,16 +1718,20 @@ namespace TeamAAS_VP.Services
                     var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
                     if (!calibResult.IsSucceed)
                     {
+                        await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { 0, 0, 0 }, string.Empty, remark);
                         return (false, 0, 0, 0);
                     }
+                    await RecordPhotoCaptureAsync(procedure, robotCoord,true, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { calibResult.X, calibResult.Y, calibResult.U }, string.Empty, remark);
                     return (true, calibResult.X, calibResult.Y, calibResult.U);
                 }
                 SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
+                await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, remark);
                 return (false, 0, 0, 0);
             }
             catch (Exception ex)
             {
                 LogHelper.WriteLogError(Lang.执行相机取图并获取单点位时出错, ex);
+                await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, remark);
                 return (false, 0, 0, 0);
             }
             finally
@@ -1736,6 +1741,77 @@ 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="emarks"></param>
+        /// <returns></returns>
+        private async Task RecordPhotoCaptureAsync(ProcedureModel procedure, double[] robotCoord, bool isSuccess, double[] pixelPosition, double[] absolutePosition, string imagePath, 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>
@@ -1748,8 +1824,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
             {
                 //拍照失败时,需要多次拍照
@@ -2243,7 +2319,7 @@ namespace TeamAAS_VP.Services
                     if (!isSucceed)
                     {
                         LogHelper.WriteLogInfo(string.Format(Lang.设置光源通道0打开失败, lightChannel.GlobalIndex));
-                            //"设置光源通道{lightChannel.GlobalIndex}打开失败!");
+                        //"设置光源通道{lightChannel.GlobalIndex}打开失败!");
                     }
                     isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(lightChannel.GlobalIndex, lightChannel.DefaultBrightness);
                     if (!isSucceed)

+ 39 - 3
TeamAAS-VM/TeamAAS-VP.csproj

@@ -534,8 +534,11 @@
     <Compile Include="Interfaces\IMesService.cs" />
     <Compile Include="Models\DeviceInfo.cs" />
     <Compile Include="Models\Feeder\ScrewFeederInfo.cs" />
+    <Compile Include="Models\HeadChangeRecord.cs" />
+    <Compile Include="Models\NozzleChangeRecord.cs" />
     <Compile Include="Models\NumberStatistics.cs" />
     <Compile Include="Models\Torque\PlcPoint_Torque.cs" />
+    <Compile Include="Models\PhotoCaptureRecord.cs" />
     <Compile Include="Models\ScrewFeederBatchRecord.cs" />
     <Compile Include="Models\TorqueTest.cs" />
     <Compile Include="Models\Torque\Torque_TaskStatus.cs" />
@@ -546,6 +549,11 @@
       <DependentUpon>Lang.resx</DependentUpon>
     </Compile>
     <Compile Include="Services\MesService.cs" />
+    <Compile Include="ViewModels\Product\PlcPointOffserParamsViewModel.cs" />
+    <Compile Include="ViewModels\User\CardLoginWindowViewModel.cs" />
+    <Compile Include="ViewModels\Home\ChangeNozzleViewModel.cs" />
+    <Compile Include="ViewModels\Home\ChangeHeaderViewModel.cs" />
+    <Compile Include="ViewModels\Home\AddScrewViewModel.cs" />
     <Compile Include="Services\TorqueService.cs" />
     <Compile Include="ViewModels\Home\SetAlarmValueViewModel.cs" />
     <Compile Include="ViewModels\Home\TorqueCheckViewModel.cs" />
@@ -941,8 +949,14 @@
     <Compile Include="Views\DebugView.xaml.cs">
       <DependentUpon>DebugView.xaml</DependentUpon>
     </Compile>
-    <Compile Include="Views\Home\SetAlarmValue.xaml.cs">
-      <DependentUpon>SetAlarmValue.xaml</DependentUpon>
+    <Compile Include="Views\Home\AddScrew.xaml.cs">
+      <DependentUpon>AddScrew.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Home\ChangeHeader.xaml.cs">
+      <DependentUpon>ChangeHeader.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Home\ChangeNozzle.xaml.cs">
+      <DependentUpon>ChangeNozzle.xaml</DependentUpon>
     </Compile>
     <Compile Include="Views\Home\ShowVisionRender.xaml.cs">
       <DependentUpon>ShowVisionRender.xaml</DependentUpon>
@@ -989,6 +1003,9 @@
     <Compile Include="Views\Product\PalletManage.xaml.cs">
       <DependentUpon>PalletManage.xaml</DependentUpon>
     </Compile>
+    <Compile Include="Views\Product\PlcPointOffserParams.xaml.cs">
+      <DependentUpon>PlcPointOffserParams.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Views\Product\PlcPointParams.xaml.cs">
       <DependentUpon>PlcPointParams.xaml</DependentUpon>
     </Compile>
@@ -1076,6 +1093,9 @@
     <Compile Include="Views\UserView.xaml.cs">
       <DependentUpon>UserView.xaml</DependentUpon>
     </Compile>
+    <Compile Include="Views\User\CardLoginWindow.xaml.cs">
+      <DependentUpon>CardLoginWindow.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Views\User\LoginView.xaml.cs">
       <DependentUpon>LoginView.xaml</DependentUpon>
     </Compile>
@@ -1263,7 +1283,15 @@
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
-    <Page Include="Views\Home\SetAlarmValue.xaml">
+    <Page Include="Views\Home\AddScrew.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Home\ChangeHeader.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Home\ChangeNozzle.xaml">
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
@@ -1347,6 +1375,10 @@
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
+    <Page Include="Views\Product\PlcPointOffserParams.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
     <Page Include="Views\Product\PlcPointParams.xaml">
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
@@ -1463,6 +1495,10 @@
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
+    <Page Include="Views\User\CardLoginWindow.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
     <Page Include="Views\User\LoginView.xaml">
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>

+ 199 - 0
TeamAAS-VM/ViewModels/Home/AddScrewViewModel.cs

@@ -0,0 +1,199 @@
+using Prism.Commands;
+using Prism.Ioc;
+using Prism.Mvvm;
+using Prism.Services.Dialogs;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Models.Feeder;
+
+namespace TeamAAS_VP.ViewModels.Home
+{
+    public class AddScrewViewModel : BindableBase, IDialogAware
+    {
+        private readonly IConfigService _configService;
+        private readonly ISystemDatabaseService _systemDatabaseService;
+        IContainerProvider _container;
+
+        public AddScrewViewModel(IConfigService configService, ISystemDatabaseService systemDatabaseService, IContainerProvider containerProvider)
+        {
+            _configService = configService;
+            _systemDatabaseService = systemDatabaseService;
+            _container = containerProvider;
+
+            ScrewFeeders = new ObservableCollection<ScrewFeederInfo>();
+            AddCommand = new DelegateCommand(ExecuteAddCommand, CanExecuteAdd).ObservesProperty(() => SelectedFeeder).ObservesProperty(() => NewBatchNumber);
+            ClearCommand = new DelegateCommand(ExecuteClearCommand, () => SelectedFeeder != null).ObservesProperty(() => SelectedFeeder);
+            CloseCommand = new DelegateCommand(ExecuteCloseCommand);
+        }
+
+        public DelegateCommand AddCommand { get; }
+        public DelegateCommand ClearCommand { get; }
+        public DelegateCommand CloseCommand { get; }
+
+        private DelegateCommand _FeederSelectedCommand;
+        public DelegateCommand FeederSelectedCommand =>
+            _FeederSelectedCommand ?? (_FeederSelectedCommand = new DelegateCommand(ExecuteFeederSelectedCommand));
+
+        public ObservableCollection<ScrewFeederInfo> ScrewFeeders { get; }
+
+        private ScrewFeederInfo _selectedFeeder;
+        public ScrewFeederInfo SelectedFeeder
+        {
+            get => _selectedFeeder;
+            set
+            {
+                SetProperty(ref _selectedFeeder, value);
+            }
+        }
+
+        private string _newBatchNumber;
+        public string NewBatchNumber { get => _newBatchNumber; set => SetProperty(ref _newBatchNumber, value); }
+
+        private string _currentBatchNumber;
+        public string CurrentBatchNumber { get => _currentBatchNumber; set => SetProperty(ref _currentBatchNumber, value); }
+
+        private int _remainingCount;
+        public int RemainingCount { get => _remainingCount; set => SetProperty(ref _remainingCount, value); }
+
+        private string _lastAddTime;
+        public string LastAddTime { get => _lastAddTime; set => SetProperty(ref _lastAddTime, value); }
+
+        public string Title => "添加螺丝";
+
+        public event Action<IDialogResult> RequestClose;
+
+        public bool CanCloseDialog()
+        {
+            return true;
+        }
+
+        public void OnDialogClosed()
+        {
+            
+        }
+
+        public void OnDialogOpened(IDialogParameters parameters)
+        {
+            // load screw feeders
+            try
+            {
+                var list = _configService.GetAllScrewFeeders();
+                if (list != null)
+                {
+                    ScrewFeeders.Clear();
+                    foreach (var s in list)
+                    {
+                        ScrewFeeders.Add(s);
+                    }
+                }
+            }
+            catch { }
+        }
+
+        void ExecuteFeederSelectedCommand()
+        {
+            UpdateSelectedFeederInfo();
+        }
+
+        private async void UpdateSelectedFeederInfo()
+        {
+            if (SelectedFeeder != null)
+            {
+                CurrentBatchNumber = SelectedFeeder.BatchNumber;
+                RemainingCount = SelectedFeeder.RemainingCount;
+                //获取最后一次的螺丝添加时间,这里简单设置为未知,实际应用中可从数据库记录中获取
+                var latestRecord = await _systemDatabaseService.GetLatestScrewFeederBatchRecordAsync(SelectedFeeder.FeederNumber);
+                if (latestRecord != null)
+                {
+                    LastAddTime = latestRecord.ChangeTime.ToString("u");
+                }
+                else
+                    LastAddTime = "(unknown)"; // could be enriched from DB records
+            }
+            else
+            {
+                CurrentBatchNumber = string.Empty;
+                RemainingCount = 0;
+                LastAddTime = string.Empty;
+            }
+        }
+
+        private bool CanExecuteAdd()
+        {
+            return SelectedFeeder != null && !string.IsNullOrWhiteSpace(NewBatchNumber);
+        }
+
+        private async void ExecuteAddCommand()
+        {
+            if (SelectedFeeder == null) return;
+            // set batch and add pack size
+            _configService.SetBatchForFeederNumber(SelectedFeeder.FeederNumber, NewBatchNumber);
+            // refresh
+            var refreshed = _configService.GetScrewFeeder(SelectedFeeder.Id);
+            if (refreshed != null)
+            {
+                SelectedFeeder.RemainingCount = refreshed.RemainingCount;
+                SelectedFeeder.BatchNumber = refreshed.BatchNumber;
+                CurrentBatchNumber = refreshed.BatchNumber;
+                RemainingCount = refreshed.RemainingCount;
+                LastAddTime = DateTime.UtcNow.ToString("u");
+            }
+            Management management = _container.Resolve<Management>();
+            if (SelectedFeeder.FeederNumber == 1)
+                management.NumStatistics.Feeder1Num = refreshed.RemainingCount;
+            else if (SelectedFeeder.FeederNumber == 2)
+                management.NumStatistics.Feeder2Num = refreshed.RemainingCount;
+
+            // try to record batch change to system DB asynchronously
+            try
+            {
+                var rec = new ScrewFeederBatchRecord
+                {
+                    BatchNumber = NewBatchNumber,
+                    PackSize = SelectedFeeder.PackSize,
+                    ChangeTime = DateTime.UtcNow,
+                    RemainingCount = SelectedFeeder.RemainingCount,
+                    FeederNumber = SelectedFeeder.FeederNumber,
+                    FeederName = SelectedFeeder.Name,
+                    PreviousCount = SelectedFeeder.RemainingCount - SelectedFeeder.PackSize,
+                    OperatorName = _systemDatabaseService.GetCurrentUser()?.UserName
+                };
+                await _systemDatabaseService.RecordScrewFeederBatchAsync(rec);
+            }
+            catch(Exception ex)
+            {
+                LogHelper.WriteLogError("Failed to record screw feeder batch change.", ex);
+            }
+        }
+
+        private void ExecuteClearCommand()
+        {
+            if (SelectedFeeder == null) return;
+            _configService.ClearScrewFeederByNumber(SelectedFeeder.FeederNumber);
+            var refreshed = _configService.GetScrewFeeder(SelectedFeeder.Id);
+            if (refreshed != null)
+            {
+                SelectedFeeder.RemainingCount = refreshed.RemainingCount;
+                SelectedFeeder.BatchNumber = refreshed.BatchNumber;
+                CurrentBatchNumber = refreshed.BatchNumber;
+                RemainingCount = refreshed.RemainingCount;
+                LastAddTime = DateTime.UtcNow.ToString("u");
+            }
+            Management management = _container.Resolve<Management>();
+            if (SelectedFeeder.FeederNumber==1)
+                management.NumStatistics.Feeder1Num = 0;
+            else if (SelectedFeeder.FeederNumber == 2)
+                management.NumStatistics.Feeder2Num = 0;
+        }
+
+        private void ExecuteCloseCommand()
+        {
+            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
+        }
+    }
+}

+ 101 - 0
TeamAAS-VM/ViewModels/Home/ChangeHeaderViewModel.cs

@@ -0,0 +1,101 @@
+using Prism.Commands;
+using Prism.Ioc;
+using Prism.Mvvm;
+using Prism.Services.Dialogs;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.ViewModels.Home
+{
+    public class ChangeHeaderViewModel : BindableBase, IDialogAware
+    {
+        ISystemDatabaseService _systemDatabaseService;
+        IContainerProvider _container;
+
+        private string _currentHeadBatchNumber;
+        private int _currentLockCount;
+        private string _lastChangeTime;
+        private string _newHeadBatchNumber;
+
+        public ChangeHeaderViewModel(ISystemDatabaseService systemDatabaseService, IContainerProvider containerProvider)
+        {
+            _systemDatabaseService = systemDatabaseService;
+            _container = containerProvider;
+            ReplaceCommand = new DelegateCommand(ExecuteReplaceCommand, ()=>string.IsNullOrEmpty(NewHeadBatchNumber)).ObservesProperty(() => NewHeadBatchNumber);
+            CloseCommand = new DelegateCommand(ExecuteCloseCommand);
+        }
+
+        public DelegateCommand ReplaceCommand { get; }
+        public DelegateCommand CloseCommand { get; }
+
+        public string CurrentHeadBatchNumber { get => _currentHeadBatchNumber; set => SetProperty(ref _currentHeadBatchNumber, value); }
+        public int CurrentLockCount { get => _currentLockCount; set => SetProperty(ref _currentLockCount, value); }
+        public string LastChangeTime { get => _lastChangeTime; set => SetProperty(ref _lastChangeTime, value); }
+        public string NewHeadBatchNumber { get => _newHeadBatchNumber; set => SetProperty(ref _newHeadBatchNumber, value); }
+
+        public string Title => "更换披头";
+
+        public event Action<IDialogResult> RequestClose;
+
+        public bool CanCloseDialog()
+        {
+            return true;
+        }
+
+        public void OnDialogClosed()
+        {
+            
+        }
+
+        public async void OnDialogOpened(IDialogParameters parameters)
+        {
+            var latestRecord = await _systemDatabaseService.GetLatestHeadChangeRecordAsync();
+            if (latestRecord != null)
+            {
+                CurrentHeadBatchNumber = latestRecord.HeadBatchNumber;
+                CurrentLockCount = latestRecord.CurrentLockCount;
+                LastChangeTime = latestRecord.ChangeTime.ToString("yyyy-MM-dd HH:mm:ss");
+            }
+        }
+
+        private void ExecuteCloseCommand()
+        {
+            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel, null));
+        }
+
+        private async void ExecuteReplaceCommand()
+        {
+            try
+            {
+                //当前用户
+                var currentUser = await _systemDatabaseService.GetCurrentUserAsync();
+                //当前用户名
+                string operatorName = currentUser != null ? currentUser.UserName : "未知用户";
+
+                await _systemDatabaseService.RecordHeadChangeAsync(new HeadChangeRecord()
+                {
+                    HeadBatchNumber = NewHeadBatchNumber,
+                    ChangeTime = DateTime.Now,
+                    CurrentLockCount = 0,
+                    OperatorName = operatorName
+                });
+                Management management= _container.Resolve<Management>();
+                management.NumStatistics.HeaderNum = 0;
+
+                RequestClose?.Invoke(new DialogResult(ButtonResult.OK, null));
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("更换披头时出错!", ex);
+                MessageBox.Show("更换披头时出错!"+ex.Message, "AAS", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+
+        }
+    }
+}

+ 100 - 0
TeamAAS-VM/ViewModels/Home/ChangeNozzleViewModel.cs

@@ -0,0 +1,100 @@
+using Prism.Commands;
+using Prism.Ioc;
+using Prism.Mvvm;
+using Prism.Services.Dialogs;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.ViewModels.Home
+{
+    public class ChangeNozzleViewModel : BindableBase, IDialogAware
+    {
+        ISystemDatabaseService _systemDatabaseService;
+        IContainerProvider _container;
+
+        private string _currentNozzleBatchNumber;
+        private int _currentLockCount;
+        private string _lastChangeTime;
+        private string _newNozzleBatchNumber;
+
+        public ChangeNozzleViewModel(ISystemDatabaseService systemDatabaseService, IContainerProvider containerProvider)
+        {
+            _systemDatabaseService = systemDatabaseService;
+            _container = containerProvider;
+            ReplaceCommand = new DelegateCommand(ExecuteReplaceCommand, () => string.IsNullOrEmpty(NewNozzleBatchNumber)).ObservesProperty(() => NewNozzleBatchNumber);
+            CloseCommand = new DelegateCommand(ExecuteCloseCommand);
+        }
+
+        public string Title => "更换吸嘴";
+
+        public event Action<IDialogResult> RequestClose;
+
+        public bool CanCloseDialog()
+        {
+            return true;
+        }
+
+        public void OnDialogClosed()
+        {
+
+        }
+
+        public async void OnDialogOpened(IDialogParameters parameters)
+        {
+            var latestRecord = await _systemDatabaseService.GetLatestNozzleChangeRecordAsync();
+            if (latestRecord != null)
+            {
+                CurrentNozzleBatchNumber = latestRecord.NozzleBatchNumber;
+                CurrentLockCount = latestRecord.CurrentLockCount;
+                LastChangeTime = latestRecord.ChangeTime.ToString("yyyy-MM-dd HH:mm:ss");
+            }
+        }
+
+        public DelegateCommand ReplaceCommand { get; }
+        public DelegateCommand CloseCommand { get; }
+
+        public string CurrentNozzleBatchNumber { get => _currentNozzleBatchNumber; set => SetProperty(ref _currentNozzleBatchNumber, value); }
+        public int CurrentLockCount { get => _currentLockCount; set => SetProperty(ref _currentLockCount, value); }
+        public string LastChangeTime { get => _lastChangeTime; set => SetProperty(ref _lastChangeTime, value); }
+        public string NewNozzleBatchNumber { get => _newNozzleBatchNumber; set => SetProperty(ref _newNozzleBatchNumber, value); }
+
+
+        private async void ExecuteReplaceCommand()
+        {
+            try
+            {
+                //当前用户
+                var currentUser = await _systemDatabaseService.GetCurrentUserAsync();
+                //当前用户名
+                string operatorName = currentUser != null ? currentUser.UserName : "未知用户";
+
+                await _systemDatabaseService.RecordNozzleChangeAsync(new NozzleChangeRecord()
+                {
+                    NozzleBatchNumber = NewNozzleBatchNumber,
+                    ChangeTime = DateTime.Now,
+                    CurrentLockCount = 0,
+                    OperatorName = operatorName
+                });
+                Management management = _container.Resolve<Management>();
+                management.NumStatistics.NozzleNum = 0;
+                RequestClose?.Invoke(new DialogResult(ButtonResult.OK, null));
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("更换吸嘴时出错!", ex);
+                MessageBox.Show("更换吸嘴时出错!" + ex.Message, "AAS", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+        }
+
+        private void ExecuteCloseCommand()
+        {
+            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel, null));
+        }
+    }
+}

+ 0 - 99
TeamAAS-VM/ViewModels/Home/SetAlarmValueViewModel.cs

@@ -1,99 +0,0 @@
-using Prism.Commands;
-using Prism.Mvvm;
-using Prism.Services.Dialogs;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using TeamAAS_VP.Core;
-using TeamAAS_VP.Models;
-
-namespace TeamAAS_VP.ViewModels.Home
-{
-    public class SetAlarmValueViewModel : BindableBase, IDialogAware
-    {
-        #region 属性
-        private int _BitAlarmValue;
-        public int BitAlarmValue
-        {
-            get { return _BitAlarmValue; }
-            set { SetProperty(ref _BitAlarmValue, value); }
-        }
-
-        private int _NozzleAlarmValue;
-        public int NozzleAlarmValue
-        {
-            get { return _NozzleAlarmValue; }
-            set { SetProperty(ref _NozzleAlarmValue, value); }
-        }
-
-        private NumberStatistics _NumStatistics = new NumberStatistics();
-        /// <summary>
-        /// 数量(批头、吸嘴、供料器)
-        /// </summary>
-        public NumberStatistics NumStatistics
-        {
-            get { return _NumStatistics; }
-            set { SetProperty(ref _NumStatistics, value); }
-        }
-        #endregion
-
-        #region 命令
-        private DelegateCommand _ConfirmCommand;
-        public DelegateCommand ConfirmCommand =>
-            _ConfirmCommand ?? (_ConfirmCommand = new DelegateCommand(ExecuteConfirmCommand));
-
-        private DelegateCommand _CancelCommand;
-        public DelegateCommand CancelCommand =>
-            _CancelCommand ?? (_CancelCommand = new DelegateCommand(ExecuteCancelCommand));
-
-        #endregion
-
-        void ExecuteCancelCommand()
-        {
-            IDialogParameters parameters = new DialogParameters();
-            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel, parameters));
-        }
-        void ExecuteConfirmCommand()
-        {
-            NumStatistics.NozzleAlarmValue = NozzleAlarmValue;
-            NumStatistics.HeaderAlarmValue = BitAlarmValue;
-            FileHelper.WriteJsonFile(NumStatistics, FilePath.NumberStatisticsPath);
-            IDialogParameters parameters = new DialogParameters();
-            RequestClose?.Invoke(new DialogResult(ButtonResult.OK, parameters));
-        }
-
-
-        public string Title => "Set Bit/Nozzle Alarm Value";
-
-        public event Action<IDialogResult> RequestClose;
-
-        public bool CanCloseDialog()
-        {
-            return true;
-        }
-
-        public void OnDialogClosed()
-        {
-            
-        }
-
-        public void OnDialogOpened(IDialogParameters parameters)
-        {
-            try
-            {
-                var res = FileHelper.ReadJsonFile<NumberStatistics>(FilePath.NumberStatisticsPath);
-                if (res != null)
-                {
-                    BitAlarmValue = res.HeaderAlarmValue;
-                    NozzleAlarmValue = res.NozzleAlarmValue;
-                }
-            }
-            catch (Exception)
-            {
-
-            }
-        }
-    }
-}

+ 94 - 42
TeamAAS-VM/ViewModels/HomeViewModel.cs

@@ -181,10 +181,22 @@ namespace TeamAAS_VP.ViewModels
         public DelegateCommand TorqueInspectionCommand =>
             _TorqueInspectionCommand ?? (_TorqueInspectionCommand = new DelegateCommand(ExecuteTorqueInspectionCommand));
 
-        private DelegateCommand _NozzleCounterResetCommand;
-        public DelegateCommand NozzleCounterResetCommand =>
-            _NozzleCounterResetCommand ?? (_NozzleCounterResetCommand = new DelegateCommand(ExecuteNozzleCounterResetCommand));
-
+        //更换吸嘴
+        private DelegateCommand _ChangeNozzleCommand;
+        public DelegateCommand ChangeNozzleCommand =>
+            _ChangeNozzleCommand ?? (_ChangeNozzleCommand = new DelegateCommand(ExecuteChangeNozzleCommand));
+
+        //更换披头
+        private DelegateCommand _ChangeHeaderCommand;
+        public DelegateCommand ChangeHeaderCommand =>
+            _ChangeHeaderCommand ?? (_ChangeHeaderCommand = new DelegateCommand(ExecuteChangeHeaderCommand));
+
+        //添加螺丝
+        private DelegateCommand _AddScrewCommand;
+        public DelegateCommand AddScrewCommand =>
+            _AddScrewCommand ?? (_AddScrewCommand = new DelegateCommand(ExecuteAddScrewCommand));
+
+        
         private DelegateCommand _SetAlarmValueCommand;
         public DelegateCommand SetAlarmValueCommand =>
             _SetAlarmValueCommand ?? (_SetAlarmValueCommand = new DelegateCommand(ExecuteSetAlarmValueCommand));
@@ -287,20 +299,6 @@ namespace TeamAAS_VP.ViewModels
             Clipboard.SetText(textToCopy);
         }
 
-        void ExecuteTorqueInspectionCommand()
-        {
-            _dialogService.ShowDialog("TorqueCheck", rst =>
-            {
-                //对话框关闭之后的回调函数,可以在这解析结果。
-                ButtonResult result1 = rst.Result;
-
-                if (result1 == ButtonResult.OK)
-                {
-                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
-                }
-            });
-        }
-
         /// <summary>
         /// 添加消息至消息队列
         /// </summary>
@@ -420,7 +418,9 @@ namespace TeamAAS_VP.ViewModels
             }
         }
 
-        //初始化曲线图
+        /// <summary>
+        /// 初始化曲线图
+        /// </summary>
         private void InitLockCurvePlotModel()
         {
             var model = new PlotModel { Title = Lang.锁付曲线, TitleFontSize = 16};
@@ -483,40 +483,84 @@ namespace TeamAAS_VP.ViewModels
 
             //更新曲线图
             App.Current.Dispatcher.BeginInvoke(new Action(() => {
-                var series = LockCurvePlotModel.Series[0] as LineSeries;
-                //var yaxis = LockCurvePlotModel.Axes.FirstOrDefault(p=>p.Key=="Y");
-                //yaxis.Maximum = result.TargetTorque;
-                series.Points.Clear();
-                foreach (var waveData in result.WaveDatas)
+                try
                 {
-                    series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
+                    var series = LockCurvePlotModel.Series[0] as LineSeries;
+                    //var yaxis = LockCurvePlotModel.Axes.FirstOrDefault(p=>p.Key=="Y");
+                    //yaxis.Maximum = result.TargetTorque;
+                    series.Points.Clear();
+                    foreach (var waveData in result.WaveDatas)
+                    {
+                        series.Points.Add(new OxyPlot.DataPoint(waveData.LockAngle, waveData.Torque));
+                    }
+                    LockCurvePlotModel.InvalidatePlot(true);
+                    if (!string.IsNullOrEmpty(result.LockCurveImagePath))
+                    {
+                        PngExporter.Export(LockCurvePlotModel, result.LockCurveImagePath, (int)LockCurvePlotModel.Width, (int)LockCurvePlotModel.Height);
+                    }
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("更新曲线图和保存曲线图时出错!", ex);
                 }
-                LockCurvePlotModel.InvalidatePlot(true);
             }));
 
         }
-        private void SaveAsPng(PlotModel LockCurvePlotModel)
+
+        /// <summary>
+        /// 添加螺丝
+        /// </summary>
+        private void ExecuteAddScrewCommand()
         {
-            string savePath = $"E:\\Data\\螺丝锁付曲线图\\{DateTime.Now:yyyyMMdd_HHmmss}.png";
+            _dialogService.ShowDialog("AddScrew", rst =>
+            {
+                //对话框关闭之后的回调函数,可以在这解析结果。
+                ButtonResult result1 = rst.Result;
 
-            Application.Current.Dispatcher.Invoke(() =>
+                if (result1 == ButtonResult.OK)
+                {
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
+                }
+            });
+        }
+
+        /// <summary>
+        /// 更换披头
+        /// </summary>
+        void ExecuteChangeHeaderCommand()
+        {
+            _dialogService.ShowDialog("ChangeHeader", rst =>
             {
-                try
+                //对话框关闭之后的回调函数,可以在这解析结果。
+                ButtonResult result1 = rst.Result;
+
+                if (result1 == ButtonResult.OK)
                 {
-                    var exporter = new PngExporter { Width = 1200, Height = 800 };
-                    exporter.ExportToFile(LockCurvePlotModel, savePath);
-                    //SaveStatus = $"已保存到:{savePath}";
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
                 }
-                catch (Exception ex)
+            });
+        }
+
+        /// <summary>
+        /// 更换吸嘴
+        /// </summary>
+        void ExecuteChangeNozzleCommand()
+        {
+            _dialogService.ShowDialog("ChangeNozzle", rst =>
+            {
+                //对话框关闭之后的回调函数,可以在这解析结果。
+                ButtonResult result1 = rst.Result;
+
+                if (result1 == ButtonResult.OK)
                 {
-                    //SaveStatus = $"保存失败:{ex.Message}";
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
                 }
             });
         }
 
-        void ExecuteSetAlarmValueCommand()
+        void ExecuteTorqueInspectionCommand()
         {
-            _dialogService.ShowDialog("SetAlarmValue", rst =>
+            _dialogService.ShowDialog("TorqueCheck", rst =>
             {
                 //对话框关闭之后的回调函数,可以在这解析结果。
                 ButtonResult result1 = rst.Result;
@@ -527,13 +571,21 @@ namespace TeamAAS_VP.ViewModels
                 }
             });
         }
-        void ExecuteNozzleCounterResetCommand()
+
+        void ExecuteSetAlarmValueCommand()
         {
-            management.NumStatistics.NozzleNum = 0;
-            management.NumStatistics.HeaderNum = 0;
-            FileHelper.WriteJsonFile(management.NumStatistics, FilePath.NumberStatisticsPath);
-            _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
+            _dialogService.ShowDialog("SetAlarmValue", rst =>
+            {
+                //对话框关闭之后的回调函数,可以在这解析结果。
+                ButtonResult result1 = rst.Result;
+
+                if (result1 == ButtonResult.OK)
+                {
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
+                }
+            });
         }
+
         #endregion
 
         #region 继承

+ 12 - 53
TeamAAS-VM/ViewModels/MainWindowViewModel.cs

@@ -150,14 +150,7 @@ namespace TeamAAS_VP.ViewModels
             LoadedCommand = new DelegateCommand(OnLoad);
             ClosedCommand = new DelegateCommand(OnClose);
             Status = management.Status;
-            try
-            {
-                _databaseInitializer.InitializeDatabase();
-            }
-            catch (Exception ex)
-            {
-                LogHelper.WriteLogError("Database initialization failed during application startup", ex);
-            }
+            
 
 
         }
@@ -220,11 +213,6 @@ namespace TeamAAS_VP.ViewModels
 
         private async void OnLoad()
         {
-            // 1. 读取配置参数
-            _configService.LoadAll();
-            // 2. 加载校准
-            _calibrationService.LoadAll();
-
             // 设置标题和版本号
             var systemconfig = _configService.GetSystemConfiguration();
             MyTitle = systemconfig.Title;
@@ -235,45 +223,10 @@ namespace TeamAAS_VP.ViewModels
 
 
             // 设置语言
-            #region 设置语言
-            var currentlanguage = _configService.GetSystemConfiguration().CurrentLanguage;
-            if (currentlanguage == Enums.Language.ChineseSimplified)
-            {
-                var culture = new CultureInfo("zh-CN");
-                App.Current.Dispatcher.Thread.CurrentCulture = culture;
-                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
-                LocalizeDictionary.Instance.Culture = culture;
-                Lang.Culture = culture;
-                Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Microsoft YaHei");
-            }
-            else if (currentlanguage == Enums.Language.ChineseTraditional)
-            {
-                var culture = new CultureInfo("zh-TW");
-                App.Current.Dispatcher.Thread.CurrentCulture = culture;
-                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
-                LocalizeDictionary.Instance.Culture = culture;
-                Lang.Culture = culture;
-                Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Microsoft YaHei");
-            }
-            else if (currentlanguage == Enums.Language.English)
-            {
-                var culture = new CultureInfo("en");
-                App.Current.Dispatcher.Thread.CurrentCulture = culture;
-                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
-                LocalizeDictionary.Instance.Culture = culture;
-                Lang.Culture = culture;
-                Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Segoe UI");
-            }
-            else if (currentlanguage == Enums.Language.Japanese)
-            {
-                var culture = new CultureInfo("ja-JP");
-                App.Current.Dispatcher.Thread.CurrentCulture = culture;
-                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
-                LocalizeDictionary.Instance.Culture = culture;
-                Lang.Culture = culture;
-                Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Segoe UI");
-            }
-            #endregion
+            //#region 设置语言
+            //var currentlanguage = _configService.GetSystemConfiguration().CurrentLanguage;
+            //_configService.SetCurrentLanguage(currentlanguage);
+            //#endregion
 
             SendTaskMessage(Lang.软件启动, MessageLevel.Info);
             StartTime = DateTime.Now;
@@ -290,6 +243,9 @@ namespace TeamAAS_VP.ViewModels
                 _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.初始化数据库}...", Value = curvalue });
             }));
 
+            // 2. 加载校准
+            _calibrationService.LoadAll();
+
             //-------------------SETP 1: 初始化数据库-----------------------------------------------------------------------
             await Task.Delay(200);
             //初始化数据库
@@ -297,6 +253,9 @@ namespace TeamAAS_VP.ViewModels
             SendTaskMessage($"{Lang.数据库读取完成}!", MessageLevel.Info);
             curvalue += 1;
 
+            //
+            await management.ReadConfig();
+
             //-------------------SETP 2: 初始化Feeder-----------------------------------------------------------------------
             curvalue += 1;
             _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
@@ -386,7 +345,7 @@ namespace TeamAAS_VP.ViewModels
                 _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在开启}...", Value = curvalue });
             }));
             await management.InitSignal();
-            management.ReadConfig();
+            
 
             //当前日期
             CurrentTime = Guid.NewGuid();

+ 124 - 0
TeamAAS-VM/ViewModels/Product/PlcPointOffserParamsViewModel.cs

@@ -0,0 +1,124 @@
+using Prism.Commands;
+using Prism.Mvvm;
+using Prism.Services.Dialogs;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Windows;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Models.PLC;
+using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.Views.Setting;
+
+namespace TeamAAS_VP.ViewModels.Product
+{
+    public class PlcPointOffserParamsViewModel : BindableBase, IDialogAware
+    {
+
+        #region 属性
+        private ObservableCollection<PlcPoint> _Points = new ObservableCollection<PlcPoint>();
+        /// <summary>
+        /// 点位集合
+        /// </summary>
+        public ObservableCollection<PlcPoint> Points
+        {
+            get { return _Points; }
+            set { SetProperty(ref _Points, value); }
+        }
+        #endregion
+
+        #region 命令
+        private DelegateCommand _ConfirmCommand;
+        public DelegateCommand ConfirmCommand =>
+            _ConfirmCommand ?? (_ConfirmCommand = new DelegateCommand(ExecuteConfirmCommand, CanExecuteConfirmCommand));
+
+        private DelegateCommand _CancelCommand;
+        public DelegateCommand CancelCommand =>
+            _CancelCommand ?? (_CancelCommand = new DelegateCommand(ExecuteCancelCommand));
+
+        private DelegateCommand _ClearAllOffsetCommand;
+        public DelegateCommand ClearAllOffsetCommand =>
+            _ClearAllOffsetCommand ?? (_ClearAllOffsetCommand = new DelegateCommand(ExecuteClearAllOffsetCommand));
+
+
+        #endregion
+
+        public PlcPointOffserParamsViewModel()
+        {
+
+        }
+
+        /// <summary>
+        /// 确认按钮
+        /// </summary>
+        /// <returns></returns>
+        bool CanExecuteConfirmCommand()
+        {
+            return true;
+        }
+
+        void ExecuteConfirmCommand()
+        {
+            IDialogParameters parameters = new DialogParameters();
+            parameters.Add("Points", Points.ToArray());
+            RequestClose?.Invoke(new DialogResult(ButtonResult.OK, parameters));
+        }
+
+        /// <summary>
+        /// 取消按钮
+        /// </summary>
+        void ExecuteCancelCommand()
+        {
+            IDialogParameters parameters = new DialogParameters();
+            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel, parameters));
+        }
+
+        /// <summary>
+        /// 清除所有补偿值
+        /// </summary>
+        void ExecuteClearAllOffsetCommand()
+        {
+            foreach (var point in Points)
+            {
+                point.X_Offset = 0;
+                point.Y_Offset = 0;
+                point.Z_Start_Offset = 0;
+                point.Z_Stop_Offset = 0;
+                point.U_Offset = 0;
+                point.R_Offset = 0;
+            }
+
+        }
+
+        private string _Title;
+        public string Title
+        {
+            get { return _Title; }
+            set { SetProperty(ref _Title, value); }
+        }
+
+        public event Action<IDialogResult> RequestClose;
+
+        public bool CanCloseDialog()
+        {
+            return true;
+        }
+
+        public void OnDialogClosed()
+        {
+
+        }
+
+        public void OnDialogOpened(IDialogParameters parameters)
+        {
+            Title = parameters.GetValue<string>("Title");
+            var pts = parameters.GetValue<PlcPoint[]>("Points");
+            if (pts != null)
+            {
+                Points = new ObservableCollection<PlcPoint>(pts);
+            }
+        }
+    }
+}

+ 109 - 19
TeamAAS-VM/ViewModels/Product/PlcPointParamsViewModel.cs

@@ -45,7 +45,7 @@ namespace TeamAAS_VP.ViewModels.Product
         IRemoteCommandService _remoteCommandService;
         ICalibrationService _calibrationService;
         ICameraService _cameraService;
-        CoordinateTransformer local=null;
+        CoordinateTransformer local = null;
 
         #region 属性
 
@@ -292,10 +292,12 @@ namespace TeamAAS_VP.ViewModels.Product
         public CameraInfo SelectedCamera
         {
             get { return _SelectedCamera; }
-            set { SetProperty(ref _SelectedCamera, value);
-                if (value!=null)
+            set
+            {
+                SetProperty(ref _SelectedCamera, value);
+                if (value != null)
                 {
-                    if(Camera!=null)
+                    if (Camera != null)
                     {
                         if (Camera.IsGrabbing)
                         {
@@ -335,7 +337,9 @@ namespace TeamAAS_VP.ViewModels.Product
         public bool IsLeftDrawerOpen
         {
             get { return _IsLeftDrawerOpen; }
-            set { SetProperty(ref _IsLeftDrawerOpen, value);
+            set
+            {
+                SetProperty(ref _IsLeftDrawerOpen, value);
                 if (!value)
                 {
                     if (IsGrap)
@@ -438,7 +442,7 @@ namespace TeamAAS_VP.ViewModels.Product
 
         private DelegateCommand _StartGrabbingCommand;
         public DelegateCommand StartGrabbingCommand =>
-            _StartGrabbingCommand ?? (_StartGrabbingCommand = new DelegateCommand(ExecuteStartGrabbingCommand, CanExecuteStartGrabbingCommand).ObservesProperty(() => IsGrap).ObservesProperty(()=> SelectedCamera));
+            _StartGrabbingCommand ?? (_StartGrabbingCommand = new DelegateCommand(ExecuteStartGrabbingCommand, CanExecuteStartGrabbingCommand).ObservesProperty(() => IsGrap).ObservesProperty(() => SelectedCamera));
 
         private DelegateCommand _StopGrabbingCommand;
         public DelegateCommand StopGrabbingCommand =>
@@ -448,7 +452,11 @@ namespace TeamAAS_VP.ViewModels.Product
         public DelegateCommand DynamicTestAnalyzerCommand =>
             _DynamicTestAnalyzerCommand ?? (_DynamicTestAnalyzerCommand = new DelegateCommand(ExecuteDynamicTestAnalyzerCommand));
 
-        
+        private DelegateCommand _SetOffsetCommand;
+        public DelegateCommand SetOffsetCommand =>
+            _SetOffsetCommand ?? (_SetOffsetCommand = new DelegateCommand(ExecuteSetOffsetCommand));
+
+
         #endregion
 
         #region 事件
@@ -625,7 +633,7 @@ namespace TeamAAS_VP.ViewModels.Product
                             break;
                     }
                     //Robot.Timeout = 5000;
-                }    
+                }
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = $"{Lang.完成}!", Duration = 0.4 });
             }
             catch (Exception ex)
@@ -657,7 +665,7 @@ namespace TeamAAS_VP.ViewModels.Product
                     }
 
                     //弹窗用户是否确认要示教该点位
-                    if (MessageBox.Show(string.Format(Lang.确认要示教点位0吗,SelectedPoint.Number), Lang.示教点位, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
+                    if (MessageBox.Show(string.Format(Lang.确认要示教点位0吗, SelectedPoint.Number), Lang.示教点位, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                     {
                         return;
                     }
@@ -976,10 +984,17 @@ namespace TeamAAS_VP.ViewModels.Product
                         int startNumber = view.StartIndex;
 
                         //弹窗提示用户是否确认要导入从该编号开始的点位,点位数量为cadPoints.Count
-                        if (MessageBox.Show(string.Format(Lang.确认要从点位编号0开始导入1个点位吗, startNumber,cadPoints.Count), Lang.导入点位, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
+                        if (MessageBox.Show(string.Format(Lang.确认要从点位编号0开始导入1个点位吗, startNumber, cadPoints.Count), Lang.导入点位, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                         {
                             return;
                         }
+                        //是否对原有点位的XY补偿值进行清零?
+                        bool clearCompensate = false;
+                        if (MessageBox.Show("是否对原有点位的XY补偿值进行清零?", Lang.确认, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
+                        {
+                            clearCompensate = true;
+                        }
+
                         //导入点位
                         for (int i = 0; i < cadPoints.Count; i++)
                         {
@@ -990,7 +1005,11 @@ namespace TeamAAS_VP.ViewModels.Product
                             {
                                 existingPoint.X_Position = point.X;
                                 existingPoint.Y_Position = point.Y;
-
+                                if (clearCompensate)
+                                {
+                                    existingPoint.X_Offset = 0;
+                                    existingPoint.Y_Offset = 0;
+                                }
                             }
                             else
                             {
@@ -1171,7 +1190,7 @@ namespace TeamAAS_VP.ViewModels.Product
             {
                 if (point.Z_Position_Stop >= point.Z_Position_Start)
                 {
-                    MessageBox.Show(string.Format(Lang.点位编号0的终点坐标大于等于起始坐标请调整终点坐标, point.Number ), Lang.警告, MessageBoxButton.OK, MessageBoxImage.Warning);
+                    MessageBox.Show(string.Format(Lang.点位编号0的终点坐标大于等于起始坐标请调整终点坐标, point.Number), Lang.警告, MessageBoxButton.OK, MessageBoxImage.Warning);
                 }
             }
 
@@ -1246,8 +1265,8 @@ namespace TeamAAS_VP.ViewModels.Product
                     if (result1 == ButtonResult.OK)
                     {
                         var param = rst.Parameters.GetValue<ObservableCollection<PointEx>>("CorrectPoints");
-                        var local1= rst.Parameters.GetValue<CoordinateTransformer>("Local");
-                        if (local1!=null)
+                        var local1 = rst.Parameters.GetValue<CoordinateTransformer>("Local");
+                        if (local1 != null)
                         {
                             local = local1;
                         }
@@ -1255,6 +1274,9 @@ namespace TeamAAS_VP.ViewModels.Product
                         {
                             SelectProduct.ScrewPoints[i].X_Position = param[i].PostX;
                             SelectProduct.ScrewPoints[i].Y_Position = param[i].PostY;
+                            //XY的补偿值清零
+                            SelectProduct.ScrewPoints[i].X_Offset = 0;
+                            SelectProduct.ScrewPoints[i].Y_Offset = 0;
                         }
 
                         _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
@@ -1309,7 +1331,7 @@ namespace TeamAAS_VP.ViewModels.Product
                 }
 
 
-                
+
                 //如果当前Local为空,则自动进行锁付点位的Local计算
                 if (local == null)
                 {
@@ -1545,7 +1567,7 @@ namespace TeamAAS_VP.ViewModels.Product
         /// </summary>
         void ExecuteStopGrabbingCommand()
         {
-            
+
             if (Camera != null)
                 Camera.StopGrabbing();
             IsGrap = false;
@@ -1586,6 +1608,74 @@ namespace TeamAAS_VP.ViewModels.Product
                      }
                  }));
         }
+
+        /// <summary>
+        /// 设置偏移
+        /// </summary>
+        void ExecuteSetOffsetCommand()
+        {
+            if (SelectedIndex<0) return;
+            IDialogParameters parameters1 = new DialogParameters();
+            if (SelectedIndex == 0)
+            {
+                parameters1.Add("Title", "取料拍照点位-补偿值设置");
+            }
+            else if (SelectedIndex == 1)
+            {
+                parameters1.Add("Title", "取料点位-补偿值设置");
+            }
+            else if (SelectedIndex == 2)
+            {
+                parameters1.Add("Title", "下相机二次定位点位-补偿值设置");
+            }
+            else if (SelectedIndex == 3)
+            {
+                parameters1.Add("Title", "锁附拍照点位-补偿值设置");
+            }
+            else if (SelectedIndex == 4)
+            {
+                parameters1.Add("Title", "锁附点位-补偿值设置");
+            }
+            else if (SelectedIndex == 5)
+            {
+                parameters1.Add("Title", "复检点位-补偿值设置");
+            }
+            else
+            {
+                parameters1.Add("Title", "点位-补偿值设置");
+            }
+
+            List<PlcPoint> _points = new List<PlcPoint>();
+            foreach (var item in Points)
+            {
+                _points.Add(item.Clone());
+            }
+            parameters1.Add("Points", _points.ToArray());
+            _dialogService.ShowDialog("PlcPointOffserParams", parameters1, rst =>
+            {
+                //对话框关闭之后的回调函数,可以在这解析结果。
+                ButtonResult result1 = rst.Result;
+
+                if (result1 == ButtonResult.OK)
+                {
+                    var param = rst.Parameters.GetValue<PlcPoint[]>("Points");
+
+                    //更新点位
+                    for (int i = 0; i < Points.Count; i++)
+                    {
+                        Points[i].X_Offset = param[i].X_Offset;
+                        Points[i].Y_Offset = param[i].Y_Offset;
+                        Points[i].Z_Start_Offset = param[i].Z_Start_Offset;
+                        Points[i].Z_Stop_Offset = param[i].Z_Stop_Offset;
+                        Points[i].U_Offset = param[i].U_Offset;
+                        Points[i].R_Offset = param[i].R_Offset;
+                    }
+
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = $"{Lang.完成}", Duration = 1 });
+                }
+
+            });
+        }
         #endregion
 
         #region 继承
@@ -1649,7 +1739,7 @@ namespace TeamAAS_VP.ViewModels.Product
                 LockScrewProgramNumber = SelectProduct.ScrewPoints.FirstOrDefault()?.ScrewProNum ?? 1;
 
                 CameraList = new ObservableCollection<CameraInfo>(_configService.GetAllCameras());
-               
+
             }
             catch (Exception ex)
             {
@@ -1687,7 +1777,7 @@ namespace TeamAAS_VP.ViewModels.Product
                         Camera.StopGrabbing();
                     }
                     Camera.ImageCallbackEvent -= Camera_ImageCallbackEvent;
-                    
+
                     Camera = null;
                 }
                 SelectedCamera = null;
@@ -1782,7 +1872,7 @@ namespace TeamAAS_VP.ViewModels.Product
 
                 var _cts = new CancellationTokenSource();
                 // 2. 执行拍照并获取识别结果
-                var recognitionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(SelectProcedure, null, new double[] { rpoint.X, rpoint.Y, 0 }, _cts.Token);
+                var recognitionResult = await _remoteCommandService.ExecutePhotoGetSinglePointWithImage(SelectProcedure, null, new double[] { rpoint.X, rpoint.Y, 0 }, _cts.Token);
                 if (!recognitionResult.IsSucceed)
                 {
                     if (DialogHost.IsDialogOpen("RootDialog"))

+ 3 - 0
TeamAAS-VM/ViewModels/Product/ProcedureParamsViewModel.cs

@@ -309,6 +309,9 @@ namespace TeamAAS_VP.ViewModels.Product
             });
         }
 
+        /// <summary>
+        /// 选择保存图片路径
+        /// </summary>
         void ExecuteSelectSaveImagePathCommand()
         {
             if (SelectProcedure == null)

+ 82 - 18
TeamAAS-VM/ViewModels/Product/VisionDynamicAccuracyAnalyzerViewModel.cs

@@ -241,6 +241,43 @@ namespace TeamAAS_VP.ViewModels.Product
             get { return _precisionResult; }
             set { SetProperty(ref _precisionResult, value); }
         }
+
+        private int _ADelay = 300;
+        /// <summary>
+        /// A点延时时间
+        /// </summary>
+        public int ADelay
+        {
+            get { return _ADelay; }
+            set { SetProperty(ref _ADelay, value); }
+        }
+
+        private int _BDelay = 500;
+        /// <summary>
+        /// B点延时时间
+        /// </summary>
+        public int BDelay
+        {
+            get { return _BDelay; }
+            set { SetProperty(ref _BDelay, value); }
+        }
+
+        private bool _IsTakePhoto = true;
+        /// <summary>
+        /// 是否启用拍照
+        /// </summary>
+        public bool IsTakePhoto
+        {
+            get { return _IsTakePhoto; }
+            set { SetProperty(ref _IsTakePhoto, value); }
+        }
+
+        private int _ProIndex;
+        public int ProIndex
+        {
+            get { return _ProIndex; }
+            set { SetProperty(ref _ProIndex, value); }
+        }
         #endregion
 
         #region 命令
@@ -385,7 +422,7 @@ namespace TeamAAS_VP.ViewModels.Product
                     SendTaskMessage("机器人移动到A点失败!");
                     return;
                 }
-                await Task.Delay(200);
+                await Task.Delay(ADelay);
 
                 //移动机器人至B点
                 isSuccess1 = await Robot.CalibMotionAsync(PointB, null);
@@ -394,9 +431,13 @@ namespace TeamAAS_VP.ViewModels.Product
                     SendTaskMessage("机器人移动到B点失败!");
                     return;
                 }
-                await Task.Delay(300);
-                //相机拍照并处理
-                (bool isSuccess, double pixelX, double pixelY, double angleU, double transformX, double transformY) = await ExecutePhotoEx(CurrentProgress);
+                await Task.Delay(BDelay);
+
+                if (IsTakePhoto)
+                {
+                    //相机拍照并处理
+                    (bool isSuccess, double pixelX, double pixelY, double angleU, double transformX, double transformY) = await ExecutePhotoEx(CurrentProgress);
+                }
 
                 CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
             }
@@ -435,6 +476,18 @@ namespace TeamAAS_VP.ViewModels.Product
                     return;
                 }
 
+                if (Robot == null || !Robot.IsConnected)
+                {
+                    SendTaskMessage("机器人未连接,无法示教!");
+                    return;
+                }
+
+                if (Camera == null || !Camera.IsConnected)
+                {
+                    SendTaskMessage("相机未连接,无法示教!");
+                    return;
+                }
+
                 //为机器人设置移动速度
                 await Robot.CalibParameAsync(new PickInfo(), MoveSpeed, 0, false, 0, 0);
 
@@ -454,7 +507,7 @@ namespace TeamAAS_VP.ViewModels.Product
                         SendTaskMessage("机器人移动到A点失败!");
                         return;
                     }
-                    await Task.Delay(200);
+                    await Task.Delay(ADelay);
                     if (_cts.Token.IsCancellationRequested)
                     {
                         Message = "测试已取消!";
@@ -468,30 +521,41 @@ namespace TeamAAS_VP.ViewModels.Product
                         SendTaskMessage("机器人移动到B点失败!");
                         return;
                     }
-                    await Task.Delay(300);
+                    await Task.Delay(BDelay);
                     if (_cts.Token.IsCancellationRequested)
                     {
                         Message = "测试已取消!";
                         break;
                     }
 
-                    //相机拍照并处理
-                    (bool isSuccess, double pixelX, double pixelY, double angleU, double transformX, double transformY) = await ExecutePhotoEx(CurrentProgress);
-                    CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
-
-                    if (isSuccess)
+                    if (IsTakePhoto)
                     {
-                        SuccessCount++;
+                        //相机拍照并处理
+                        (bool isSuccess, double pixelX, double pixelY, double angleU, double transformX, double transformY) = await ExecutePhotoEx(CurrentProgress);
+
+                        CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
+
+                        if (isSuccess)
+                        {
+                            SuccessCount++;
+                        }
+                        else
+                        {
+                            FailCount++;
+                        }
+                        TestResults.Add(new DynamicTestResult(CurrentProgress, isSuccess, PointB, CycleTime, pixelX, pixelY, angleU, transformX, transformY));
+                        OnTestResultAdded();
+
+                        CurrentProgress++;
+                        SuccessRate = (double)SuccessCount / CurrentProgress * 100;
                     }
                     else
                     {
-                        FailCount++;
+                        CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
+                        SuccessCount++;
+                        CurrentProgress++;
+                        SuccessRate = (double)SuccessCount / CurrentProgress * 100;
                     }
-                    TestResults.Add(new DynamicTestResult(CurrentProgress, isSuccess, PointB, CycleTime, pixelX, pixelY, angleU, transformX, transformY));
-                    OnTestResultAdded();
-
-                    CurrentProgress++;
-                    SuccessRate = (double)SuccessCount / CurrentProgress * 100;
                     SendTaskMessage($"测试进行中... {CurrentProgress}/{RepeatCount}");
                 }
                 if (CurrentProgress >= RepeatCount)

+ 28 - 2
TeamAAS-VM/ViewModels/Product/VisionStaticAccuracyAnalyzerViewModel.cs

@@ -119,6 +119,16 @@ namespace TeamAAS_VP.ViewModels.Product
             set { SetProperty(ref _RepeatCount, value); }
         }
 
+        private int _DelayTime = 200;
+        /// <summary>
+        /// 延时时间
+        /// </summary>
+        public int DelayTime
+        {
+            get { return _DelayTime; }
+            set { SetProperty(ref _DelayTime, value); }
+        }
+
         private int _CurrentProgress;
         /// <summary>
         /// 当前进度
@@ -317,7 +327,7 @@ namespace TeamAAS_VP.ViewModels.Product
                         Message = "测试已取消!";
                         break;
                     }
-
+                    await Task.Delay(DelayTime);
                     (bool isSuccess, object[] Result) = await ExecutePhotoEx(CurrentProgress);
                     if (isSuccess)
                     {
@@ -957,8 +967,24 @@ namespace TeamAAS_VP.ViewModels.Product
                                             //如果需要转换为绝对坐标,则再创建绝对X、绝对Y两列
                                             if (needConvertToAbsolute)
                                             {
+                                                double[] point = new double[3];
                                                 var calibration = _calibrationService.GetCalibration(SelectProcedure.CalibrationId);
-                                                (bool IsSucceed, double X, double Y, double U) = _calibrationService.ConvertPixelToPosition((double.Parse(subitems[0]), double.Parse(subitems[1]), double.Parse(subitems[2])), null, calibration);
+
+                                                var Robot = _robotService.GetRobot(SelectProcedure.RobotId);
+                                                if (Robot!=null)
+                                                {
+                                                    //获取机器人当前坐标系
+                                                    RPoint rPoint = Robot.GetRobotPos();
+
+                                                    point[0] = rPoint.X;
+                                                    point[1] = rPoint.Y;
+                                                    point[2] = rPoint.U;
+                                                    if (calibration.CameraMount == CameraMount.FixedUp || calibration.CameraMount == CameraMount.FixedDown)
+                                                    {
+                                                        point = null;
+                                                    }
+                                                }
+                                                (bool IsSucceed, double X, double Y, double U) = _calibrationService.ConvertPixelToPosition((double.Parse(subitems[0]), double.Parse(subitems[1]), double.Parse(subitems[2])), point, calibration);
                                                 result.Add(Math.Round(X, 5));
                                                 result.Add(Math.Round(Y, 5));
                                             }

+ 2 - 2
TeamAAS-VM/ViewModels/Setting/AddLightControllerViewModel.cs

@@ -36,7 +36,7 @@ namespace TeamAAS_VP.ViewModels.Setting
 
         public void OnDialogOpened(IDialogParameters parameters)
         {
-            LightController = new LightControllerConfig() { Id = 0, Name = "New Controller", LightModel = TeamAAS_VP.Core.Lights.LightModel.KCS_KDC_12V60W_4T };
+            LightController = new LightControllerConfig() { Id = 0, Name = "New Controller", LightModel = TeamAAS_VP.Core.Lights.LightModel.KCS_KDC_12V60W_4T }.Init();
         }
 
         bool CanExecuteConfirmCommand()
@@ -47,7 +47,7 @@ namespace TeamAAS_VP.ViewModels.Setting
         void ExecuteConfirmCommand()
         {
             var p = new DialogParameters();
-            p.Add("LightController", LightController);
+            p.Add("LightController", LightController.Init());
             RequestClose?.Invoke(new DialogResult(ButtonResult.OK, p));
         }
 

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

@@ -333,6 +333,13 @@ namespace TeamAAS_VP.ViewModels
             set { SetProperty(ref _DeviceInfo, value); }
         }
 
+        private SerialPortConfig _CardReaderConfig;
+        public SerialPortConfig CardReaderConfig
+        {
+            get { return _CardReaderConfig; }
+            set { SetProperty(ref _CardReaderConfig, value); }
+        }
+
         #endregion
 
         #region 命令
@@ -412,6 +419,9 @@ namespace TeamAAS_VP.ViewModels
         private DelegateCommand _SaveDeviceInfoCommand;
         public DelegateCommand SaveDeviceInfoCommand => _SaveDeviceInfoCommand ?? (_SaveDeviceInfoCommand = new DelegateCommand(ExecuteSaveDeviceInfoCommand));
 
+        private DelegateCommand _BrowseScrewCurvePathCommand;
+        public DelegateCommand BrowseScrewCurvePathCommand => _BrowseScrewCurvePathCommand ?? (_BrowseScrewCurvePathCommand = new DelegateCommand(ExecuteBrowseScrewCurvePathCommand));
+
         private DelegateCommand _AddScrewFeederCommand;
         public DelegateCommand AddScrewFeederCommand =>
             _AddScrewFeederCommand ?? (_AddScrewFeederCommand = new DelegateCommand(ExecuteAddScrewFeederCommand));
@@ -424,7 +434,15 @@ namespace TeamAAS_VP.ViewModels
         public DelegateCommand SaveScrewFeedersCommand =>
             _SaveScrewFeedersCommand ?? (_SaveScrewFeedersCommand = new DelegateCommand(ExecuteSaveScrewFeedersCommand));
 
+        private DelegateCommand<object> _LightModelChangedCommand;
+        public DelegateCommand<object> LightModelChangedCommand =>
+            _LightModelChangedCommand ?? (_LightModelChangedCommand = new DelegateCommand<object>(ExecuteLightModelChangedCommand));
+
+        private DelegateCommand _SaveCardReaderConfigCommand;
+        public DelegateCommand SaveCardReaderConfigCommand =>
+            _SaveCardReaderConfigCommand ?? (_SaveCardReaderConfigCommand = new DelegateCommand(ExecuteSaveCardReaderConfigCommand));
 
+        
         #endregion
 
         #region 事件
@@ -521,7 +539,7 @@ namespace TeamAAS_VP.ViewModels
                         if (robot != null)
                         {
                             //更新连接参数
-                            robot.SafeZ=item.SafeZ;
+                            robot.SafeZ = item.SafeZ;
                         }
                         _configService.AddOrUpdateRobot(item);
                     }
@@ -974,6 +992,28 @@ namespace TeamAAS_VP.ViewModels
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
             }
         }
+
+        /// <summary>
+        /// 光源型号改变
+        /// </summary>
+        void ExecuteLightModelChangedCommand(object obj)
+        {
+            try
+            {
+                if (obj == null)
+                {
+                    return;
+                }
+                if (obj is LightControllerConfig lc)
+                {
+                    lc.Init();
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
         #endregion
 
         #region 螺丝供料器
@@ -1120,57 +1160,25 @@ namespace TeamAAS_VP.ViewModels
             if (string.Equals(language, "ChineseSimplified"))
             {
                 CurrentLanguage = Enums.Language.ChineseSimplified;
-                var sysConfig = _configService.GetSystemConfiguration();
-                sysConfig.CurrentLanguage = CurrentLanguage;
-                _configService.SaveSystemConfiguration(sysConfig);
-                var culture = new CultureInfo("zh-CN");
-                App.Current.Dispatcher.Thread.CurrentCulture = culture;
-                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
-                LocalizeDictionary.Instance.Culture = culture;
-                Lang.Culture = culture;
-                Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Microsoft YaHei");
+                _configService.SetCurrentLanguage(CurrentLanguage);
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 0.5 });
             }
             else if (string.Equals(language, "ChineseTraditional"))
             {
                 CurrentLanguage = Enums.Language.ChineseTraditional;
-                var sysConfig = _configService.GetSystemConfiguration();
-                sysConfig.CurrentLanguage = CurrentLanguage;
-                _configService.SaveSystemConfiguration(sysConfig);
-                var culture = new CultureInfo("zh-TW");
-                App.Current.Dispatcher.Thread.CurrentCulture = culture;
-                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
-                LocalizeDictionary.Instance.Culture = culture;
-                Lang.Culture = culture;
-                Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Microsoft YaHei");
+                _configService.SetCurrentLanguage(CurrentLanguage);
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 0.5 });
             }
             else if (string.Equals(language, "English"))
             {
                 CurrentLanguage = Enums.Language.English;
-                var sysConfig = _configService.GetSystemConfiguration();
-                sysConfig.CurrentLanguage = CurrentLanguage;
-                _configService.SaveSystemConfiguration(sysConfig);
-                var culture = new CultureInfo("en");
-                App.Current.Dispatcher.Thread.CurrentCulture = culture;
-                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
-                LocalizeDictionary.Instance.Culture = culture;
-                Lang.Culture = culture;
-                Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Segoe UI");
+                _configService.SetCurrentLanguage(CurrentLanguage);
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 0.5 });
             }
             else if (string.Equals(language, "Japanese"))
             {
                 CurrentLanguage = Enums.Language.Japanese;
-                var sysConfig = _configService.GetSystemConfiguration();
-                sysConfig.CurrentLanguage = CurrentLanguage;
-                _configService.SaveSystemConfiguration(sysConfig);
-                var culture = new CultureInfo("ja-JP");
-                App.Current.Dispatcher.Thread.CurrentCulture = culture;
-                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
-                LocalizeDictionary.Instance.Culture = culture;
-                Lang.Culture = culture;
-                Application.Current.Resources["DefaultFont"] = new System.Windows.Media.FontFamily("Segoe UI");
+                _configService.SetCurrentLanguage(CurrentLanguage);
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 0.5 });
             }
         }
@@ -1321,6 +1329,18 @@ namespace TeamAAS_VP.ViewModels
                 DeviceInfo = _configService.GetDeviceInfo();
             }
 
+            if (ScrewFeederList==null)
+            {
+                var screwFeeders = _configService.GetAllScrewFeeders();
+                ScrewFeederList = new ObservableCollection<ScrewFeederInfo>(screwFeeders);
+            }
+
+            if (CardReaderConfig == null)
+            {
+                // load card reader config
+                CardReaderConfig = _configService.GetCardReaderConfig();
+            }
+
             CurrentLanguage = _configService.GetSystemConfiguration().CurrentLanguage;
 
             // load system parameters into UI
@@ -1340,6 +1360,8 @@ namespace TeamAAS_VP.ViewModels
                 FixedCameraPutNum = sys.FixedCameraPutNum;
                 FixedCameracheckNum = sys.FixedCameracheckNum;
                 ScrewTeachNum = sys.ScrewTeachNum;
+                IsSaveScrewCurve= sys.IsSaveScrewCurve;
+                ScrewCurvePath= sys.ScrewCurvePath;
             }
 
             if (isFirstLoad)
@@ -1502,6 +1524,54 @@ namespace TeamAAS_VP.ViewModels
             set => SetProperty(ref _ScrewTeachNum, value);
         }
 
+        private bool _IsSaveScrewCurve;
+        /// <summary>
+        /// 是否保存锁付曲线图
+        /// </summary>
+        public bool IsSaveScrewCurve
+        {
+            get { return _IsSaveScrewCurve; }
+            set { SetProperty(ref _IsSaveScrewCurve, value); }
+        }
+
+        private string _ScrewCurvePath;
+        /// <summary>
+        /// 锁付曲线图保存路径
+        /// </summary>
+        public string ScrewCurvePath
+        {
+            get { return _ScrewCurvePath; }
+            set { SetProperty(ref _ScrewCurvePath, value); }
+        }
+
+        /// <summary>
+        /// 选择锁付曲线图保存路径
+        /// </summary>
+        void ExecuteBrowseScrewCurvePathCommand()
+        {
+            try
+            {
+                using (var dlg = new System.Windows.Forms.FolderBrowserDialog())
+                {
+                    dlg.Description = "选择锁付曲线图保存路径";
+                    dlg.ShowNewFolderButton = true;
+                    if (!string.IsNullOrEmpty(ScrewCurvePath)) dlg.SelectedPath = ScrewCurvePath;
+                    var result = dlg.ShowDialog();
+                    if (result == System.Windows.Forms.DialogResult.OK || result == System.Windows.Forms.DialogResult.Yes)
+                    {
+                        ScrewCurvePath = dlg.SelectedPath;
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 2 });
+            }
+        }
+
+        /// <summary>
+        /// 保存系统参数
+        /// </summary>
         async void ExecuteSaveSystemParametersCommand()
         {
             var view = new ShowMessage($"AAS", Lang.是否保存系统参数);
@@ -1521,6 +1591,8 @@ namespace TeamAAS_VP.ViewModels
                     sysConfig.FixedCameraPutNum = FixedCameraPutNum;
                     sysConfig.FixedCameracheckNum = FixedCameracheckNum;
                     sysConfig.ScrewTeachNum = ScrewTeachNum;
+                    sysConfig.IsSaveScrewCurve = IsSaveScrewCurve;
+                    sysConfig.ScrewCurvePath = ScrewCurvePath;
 
                     _configService.SaveSystemConfiguration(sysConfig);
                     await management.WriteSystemParameterToPlcAsync(sysConfig);
@@ -1532,6 +1604,21 @@ namespace TeamAAS_VP.ViewModels
                 }
             }
         }
+
+        /// <summary>
+        /// 保存读卡器配置
+        /// </summary>
+        void ExecuteSaveCardReaderConfigCommand()
+        {
+            try
+            {
+                _configService.SaveCardReaderConfig(CardReaderConfig);
+            }
+            catch (Exception ex)
+            {
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
+            }
+        }
         #endregion
 
         #region 设备信息

+ 16 - 11
TeamAAS-VM/ViewModels/Statistics/LockResultRecoredQueryViewModel.cs

@@ -149,18 +149,19 @@ namespace TeamAAS_VP.ViewModels.Statistics
                 var end = EndDate.HasValue ? EndDate.Value.Date.AddDays(1) : DateTime.MaxValue;
 
                 string productNumberFilter = null;
+                string productName = 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))
+                if (SelectedProduct != null)
                 {
                     // assume SelectedProduct.Name correspond to ProductNumber field used when storing
-                    productNumberFilter = SelectedProduct.Name;
+                    productName = SelectedProduct.Name;
                 }
 
                 int pageIndex = PageIndex < 1 ? 1 : PageIndex;
                 int pageSize = PageSize < 1 ? 20 : PageSize;
 
-                var res = await _systemDatabaseService.QueryLockResultsAsync(start, end, pageIndex, pageSize, productNumberFilter, ScrewNumber);
+                var res = await _systemDatabaseService.QueryLockResultsAsync(start, end, pageIndex, pageSize, productNumberFilter, productName, ScrewNumber);
                 Results = new ObservableCollection<LockResult>(res.Items);
                 TotalCount = res.TotalCount;
             }
@@ -185,14 +186,15 @@ namespace TeamAAS_VP.ViewModels.Statistics
                 var end = EndDate.HasValue ? EndDate.Value.Date.AddDays(1) : DateTime.MaxValue;
 
                 string productNumberFilter = null;
+                string productName = null;
                 if (!string.IsNullOrWhiteSpace(ProductNumber)) productNumberFilter = ProductNumber.Trim();
-                if (SelectedProduct != null && string.IsNullOrEmpty(productNumberFilter))
+                if (SelectedProduct != null)
                 {
-                    productNumberFilter = SelectedProduct.Name;
+                    productName = SelectedProduct.Name;
                 }
 
                 // fetch all matching records (not paged)
-                var all = await _systemDatabaseService.QueryAllLockResultsAsync(start, end, productNumberFilter, ScrewNumber);
+                var all = await _systemDatabaseService.QueryAllLockResultsAsync(start, end, productNumberFilter, productName, ScrewNumber);
                 if (all == null || !all.Any())
                 {
                     MessageBox.Show(Lang.没有找到符合条件的记录, Lang.提示, MessageBoxButton.OK, MessageBoxImage.Information);
@@ -212,12 +214,13 @@ namespace TeamAAS_VP.ViewModels.Statistics
                 // write in streaming manner to support large sets
                 using (var sw = new StreamWriter(path, false, Encoding.UTF8))
                 {
-                    sw.WriteLine("Id,Number,ProductNumber,Timestamp,LockTurns,LockTorque,LockDuration,LockPassed,ResultDetails,ScrewdriverProgramNumber,Pressure,TargetTorque,TargetTurnsUpperLimit,TargetTurnsLowerLimit,TargetLockSpeed,StartPositionX,StartPositionY,StartPositionZ,EndPositionZ,LockDescentSpeed,FeederNumber,NozzleNumber,OperatorName,ProductImagePath");
+                    sw.WriteLine("Id,Number,ProductName,ProductNumber,Timestamp,LockTurns,LockTorque,LockDuration,LockPassed,ResultDetails,ScrewdriverProgramNumber,Pressure,TargetTorqueUpperLimit,TargetTorqueLowerLimit,TargetTurnsUpperLimit,TargetTurnsLowerLimit,TargetLockSpeed,StartPositionX,StartPositionY,StartPositionZ,EndPositionZ,LockDescentSpeed,FeederNumber,NozzleNumber,OperatorName,ProductImagePath,LockCurveImagePath");
                     foreach (var r in all)
                     {
                         var line = string.Join(",",
                             EscapeCsv(r.Id.ToString()),
                             EscapeCsv(r.Number.ToString()),
+                            EscapeCsv(r.ProductName),
                             EscapeCsv(r.ProductNumber),
                             EscapeCsv(r.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")),
                             EscapeCsv(r.LockTurns.ToString()),
@@ -227,19 +230,21 @@ namespace TeamAAS_VP.ViewModels.Statistics
                             EscapeCsv(r.ResultDetails),
                             EscapeCsv(r.ScrewdriverProgramNumber.ToString()),
                             EscapeCsv(r.Pressure.ToString()),
-                            EscapeCsv(r.TargetTorque.ToString()),
+                            EscapeCsv(r.TargetTorqueUpperLimit.ToString()),
+                            EscapeCsv(r.TargetTorqueLowerLimit.ToString()),
                             EscapeCsv(r.TargetTurnsUpperLimit.ToString()),
                             EscapeCsv(r.TargetTurnsLowerLimit.ToString()),
                             EscapeCsv(r.TargetLockSpeed.ToString()),
-                            EscapeCsv(r.StartPositionX.ToString()),
-                            EscapeCsv(r.StartPositionY.ToString()),
+                            EscapeCsv(r.PositionX.ToString()),
+                            EscapeCsv(r.PositionY.ToString()),
                             EscapeCsv(r.StartPositionZ.ToString()),
                             EscapeCsv(r.EndPositionZ.ToString()),
                             EscapeCsv(r.LockDescentSpeed.ToString()),
                             EscapeCsv(r.FeederNumber.ToString()),
                             EscapeCsv(r.NozzleNumber),
                             EscapeCsv(r.OperatorName),
-                            EscapeCsv(r.ProductImagePath)
+                            EscapeCsv(r.ProductImagePath),
+                            EscapeCsv(r.LockCurveImagePath)
                         );
                         sw.WriteLine(line);
                     }

+ 287 - 0
TeamAAS-VM/ViewModels/User/CardLoginWindowViewModel.cs

@@ -0,0 +1,287 @@
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using OpenCvSharp;
+using Prism.Commands;
+using Prism.Events;
+using Prism.Ioc;
+using Prism.Mvvm;
+using Prism.Regions;
+using Prism.Services.Dialogs;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Net.Http;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Core.Lights;
+using TeamAAS_VP.Data;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Events;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.Views;
+using TeamAAS_VP.Views.User;
+
+namespace TeamAAS_VP.ViewModels.User
+{
+    public class CardLoginWindowViewModel : BindableBase
+    {
+        #region 字段
+        IConfigService _configService;
+        private readonly ISystemDatabaseService _systemDatabaseService;
+        private readonly IEventAggregator _eventAggregator;
+        private List<TeamAAS_VP.Models.User> Users;
+        #endregion
+
+        #region 属性
+
+        private ObservableCollection<string> _UserNameList = new ObservableCollection<string>();
+
+        /// <summary>
+        /// 用户列表
+        /// </summary>
+        public ObservableCollection<string> UserNameList
+        {
+            get { return _UserNameList; }
+            set { _UserNameList = value; }
+        }
+
+        private string _SelectedUserName;
+        public string SelectedUserName
+        {
+            get { return _SelectedUserName; }
+            set { SetProperty(ref _SelectedUserName, value); }
+        }
+
+        private string _Password;
+        public string Password
+        {
+            get { return _Password; }
+            set { SetProperty(ref _Password, value); }
+        }
+
+        public bool IsRemember { get; set; }
+
+        public bool IsLocal { get; private set; }
+        public CardLoginWindow View { get; set; }
+
+        //正在登录中
+        private bool _IsLogining;
+        public bool IsLogining
+        {
+            get { return _IsLogining; }
+            set { SetProperty(ref _IsLogining, value); }
+        }
+
+        private int _PageIndex;
+        public int PageIndex
+        {
+            get { return _PageIndex; }
+            set { SetProperty(ref _PageIndex, value); }
+        }
+
+        private Visibility _CardBtnVisibility = Visibility.Visible;
+        public Visibility CardBtnVisibility
+        {
+            get { return _CardBtnVisibility; }
+            set { SetProperty(ref _CardBtnVisibility, value); }
+        }
+
+        public SerialPortProtocol serialPortProtocol { get; set; }
+        #endregion
+
+        #region 命令
+        private DelegateCommand _LoginCommand;
+        public DelegateCommand LoginCommand =>
+            _LoginCommand ?? (_LoginCommand = new DelegateCommand(ExecuteLoginCommand, CanExecuteLoginCommand).ObservesProperty(() => SelectedUserName).ObservesProperty(() => Password).ObservesProperty(() => IsLogining));
+
+        private DelegateCommand _CloseCommand;
+        public DelegateCommand CloseCommand =>
+            _CloseCommand ?? (_CloseCommand = new DelegateCommand(ExecuteCloseCommand));
+
+        private DelegateCommand<string> _TransitionerCommand;
+        public DelegateCommand<string> TransitionerCommand =>
+            _TransitionerCommand ?? (_TransitionerCommand = new DelegateCommand<string>(ExecuteTransitionerCommand));
+
+        private DelegateCommand _LoadedCommand;
+        public DelegateCommand LoadedCommand =>
+            _LoadedCommand ?? (_LoadedCommand = new DelegateCommand(ExecuteLoadedCommand));
+        #endregion
+
+        #region 事件
+
+        #endregion
+
+        public CardLoginWindowViewModel(IConfigService configService, ISystemDatabaseService systemDatabaseService, IEventAggregator eventAggregator)
+        {
+            _configService = configService;
+            _systemDatabaseService = systemDatabaseService;
+            _eventAggregator = eventAggregator;
+        }
+
+
+        #region 方法
+        /// <summary>
+        /// 加载
+        /// </summary>
+        async void ExecuteLoadedCommand()
+        {
+            //获取刷卡器配置
+            var cardConfig = _configService.GetCardReaderConfig();
+            try
+            {
+                Users = _systemDatabaseService.GetAllUsersAsync().GetAwaiter().GetResult()?.ToList();
+            }
+            catch
+            {
+                Users = new List<TeamAAS_VP.Models.User>();
+            }
+            TeamAAS_VP.Models.User rememberUser = null;
+            if (Users != null)
+            {
+                UserNameList.Clear();
+                foreach (var user in Users)
+                {
+                    UserNameList.Add(user.UserName);
+                    if (user.IsRemember)
+                    {
+                        rememberUser = user;
+                    }
+                }
+            }
+
+            //对记住的用户界面绑定
+            if (rememberUser != null)
+            {
+                SelectedUserName = UserNameList.FirstOrDefault(p => p == rememberUser.UserName);
+                Password = rememberUser.UserPassword;
+                IsRemember = true;
+            }
+
+            //创建刷卡器通讯
+            serialPortProtocol = new SerialPortProtocol(cardConfig);
+            serialPortProtocol.DataReceived += CardSerial_DataReceived;
+            bool isConnected = await serialPortProtocol.ConnectAsync();
+            if (!isConnected)
+            {
+                MessageBox.Show("刷卡器连接失败,请检查连接!");
+            }
+        }
+
+        private async void CardSerial_DataReceived(object sender, string code)
+        {
+            if (PageIndex == 0)
+            {
+                if (string.IsNullOrEmpty(code))
+                {
+                    return;
+                }
+                Models.User user = new Models.User();
+                user.UserName = code.Trim().TrimStart('\0');
+                user.userPart = UserPart.Engineer;
+                user.UserPassword = code.Trim().TrimStart('\0'); //刷卡密码默认为卡号
+                user.CreateTime = DateTime.Now;
+                user.Id = -1;
+
+                await _systemDatabaseService.SetCurrentUserAsync(user);
+
+                App.Current.Dispatcher.Invoke(() =>
+                {
+                    _eventAggregator.GetEvent<UserLoginNotification>().Publish(user);
+                    View.DialogResult = true;
+                });
+                
+            }
+        }
+
+        public async void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
+        {
+            if (serialPortProtocol!=null)
+            {
+                serialPortProtocol.DataReceived -= CardSerial_DataReceived;
+            }
+            await serialPortProtocol?.DisconnectAsync();
+            
+            serialPortProtocol?.Dispose();
+            serialPortProtocol = null;
+        }
+
+        async void ExecuteLoginCommand()
+        {
+            if (Users == null || string.IsNullOrEmpty(SelectedUserName))
+                return;
+
+            IsLogining = true;
+            try
+            {
+                if (_systemDatabaseService.GetCurrentUser() != null)
+                {
+                    if (_systemDatabaseService.GetCurrentUser().UserName == SelectedUserName)
+                    {
+                        View.DialogResult = true;
+                        return;
+                    }
+                }
+
+                // authenticate via system database service
+                var user = await _systemDatabaseService.AuthenticateUserAsync(SelectedUserName, Password);
+                if (user != null)
+                {
+                    // set remember flag via system database service
+                    try
+                    {
+                        if (IsRemember)
+                            await _systemDatabaseService.SetRememberUserAsync(SelectedUserName);
+                        else
+                            await _systemDatabaseService.ClearRememberUserAsync();
+                    }
+                    catch
+                    {
+
+                    }
+
+                    // mark current user in system DB and record login
+                    await _systemDatabaseService.SetCurrentUserAsync(user.Id);
+                    await _systemDatabaseService.RecordUserLoginAsync(new UserLoginRecord { UserId = user.Id, Success = true, Time = DateTime.UtcNow, Message = "Login success" });
+                    _eventAggregator.GetEvent<UserLoginNotification>().Publish(user);
+                    View.DialogResult = true;
+                }
+
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message);
+            }
+            finally
+            {
+                IsLogining = false;
+            }
+        }
+
+        bool CanExecuteLoginCommand()
+        {
+            return !string.IsNullOrEmpty(SelectedUserName) && !IsLogining;
+        }
+
+        void ExecuteCloseCommand()
+        {
+            View.DialogResult = false;
+        }
+
+        void ExecuteTransitionerCommand(string parameter)
+        {
+            PageIndex = int.Parse(parameter);
+        }
+
+        public void SetModel(bool isAdmin)
+        {
+            PageIndex = isAdmin ? 1 : 0;
+            CardBtnVisibility = isAdmin ? Visibility.Collapsed : Visibility.Visible;
+        }
+        #endregion
+    }
+}

+ 32 - 14
TeamAAS-VM/ViewModels/User/LoginViewModel.cs

@@ -11,12 +11,13 @@ using System.Collections.ObjectModel;
 using System.Data.Entity;
 using System.Linq;
 using System.Threading.Tasks;
+using TeamAAS_VP.Core;
 using TeamAAS_VP.Data;
 using TeamAAS_VP.Events;
-using TeamAAS_VP.Core;
+using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Resources.Languages;
-using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Views.User;
 
 namespace TeamAAS_VP.ViewModels.User
 {
@@ -25,8 +26,7 @@ namespace TeamAAS_VP.ViewModels.User
         private readonly IRegionManager _regionManager;
         private readonly IEventAggregator _eventAggregator;
         private readonly IContainerProvider _container;
-        private readonly ISystemDatabaseService _systemDb;
-		ISystemDatabaseService _systemDatabaseService;
+        private readonly ISystemDatabaseService _systemDatabaseService;
 
 		private List<TeamAAS_VP.Models.User> Users;
         #region 属性
@@ -59,18 +59,23 @@ namespace TeamAAS_VP.ViewModels.User
         /// </summary>
         public DelegateCommand LoginCommand { get; set; }
         public DelegateCommand LoadedCommand { get; set; }
+
+        private DelegateCommand _CardLoginCommand;
+        public DelegateCommand CardLoginCommand =>
+            _CardLoginCommand ?? (_CardLoginCommand = new DelegateCommand(ExecuteCardLoginCommand));
+
+        
         #endregion
 
         #region 事件
 
         #endregion
 
-        public LoginViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, ISystemDatabaseService systemDb,ISystemDatabaseService systemDatabaseService)
+        public LoginViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, ISystemDatabaseService systemDatabaseService)
         {
             _regionManager = regionManager;
             _eventAggregator = ea;
             _container = container;
-            _systemDb = systemDb;
             _systemDatabaseService = systemDatabaseService;
 
 			LoadedCommand = new DelegateCommand(OnLoad);
@@ -82,7 +87,7 @@ namespace TeamAAS_VP.ViewModels.User
             // load users from system database (sync-block safe call)
             try
             {
-                Users = _systemDb.GetAllUsersAsync().GetAwaiter().GetResult()?.ToList();
+                Users = _systemDatabaseService.GetAllUsersAsync().GetAwaiter().GetResult()?.ToList();
             }
             catch
             {
@@ -128,16 +133,16 @@ namespace TeamAAS_VP.ViewModels.User
             try
             {
                 // authenticate via system database service
-                var user = await _systemDb.AuthenticateUserAsync(SelectedUserName, UserPassword);
+                var user = await _systemDatabaseService.AuthenticateUserAsync(SelectedUserName, UserPassword);
                 if (user != null)
                 {
                     // set remember flag via system database service
                     try
                     {
                         if (IsRemember)
-                            await _systemDb.SetRememberUserAsync(SelectedUserName);
+                            await _systemDatabaseService.SetRememberUserAsync(SelectedUserName);
                         else
-                            await _systemDb.ClearRememberUserAsync();
+                            await _systemDatabaseService.ClearRememberUserAsync();
                     }
                     catch
                     {
@@ -145,8 +150,8 @@ namespace TeamAAS_VP.ViewModels.User
                     }
 
                     // mark current user in system DB and record login
-                    await _systemDb.SetCurrentUserAsync(user.Id);
-                    await _systemDb.RecordUserLoginAsync(new UserLoginRecord { UserId = user.Id, Success = true, Time = DateTime.UtcNow, Message = "Login success" });
+                    await _systemDatabaseService.SetCurrentUserAsync(user.Id);
+                    //await _systemDatabaseService.RecordUserLoginAsync(new UserLoginRecord { UserId = user.Id, Success = true, Time = DateTime.UtcNow, Message = "Login success" });
 
                     _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = $"{Lang.登录成功}!", Duration = 1 });
                     _eventAggregator.GetEvent<UserLoginNotification>().Publish(user);
@@ -155,7 +160,7 @@ namespace TeamAAS_VP.ViewModels.User
             catch (Exception ex)
             {
                 // authentication failed or error
-                await _systemDb.RecordUserLoginAsync(new UserLoginRecord { UserId = 0, Success = false, Time = DateTime.UtcNow, Message = $"Login failed for {SelectedUserName}: {ex.Message}" });
+                await _systemDatabaseService.RecordUserLoginAsync(new UserLoginRecord { UserId = 0, Success = false, Time = DateTime.UtcNow, Message = $"Login failed for {SelectedUserName}: {ex.Message}" });
                 _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.密码错误, Duration = 1 });
             }
         }
@@ -186,7 +191,7 @@ namespace TeamAAS_VP.ViewModels.User
             //获取所有用户
             try
             {
-                Users = _systemDb.GetAllUsersAsync().GetAwaiter().GetResult()?.ToList();
+                Users = _systemDatabaseService.GetAllUsersAsync().GetAwaiter().GetResult()?.ToList();
             }
             catch
             {
@@ -213,6 +218,19 @@ namespace TeamAAS_VP.ViewModels.User
                 IsRemember = true;
             }
         }
+
+        /// <summary>
+        /// 刷卡登录命令
+        /// </summary>
+        void ExecuteCardLoginCommand()
+        {
+            var cardLogin = _container.Resolve<CardLoginWindow>();
+            var result = cardLogin.ShowDialog();
+            if (result is bool st1 && !st1)
+            {
+                
+            }
+        }
         #endregion
     }
 }

+ 145 - 0
TeamAAS-VM/Views/Home/AddScrew.xaml

@@ -0,0 +1,145 @@
+<UserControl x:Class="TeamAAS_VP.Views.Home.AddScrew"
+             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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:enums="clr-namespace:TeamAAS_VP.Enums"
+             xmlns:valRules="clr-namespace:TeamAAS_VP.Identity"
+             xmlns:ext="clr-namespace:TeamAAS_VP.Extension"
+             xmlns:c="clr-namespace:TeamAAS_VP.ValueConverter"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             xmlns:vm="clr-namespace:TeamAAS_VP.ViewModels.Home"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:Background="White"
+             d:DataContext="{d:DesignInstance Type=vm:AddScrewViewModel}"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             FontFamily="{DynamicResource DefaultFont}">
+    <prism:Dialog.WindowStyle>
+        <Style TargetType="Window">
+            <Setter Property="prism:Dialog.WindowStartupLocation"
+                    Value="CenterScreen" />
+            <!--<Setter Property="WindowChrome.WindowChrome">
+            <Setter.Value>
+                <WindowChrome CaptionHeight="0"
+                              ResizeBorderThickness="1" />
+            </Setter.Value>
+        </Setter>-->
+            <Setter Property="WindowStyle"
+                    Value="None" />
+            <Setter Property="AllowDrop"
+                    Value="True" />
+            <Setter Property="BorderThickness"
+                    Value="0" />
+            <Setter Property="ShowInTaskbar"
+                    Value="False" />
+            <Setter Property="SizeToContent"
+                    Value="WidthAndHeight" />
+            <Setter Property="WindowState"
+                    Value="Normal" />
+            <Setter Property="Topmost"
+                    Value="True" />
+        </Style>
+    </prism:Dialog.WindowStyle>
+
+    <Grid Margin="16">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+        </Grid.RowDefinitions>
+        <Grid.ColumnDefinitions>
+            <ColumnDefinition Width="Auto" />
+            <ColumnDefinition Width="*" />
+        </Grid.ColumnDefinitions>
+
+        <TextBlock Grid.Row="0"
+                   Grid.Column="0"
+                   Text="选择供料器:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <ComboBox Grid.Row="0"
+                  Grid.Column="1"
+                  ItemsSource="{Binding ScrewFeeders}"
+                  SelectedItem="{Binding SelectedFeeder}"
+                  DisplayMemberPath="Name"
+                  Margin="4">
+            <b:Interaction.Triggers>
+                <b:EventTrigger EventName="SelectionChanged">
+                    <b:InvokeCommandAction Command="{Binding FeederSelectedCommand}" />
+                </b:EventTrigger>
+            </b:Interaction.Triggers>
+        </ComboBox>
+
+        <TextBlock Grid.Row="1"
+                   Grid.Column="0"
+                   Text="当前批号:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="1"
+                   Grid.Column="1"
+                   Text="{Binding CurrentBatchNumber}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="2"
+                   Grid.Column="0"
+                   Text="剩余数量:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="2"
+                   Grid.Column="1"
+                   Text="{Binding RemainingCount}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="3"
+                   Grid.Column="0"
+                   Text="上次添加时间:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="3"
+                   Grid.Column="1"
+                   Text="{Binding LastAddTime}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="4"
+                   Grid.Column="0"
+                   Text="添加批号:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBox Grid.Row="4"
+                 Grid.Column="1"
+                 Text="{Binding NewBatchNumber,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
+                 Margin="4" />
+
+        <StackPanel Grid.Row="5"
+                    Grid.ColumnSpan="2"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Right"
+                    Margin="4">
+            <Button Style="{StaticResource MaterialDesignRaisedButton}"
+                    Content="清零"
+                    Command="{Binding ClearCommand}"
+                    Margin="4" />
+            <Button Style="{StaticResource MaterialDesignRaisedButton}"
+                    Content="添加"
+                    Command="{Binding AddCommand}"
+                    Margin="4" />
+            <Button Style="{StaticResource MaterialDesignRaisedButton}"
+                    Content="关闭"
+                    Command="{Binding CloseCommand}"
+                    Margin="4" />
+        </StackPanel>
+    </Grid>
+</UserControl>

+ 15 - 0
TeamAAS-VM/Views/Home/AddScrew.xaml.cs

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

+ 123 - 0
TeamAAS-VM/Views/Home/ChangeHeader.xaml

@@ -0,0 +1,123 @@
+<UserControl x:Class="TeamAAS_VP.Views.Home.ChangeHeader"
+             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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:enums="clr-namespace:TeamAAS_VP.Enums"
+             xmlns:valRules="clr-namespace:TeamAAS_VP.Identity"
+             xmlns:ext="clr-namespace:TeamAAS_VP.Extension"
+             xmlns:c="clr-namespace:TeamAAS_VP.ValueConverter"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             xmlns:vm="clr-namespace:TeamAAS_VP.ViewModels.Home"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:Background="White"
+             d:DataContext="{d:DesignInstance Type=vm:ChangeHeaderViewModel}"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             FontFamily="{DynamicResource DefaultFont}">
+    <prism:Dialog.WindowStyle>
+        <Style TargetType="Window">
+            <Setter Property="prism:Dialog.WindowStartupLocation"
+                    Value="CenterScreen" />
+            <!--<Setter Property="WindowChrome.WindowChrome">
+        <Setter.Value>
+            <WindowChrome CaptionHeight="0"
+                          ResizeBorderThickness="1" />
+        </Setter.Value>
+    </Setter>-->
+            <Setter Property="WindowStyle"
+                    Value="None" />
+            <Setter Property="AllowDrop"
+                    Value="True" />
+            <Setter Property="BorderThickness"
+                    Value="0" />
+            <Setter Property="ShowInTaskbar"
+                    Value="False" />
+            <Setter Property="SizeToContent"
+                    Value="WidthAndHeight" />
+            <Setter Property="WindowState"
+                    Value="Normal" />
+            <Setter Property="Topmost"
+                    Value="True" />
+        </Style>
+    </prism:Dialog.WindowStyle>
+
+    <Grid Margin="16">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition  Height="Auto" />
+        </Grid.RowDefinitions>
+        <Grid.ColumnDefinitions>
+            <ColumnDefinition Width="Auto" />
+            <ColumnDefinition Width="*" />
+        </Grid.ColumnDefinitions>
+
+        <TextBlock Grid.Row="0"
+                   Grid.Column="0"
+                   Text="当前披头批号:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="0"
+                   Grid.Column="1"
+                   Text="{Binding CurrentHeadBatchNumber}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="1"
+                   Grid.Column="0"
+                   Text="当前锁付次数:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="1"
+                   Grid.Column="1"
+                   Text="{Binding CurrentLockCount}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="2"
+                   Grid.Column="0"
+                   Text="上次更换时间:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="2"
+                   Grid.Column="1"
+                   Text="{Binding LastChangeTime}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="3"
+                   Grid.Column="0"
+                   Text="新披头批号:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBox Grid.Row="3"
+                 Grid.Column="1"
+                 MinWidth="150"
+                 Text="{Binding NewHeadBatchNumber,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
+                 Margin="4" />
+
+        <StackPanel Grid.Row="4"
+                    Grid.ColumnSpan="2"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Right"
+                    Margin="4">
+            <Button Style="{StaticResource MaterialDesignRaisedButton}"
+                    Content="更换"
+                    Command="{Binding ReplaceCommand}"
+                    Margin="4" />
+            <Button Style="{StaticResource MaterialDesignRaisedButton}"
+                    Content="关闭"
+                    Command="{Binding CloseCommand}"
+                    Margin="4" />
+        </StackPanel>
+    </Grid>
+</UserControl>

+ 15 - 0
TeamAAS-VM/Views/Home/ChangeHeader.xaml.cs

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

+ 123 - 0
TeamAAS-VM/Views/Home/ChangeNozzle.xaml

@@ -0,0 +1,123 @@
+<UserControl x:Class="TeamAAS_VP.Views.Home.ChangeNozzle"
+             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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:enums="clr-namespace:TeamAAS_VP.Enums"
+             xmlns:valRules="clr-namespace:TeamAAS_VP.Identity"
+             xmlns:ext="clr-namespace:TeamAAS_VP.Extension"
+             xmlns:c="clr-namespace:TeamAAS_VP.ValueConverter"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             xmlns:vm="clr-namespace:TeamAAS_VP.ViewModels.Home"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:Background="White"
+             d:DataContext="{d:DesignInstance Type=vm:ChangeNozzleViewModel}"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             FontFamily="{DynamicResource DefaultFont}">
+    <prism:Dialog.WindowStyle>
+        <Style TargetType="Window">
+            <Setter Property="prism:Dialog.WindowStartupLocation"
+                    Value="CenterScreen" />
+            <!--<Setter Property="WindowChrome.WindowChrome">
+    <Setter.Value>
+        <WindowChrome CaptionHeight="0"
+                      ResizeBorderThickness="1" />
+    </Setter.Value>
+</Setter>-->
+            <Setter Property="WindowStyle"
+                    Value="None" />
+            <Setter Property="AllowDrop"
+                    Value="True" />
+            <Setter Property="BorderThickness"
+                    Value="0" />
+            <Setter Property="ShowInTaskbar"
+                    Value="False" />
+            <Setter Property="SizeToContent"
+                    Value="WidthAndHeight" />
+            <Setter Property="WindowState"
+                    Value="Normal" />
+            <Setter Property="Topmost"
+                    Value="True" />
+        </Style>
+    </prism:Dialog.WindowStyle>
+
+    <Grid Margin="16">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+        </Grid.RowDefinitions>
+        <Grid.ColumnDefinitions>
+            <ColumnDefinition Width="Auto" />
+            <ColumnDefinition Width="*" />
+        </Grid.ColumnDefinitions>
+
+        <TextBlock Grid.Row="0"
+                   Grid.Column="0"
+                   Text="当前吸嘴批号:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="0"
+                   Grid.Column="1"
+                   Text="{Binding CurrentNozzleBatchNumber}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="1"
+                   Grid.Column="0"
+                   Text="当前锁付次数:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="1"
+                   Grid.Column="1"
+                   Text="{Binding CurrentLockCount}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="2"
+                   Grid.Column="0"
+                   Text="上次更换时间:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBlock Grid.Row="2"
+                   Grid.Column="1"
+                   Text="{Binding LastChangeTime}"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+
+        <TextBlock Grid.Row="3"
+                   Grid.Column="0"
+                   Text="新吸嘴批号:"
+                   VerticalAlignment="Center"
+                   Margin="4" />
+        <TextBox Grid.Row="3"
+                 Grid.Column="1"
+                 MinWidth="150"
+                 Text="{Binding NewNozzleBatchNumber,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
+                 Margin="4" />
+
+        <StackPanel Grid.Row="4"
+                    Grid.ColumnSpan="2"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Right"
+                    Margin="4">
+            <Button Style="{StaticResource MaterialDesignRaisedButton}"
+                    Content="更换"
+                    Command="{Binding ReplaceCommand}"
+                    Margin="4" />
+            <Button Style="{StaticResource MaterialDesignRaisedButton}"
+                    Content="关闭"
+                    Command="{Binding CloseCommand}"
+                    Margin="4" />
+        </StackPanel>
+    </Grid>
+</UserControl>

+ 15 - 0
TeamAAS-VM/Views/Home/ChangeNozzle.xaml.cs

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

+ 0 - 94
TeamAAS-VM/Views/Home/SetAlarmValue.xaml

@@ -1,94 +0,0 @@
-<UserControl x:Class="TeamAAS_VP.Views.Home.SetAlarmValue"
-             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
-             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
-             xmlns:local="clr-namespace:TeamAAS_VP.Views.Home"
-             mc:Ignorable="d" 
-             xmlns:prism="http://prismlibrary.com/"
-             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
-             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
-             xmlns:sys="clr-namespace:System;assembly=mscorlib"
-             xmlns:enums="clr-namespace:TeamAAS_VP.Enums"
-             xmlns:uControl="clr-namespace:TeamAAS_VP.Controls"
-             xmlns:convert="clr-namespace:TeamAAS_VP.ValueConverter"
-             xmlns:valRules="clr-namespace:TeamAAS_VP.Identity"
-             xmlns:validationRule="clr-namespace:TeamAAS_VP.ValidationRules"
-             xmlns:ext="clr-namespace:TeamAAS_VP.Extension"
-             xmlns:lex="http://wpflocalizeextension.codeplex.com"
-             xmlns:vm="clr-namespace:TeamAAS_VP.ViewModels.Home"
-             lex:LocalizeDictionary.DesignCulture="zh-CN"
-             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
-             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
-             d:Background="White"
-             d:DataContext="{d:DesignInstance Type=vm:SetAlarmValueViewModel}"
-             prism:ViewModelLocator.AutoWireViewModel="True"
-             FontFamily="{DynamicResource DefaultFont}">
-    <Grid HorizontalAlignment="Center">
-        <Grid.RowDefinitions>
-            <RowDefinition />
-            <RowDefinition />
-            <RowDefinition />
-            <RowDefinition />
-        </Grid.RowDefinitions>
-        <Grid.ColumnDefinitions>
-            <ColumnDefinition />
-            <ColumnDefinition />
-        </Grid.ColumnDefinitions>
-        <TextBlock Text="{lex:Loc 设置批头吸嘴报警值}"
-                   FontSize="20" 
-                   HorizontalAlignment="Center"
-                   Margin="50,30"
-                   Grid.ColumnSpan="2"/>
-
-        <TextBlock Text="{lex:Loc 设置批头报警值}"
-                   FontSize="14"
-                   HorizontalAlignment="Right"
-                   Margin="10"
-                   Grid.Row="1"
-                   Grid.Column="0"/>
-
-        <TextBlock Text="{lex:Loc 设置吸嘴报警值}"
-                   FontSize="14"
-                   HorizontalAlignment="Right"
-                   Margin="10"
-                   Grid.Row="2"
-                   Grid.Column="0" />
-
-        <TextBox Text="{Binding BitAlarmValue}"
-                 FontSize="14"
-                 HorizontalAlignment="Left"
-                 Margin="10"
-                 Grid.Row="1"
-                 Grid.Column="1"
-                 Width="100"/>
-
-        <TextBox Text="{Binding NozzleAlarmValue}"
-                 FontSize="14"
-                 HorizontalAlignment="Left"
-                 Margin="10"
-                 Grid.Row="2"
-                 Grid.Column="1"
-                 Width="100" />
-
-        <StackPanel Orientation="Horizontal"
-                    Margin="10,3"
-                    HorizontalAlignment="Right"
-                    Grid.Row="3"
-                    Grid.ColumnSpan="2">
-            <Button Content="{lex:Loc 确定}"
-                    VerticalContentAlignment="Center"
-                    materialDesign:ButtonAssist.CornerRadius="10"
-                    Style="{StaticResource MaterialDesignRaisedDarkButton}"
-                    Command="{Binding ConfirmCommand}"
-                    Margin="10,3" />
-            <Button Content="{lex:Loc 取消}"
-                    VerticalContentAlignment="Center"
-                    materialDesign:ButtonAssist.CornerRadius="10"
-                    Style="{StaticResource MaterialDesignRaisedDarkButton}"
-                    Command="{Binding CancelCommand}"
-                    Margin="10,3" />
-        </StackPanel>
-
-    </Grid>
-</UserControl>

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

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

+ 65 - 0
TeamAAS-VM/Views/Home/ShowVisionRender.xaml.cs

@@ -21,6 +21,7 @@ using TeamAAS_VP.Events;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.Services;
 using TeamAAS_VP.ViewModels;
 using TeamAAS_VP.ViewModels.Home;
 using static MaterialDesignThemes.Wpf.Theme.ToolBar;
@@ -37,6 +38,8 @@ namespace TeamAAS_VP.Views.Home
         Dictionary<Guid, TextBlock> Titles;
         IEventAggregator _eventAggregator;
         ISystemDatabaseService _systemDatabaseService;
+        IProductService _productService;
+
         public ShowVisionRender()
         {
             InitializeComponent();
@@ -45,6 +48,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);
@@ -889,6 +893,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 +960,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 +1036,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));    //创建文件夹

+ 14 - 7
TeamAAS-VM/Views/HomeView.xaml

@@ -15,8 +15,8 @@
              lex:ResxLocalizationProvider.DefaultDictionary="Lang"
              prism:ViewModelLocator.AutoWireViewModel="True"
              mc:Ignorable="d"
-             d:Height="600"
-             d:Width="1024"
+             d:Height="1080"
+             d:Width="1920"
              d:Background="White"
              d:DataContext="{d:DesignInstance Type=vm:HomeViewModel}"
              Background="Transparent"
@@ -328,7 +328,7 @@
                                FontWeight="Bold"
                                FontSize="{DynamicResource Font.Size.Body2}"
                                VerticalAlignment="Center" />
-                    <TextBlock Text="{Binding CTTotalSeconds,StringFormat={}{0:F2} s}"
+                    <TextBlock Text="{Binding management.CTtime,StringFormat={}{0:F2} s}"
                                FontSize="{DynamicResource Font.Size.Body3}"
                                VerticalAlignment="Center"
                                Margin="10,0" />
@@ -351,17 +351,24 @@
                             Style="{StaticResource MaterialDesignRaisedButton}"
                             Command="{Binding ResetCounterCommand}"
                             IsEnabled="{Binding IsAllowEdit}" />
-                    <Button Content="{lex:Loc 批头吸嘴计数清零}"
+                    <Button Content="添加螺丝"
                             Margin="3"
                             materialDesign:ButtonAssist.CornerRadius="10"
                             Style="{StaticResource MaterialDesignRaisedButton}"
-                            Command="{Binding NozzleCounterResetCommand}"
+                            Command="{Binding AddScrewCommand}"
+                            IsEnabled="{Binding IsAllowEdit}" /> 
+
+                    <Button Content="更换披头"
+                            Margin="3"
+                            materialDesign:ButtonAssist.CornerRadius="10"
+                            Style="{StaticResource MaterialDesignRaisedButton}"
+                            Command="{Binding ChangeHeaderCommand}"
                             IsEnabled="{Binding IsAllowEdit}" />
-                    <Button Content="{lex:Loc 设置批头吸嘴报警值}"
+                    <Button Content="更换吸嘴"
                             Margin="3"
                             materialDesign:ButtonAssist.CornerRadius="10"
                             Style="{StaticResource MaterialDesignRaisedButton}"
-                            Command="{Binding SetAlarmValueCommand}"
+                            Command="{Binding ChangeNozzleCommand}"
                             IsEnabled="{Binding IsAllowEdit}" />
                 </StackPanel>
 

+ 319 - 0
TeamAAS-VM/Views/Product/PlcPointOffserParams.xaml

@@ -0,0 +1,319 @@
+<UserControl x:Class="TeamAAS_VP.Views.Product.PlcPointOffserParams"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:system="clr-namespace:System;assembly=mscorlib"
+             xmlns:local="clr-namespace:TeamAAS_VP.Controls"
+             xmlns:vm="clr-namespace:TeamAAS_VP.ViewModels.Product"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="768"
+             d:DesignWidth="1024"
+             d:Background="White"
+             MaxHeight="1000"
+             MaxWidth="1840"
+             d:DataContext="{d:DesignInstance Type=vm:PlcPointOffserParamsViewModel}"
+             FontFamily="{DynamicResource DefaultFont}">
+    <prism:Dialog.WindowStyle>
+        <Style TargetType="Window">
+            <Setter Property="prism:Dialog.WindowStartupLocation"
+                    Value="CenterScreen" />
+            <!--<Setter Property="WindowChrome.WindowChrome">
+            <Setter.Value>
+                <WindowChrome CaptionHeight="0"
+                              ResizeBorderThickness="1" />
+            </Setter.Value>
+        </Setter>-->
+            <Setter Property="WindowStyle"
+                    Value="None" />
+            <Setter Property="AllowDrop"
+                    Value="True" />
+            <Setter Property="BorderThickness"
+                    Value="0" />
+            <Setter Property="ShowInTaskbar"
+                    Value="False" />
+            <Setter Property="SizeToContent"
+                    Value="WidthAndHeight" />
+            <Setter Property="WindowState"
+                    Value="Normal" />
+            <Setter Property="Topmost"
+                    Value="True" />
+        </Style>
+    </prism:Dialog.WindowStyle>
+    <Grid Margin="16">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="auto" />
+            <RowDefinition Height="*" />
+            <RowDefinition Height="auto" />
+        </Grid.RowDefinitions>
+        <TextBlock Text="{Binding Title}"
+                   FontSize="16"
+                   FontWeight="Bold"
+                   Margin="0,10"
+                   VerticalAlignment="Center"
+                   TextAlignment="Left"
+                   HorizontalAlignment="Left" />
+        <!--点位表-->
+        <Border Grid.Row="1"
+                BorderBrush="#D0D0D0"
+                BorderThickness="1"
+                Margin="0,5">
+            <DataGrid x:Name="dgPoints"
+                      AutoGenerateColumns="False"
+                      CanUserAddRows="False"
+                      CanUserDeleteRows="False"
+                      ColumnWidth="*"
+                      SelectionUnit="FullRow"
+                      SelectionMode="Single"
+                      ItemsSource="{Binding Points}"
+                      HeadersVisibility="Column"
+                      HorizontalScrollBarVisibility="Auto"
+                      ScrollViewer.CanContentScroll="True"
+                      ScrollViewer.HorizontalScrollBarVisibility="Auto"
+                      GridLinesVisibility="All"
+                      VerticalGridLinesBrush="#D0D0D0">
+                <DataGrid.Resources>
+                    <Style TargetType="DataGridCell">
+                        <Style.Resources>
+                            <SolidColorBrush  x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
+                                              Color="#0078D7" />
+                        </Style.Resources>
+                        <Setter Property="MinHeight"
+                                Value="25" />
+                        <Setter Property="VerticalContentAlignment"
+                                Value="Center" />
+                        <Setter Property="HorizontalContentAlignment"
+                                Value="Center" />
+                        <Setter Property="VerticalAlignment"
+                                Value="Center" />
+                        <Setter Property="TextBlock.TextAlignment"
+                                Value="Center" />
+                        <Setter Property="Padding"
+                                Value="0" />
+                        <Style.Triggers>
+                            <Trigger Property="IsSelected"
+                                     Value="True">
+                                <Setter Property="Foreground"
+                                        Value="White" />
+                            </Trigger>
+                        </Style.Triggers>
+                    </Style>
+
+                    <!-- 为 TextBlock 添加默认居中样式 -->
+                    <Style TargetType="TextBlock">
+                        <Setter Property="TextAlignment"
+                                Value="Center" />
+                        <Setter Property="HorizontalAlignment"
+                                Value="Center" />
+                        <Setter Property="VerticalAlignment"
+                                Value="Center" />
+                    </Style>
+                </DataGrid.Resources>
+                <DataGrid.Columns>
+                    <DataGridTextColumn Header="{lex:Loc 编号}"
+                                        IsReadOnly="True"
+                                        MinWidth="60"
+                                        Width="Auto"
+                                        Binding="{Binding Number, Mode=TwoWay, StringFormat={}{0:F0}}">
+                    </DataGridTextColumn>
+                    <DataGridTextColumn Header="{lex:Loc 标签}"
+                                        MinWidth="100"
+                                        Width="Auto"
+                                        Binding="{Binding Label, Mode=TwoWay}" />
+                    <!--X 坐标-->
+                    <DataGridTemplateColumn Header="X补偿"
+                                            MinWidth="60"
+                                            Width="Auto">
+                        <DataGridTemplateColumn.CellTemplate>
+                            <DataTemplate>
+                                <TextBlock Text="{Binding X_Offset, StringFormat={}{0:F3}}"
+                                           HorizontalAlignment="Center"
+                                           VerticalAlignment="Center" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellTemplate>
+                        <DataGridTemplateColumn.CellEditingTemplate>
+                            <DataTemplate>
+                                <mah:NumericUpDown Value="{Binding X_Offset, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+                                                   Minimum="-9999.000"
+                                                   Maximum="9999.000"
+                                                   Interval="0.1"
+                                                   StringFormat="F3"
+                                                   HorizontalAlignment="Stretch"
+                                                   VerticalAlignment="Center"
+                                                   Margin="0"
+                                                   Padding="2" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellEditingTemplate>
+                    </DataGridTemplateColumn>
+                    <!--Y 坐标-->
+                    <DataGridTemplateColumn Header="Y补偿"
+                                            MinWidth="60"
+                                            Width="Auto">
+                        <DataGridTemplateColumn.CellTemplate>
+                            <DataTemplate>
+                                <TextBlock Text="{Binding Y_Offset, StringFormat={}{0:F3}}"
+                                           HorizontalAlignment="Center"
+                                           VerticalAlignment="Center" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellTemplate>
+                        <DataGridTemplateColumn.CellEditingTemplate>
+                            <DataTemplate>
+                                <mah:NumericUpDown Value="{Binding Y_Offset, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+                                                   Minimum="-9999.000"
+                                                   Maximum="9999.000"
+                                                   Interval="0.1"
+                                                   StringFormat="F3"
+                                                   HorizontalAlignment="Stretch"
+                                                   VerticalAlignment="Center"
+                                                   Margin="0"
+                                                   Padding="2" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellEditingTemplate>
+                    </DataGridTemplateColumn>
+                    <!--Z 起点坐标-->
+                    <DataGridTemplateColumn Header="Z起点补偿"
+                                            MinWidth="60"
+                                            Width="Auto">
+                        <DataGridTemplateColumn.CellTemplate>
+                            <DataTemplate>
+                                <TextBlock Text="{Binding Z_Start_Offset, StringFormat={}{0:F3}}"
+                                           HorizontalAlignment="Center"
+                                           VerticalAlignment="Center" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellTemplate>
+                        <DataGridTemplateColumn.CellEditingTemplate>
+                            <DataTemplate>
+                                <mah:NumericUpDown Value="{Binding Z_Start_Offset, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+                                                   Minimum="-9999.000"
+                                                   Maximum="9999.000"
+                                                   Interval="0.1"
+                                                   StringFormat="F3"
+                                                   HorizontalAlignment="Stretch"
+                                                   VerticalAlignment="Center"
+                                                   Margin="0"
+                                                   Padding="2" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellEditingTemplate>
+                    </DataGridTemplateColumn>
+                    <!--Z 终点坐标-->
+                    <DataGridTemplateColumn Header="Z终点补偿"
+                                            MinWidth="60"
+                                            Width="Auto">
+                        <DataGridTemplateColumn.CellTemplate>
+                            <DataTemplate>
+                                <TextBlock Text="{Binding Z_Stop_Offset, StringFormat={}{0:F3}}"
+                                           HorizontalAlignment="Center"
+                                           VerticalAlignment="Center" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellTemplate>
+                        <DataGridTemplateColumn.CellEditingTemplate>
+                            <DataTemplate>
+                                <mah:NumericUpDown Value="{Binding Z_Stop_Offset, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+                                                   Minimum="-9999.000"
+                                                   Maximum="9999.000"
+                                                   Interval="0.1"
+                                                   StringFormat="F3"
+                                                   HorizontalAlignment="Stretch"
+                                                   VerticalAlignment="Center"
+                                                   Margin="0"
+                                                   Padding="2" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellEditingTemplate>
+                    </DataGridTemplateColumn>
+                    <!--U 坐标-->
+                    <DataGridTemplateColumn Header="U补偿"
+                                            MinWidth="60"
+                                            Width="Auto">
+                        <DataGridTemplateColumn.CellTemplate>
+                            <DataTemplate>
+                                <TextBlock Text="{Binding U_Offset, StringFormat={}{0:F3}}"
+                                           HorizontalAlignment="Center"
+                                           VerticalAlignment="Center" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellTemplate>
+                        <DataGridTemplateColumn.CellEditingTemplate>
+                            <DataTemplate>
+                                <mah:NumericUpDown Value="{Binding U_Offset, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+                                                   Minimum="-9999.000"
+                                                   Maximum="9999.000"
+                                                   Interval="0.1"
+                                                   StringFormat="F3"
+                                                   HorizontalAlignment="Stretch"
+                                                   VerticalAlignment="Center"
+                                                   Margin="0"
+                                                   Padding="2" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellEditingTemplate>
+                    </DataGridTemplateColumn>
+                    <!--R 坐标-->
+                    <DataGridTemplateColumn Header="R补偿"
+                                            MinWidth="60"
+                                            Width="Auto">
+                        <DataGridTemplateColumn.CellTemplate>
+                            <DataTemplate>
+                                <TextBlock Text="{Binding R_Offset, StringFormat={}{0:F3}}"
+                                           HorizontalAlignment="Center"
+                                           VerticalAlignment="Center" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellTemplate>
+                        <DataGridTemplateColumn.CellEditingTemplate>
+                            <DataTemplate>
+                                <mah:NumericUpDown Value="{Binding R_Offset, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+                                                   Minimum="-9999.000"
+                                                   Maximum="9999.000"
+                                                   Interval="0.1"
+                                                   StringFormat="F3"
+                                                   HorizontalAlignment="Stretch"
+                                                   VerticalAlignment="Center"
+                                                   Margin="0"
+                                                   Padding="2" />
+                            </DataTemplate>
+                        </DataGridTemplateColumn.CellEditingTemplate>
+                    </DataGridTemplateColumn>
+
+                    <DataGridTextColumn Header="{lex:Loc 描述}"
+                                        MinWidth="100"
+                                        Width="200"
+                                        Binding="{Binding Description, Mode=TwoWay}" />
+                </DataGrid.Columns>
+            </DataGrid>
+        </Border>
+        <StackPanel Grid.Row="2"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Right">
+            <!--清除所有补偿-->
+            <Button Height="30"
+                    Margin="0,0,20,0"
+                    materialDesign:ButtonAssist.CornerRadius="10"
+                    Style="{StaticResource MaterialDesignRaisedButton}"
+                    ToolTip="清除所有补偿"
+                    Command="{Binding ClearAllOffsetCommand}">
+                <TextBlock Text="清除所有补偿" />
+            </Button>
+
+            <Button Height="30"
+                    materialDesign:ButtonAssist.CornerRadius="10"
+                    Style="{StaticResource MaterialDesignRaisedButton}"
+                    ToolTip="{lex:Loc 确定}"
+                    Command="{Binding ConfirmCommand}">
+                <TextBlock Text="{lex:Loc 确定}" />
+            </Button>
+            <Button Height="30"
+                    Margin="20,0"
+                    materialDesign:ButtonAssist.CornerRadius="10"
+                    Style="{StaticResource MaterialDesignRaisedButton}"
+                    ToolTip="{lex:Loc 取消}"
+                    Command="{Binding CancelCommand}">
+                <TextBlock Text="{lex:Loc 取消}" />
+            </Button>
+        </StackPanel>
+    </Grid>
+</UserControl>

+ 15 - 0
TeamAAS-VM/Views/Product/PlcPointOffserParams.xaml.cs

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

+ 60 - 7
TeamAAS-VM/Views/Product/PlcPointParams.xaml

@@ -125,8 +125,7 @@
                                 Orientation="Horizontal">
                         <TextBlock Text="{lex:Loc 相机,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}"
                                    FontWeight="Bold"
-                                   VerticalAlignment="Center"
-                                   />
+                                   VerticalAlignment="Center" />
                         <ComboBox Margin="5,0,10,0"
                                   IsEnabled="{Binding IsGrap,Converter={StaticResource InvertBooleanConverter}}"
                                   ItemsSource="{Binding CameraList}"
@@ -162,7 +161,7 @@
                                    Foreground="Gray" />
                     </StackPanel>
                 </Grid>
-                
+
             </materialDesign:DrawerHost.LeftDrawerContent>
             <Grid>
                 <Grid.ColumnDefinitions>
@@ -330,6 +329,31 @@
                                     </Style>
                                 </Button.Style>
                             </Button>
+                            <!--设置补偿值-->
+                            <Button Content="设置补偿值"
+                                    Margin="5,2"
+                                    MinWidth="80"
+                                    d:Visibility="Visible"
+                                    materialDesign:ButtonAssist.CornerRadius="5"
+                                    Command="{Binding SetOffsetCommand}">
+                                <!--<Button.Style>
+                                    <Style TargetType="Button"
+                                           BasedOn="{StaticResource MaterialDesignRaisedDarkButton}">
+                                        <Setter Property="Visibility"
+                                                Value="Collapsed" />
+                                        <Style.Triggers>
+                                            -->
+                                <!-- 当 SelectedIndex == 0 时显示此面板 -->
+                                <!--
+                                            <DataTrigger Binding="{Binding SelectedIndex}"
+                                                         Value="1">
+                                                <Setter Property="Visibility"
+                                                        Value="Visible" />
+                                            </DataTrigger>
+                                        </Style.Triggers>
+                                    </Style>
+                                </Button.Style>-->
+                            </Button>
                         </StackPanel>
                         <Border BorderBrush="LightGray"
                                 BorderThickness="1"
@@ -419,7 +443,7 @@
                                             </ComboBox>
                                             <TextBlock Margin="5,0,0,0"
                                                        VerticalAlignment="Center"
-                                                       Text="{lex:Loc 选择要校准的取料位:}" />
+                                                       Text="{lex:Loc 选择要校准的取料位}" />
                                             <ComboBox MinWidth="50"
                                                       Margin="5,0,0,0"
                                                       ItemsSource="{Binding PickPoints}"
@@ -1259,6 +1283,35 @@
                                             </DataTemplate>
                                         </DataGridTemplateColumn.CellEditingTemplate>
                                     </DataGridTemplateColumn>
+                                    <!--视觉流程-->
+                                    <DataGridTemplateColumn x:Name="colProcedure"
+                                                            Header="视觉流程"
+                                                            MinWidth="60"
+                                                            Width="Auto">
+                                        <DataGridTemplateColumn.CellTemplate>
+                                            <DataTemplate>
+                                                <ComboBox MinWidth="50"
+                                                          Margin="5,0,0,0"
+                                                          ItemsSource="{Binding DataContext.ProcedureModels,RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
+                                                          SelectedValuePath="Id"
+                                                          SelectedValue="{Binding VisionProcessID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+                                                          SelectionChanged="ProcedureCombo_SelectionChanged">
+                                                    <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>
+                                            </DataTemplate>
+                                        </DataGridTemplateColumn.CellTemplate>
+                                    </DataGridTemplateColumn>
 
                                     <DataGridTextColumn Header="{lex:Loc 描述}"
                                                         MinWidth="100"
@@ -1286,7 +1339,7 @@
                             <ToggleButton Grid.ColumnSpan="2"
                                           HorizontalAlignment="Left"
                                           VerticalAlignment="Top"
-                                         materialDesign:ToggleButtonAssist.OnContent="{materialDesign:PackIcon Kind=ArrowLeft}"
+                                          materialDesign:ToggleButtonAssist.OnContent="{materialDesign:PackIcon Kind=ArrowLeft}"
                                           Content="{materialDesign:PackIcon Kind=Camera}"
                                           Style="{StaticResource MaterialDesignActionToggleButton}"
                                           ToolTip="{lex:Loc 相机图像}"
@@ -1301,8 +1354,8 @@
                                     <RowDefinition Height="auto" />
                                     <RowDefinition Height="auto" />
                                 </Grid.RowDefinitions>
-                                
-                                
+
+
                                 <Button Content="{lex:Loc 上使能}"
                                         Grid.Row="0"
                                         materialDesign:ButtonAssist.CornerRadius="10"

+ 42 - 0
TeamAAS-VM/Views/Product/PlcPointParams.xaml.cs

@@ -19,12 +19,54 @@ namespace TeamAAS_VP.Views.Product
             InitializeComponent();
             VM = DataContext as PlcPointParamsViewModel;
             VM.PropertyChanged += VM_PropertyChanged;
+            VM.PropertyChanged += Vm_SelectedIndexChanged;
+            // initialize visibility
+            try
+            {
+                if (VM != null && colProcedure != null)
+                    colProcedure.Visibility = VM.SelectedIndex == 3 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
+            }
+            catch { }
             this.display.HorizontalScrollBar = false;
             this.display.VerticalScrollBar = false;
             this.display.AutoFit = true;
             this.display.BackColor = System.Drawing.SystemColors.ActiveCaption;
         }
 
+        private void Vm_SelectedIndexChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
+        {
+            if (e.PropertyName == nameof(PlcPointParamsViewModel.SelectedIndex))
+            {
+                try
+                {
+                    var visible = VM.SelectedIndex == 3 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
+                    this.Dispatcher.BeginInvoke(new Action(() =>
+                    {
+                        if (colProcedure != null)
+                            colProcedure.Visibility = visible;
+                    }));
+                }
+                catch { }
+            }
+        }
+
+        private void ProcedureCombo_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
+        {
+            try
+            {
+                var combo = sender as System.Windows.Controls.ComboBox;
+                if (combo == null) return;
+                var proc = combo.SelectedItem as TeamAAS_VP.Models.ProcedureModel;
+                var point = combo.DataContext as TeamAAS_VP.Models.PLC.PlcPoint;
+                if (point != null && proc != null)
+                {
+                    // SelectedValue binding already sets VisionProcessID; sync name
+                    point.VisionProcessName = proc.Name;
+                }
+            }
+            catch { }
+        }
+
         private int _imageWidth;
         private int _imageHeight;
         private void VM_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)

+ 40 - 5
TeamAAS-VM/Views/Product/VisionDynamicAccuracyAnalyzer.xaml

@@ -27,7 +27,6 @@
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              FontFamily="{DynamicResource DefaultFont}">
-
     <prism:Dialog.WindowStyle>
         <Style TargetType="Window">
             <Setter Property="prism:Dialog.WindowStartupLocation"
@@ -43,7 +42,7 @@
             <Setter Property="WindowState"
                     Value="Maximized" />
             <Setter Property="Topmost"
-                    Value="True" />
+                    Value="False" />
         </Style>
     </prism:Dialog.WindowStyle>
 
@@ -228,7 +227,7 @@
                                    Grid.Column="0"
                                    VerticalAlignment="Center" />
                                     <ComboBox Grid.Column="1"
-                                  ItemsSource="{Binding ProcedureModels}"
+                                  ItemsSource="{Binding ProcedureModels, Mode=TwoWay}"
                                   SelectedItem="{Binding SelectProcedure, Mode=TwoWay}"
                                   ToolTip="选择视觉处理流程">
                                         <ComboBox.ItemTemplate>
@@ -259,6 +258,8 @@
                                 <Grid.ColumnDefinitions>
                                     <ColumnDefinition Width="*" />
                                     <ColumnDefinition Width="*" />
+                                    <ColumnDefinition Width="*" />
+                                    <ColumnDefinition Width="*" />
                                 </Grid.ColumnDefinitions>
 
                                 <!-- 重复次数 -->
@@ -276,7 +277,7 @@
 
                                 <!-- 移动速度 -->
                                 <StackPanel Grid.Column="1"
-                                Margin="10,0,0,0">
+                                            Margin="10,0,0,0">
                                     <TextBlock Text="移动速度(%):" />
                                     <mah:NumericUpDown Value="{Binding MoveSpeed, Mode=TwoWay}"
                                            Minimum="1"
@@ -287,6 +288,32 @@
                                            HorizontalAlignment="Stretch"
                                            IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}" />
                                 </StackPanel>
+
+                                <!-- A点延时 -->
+                                <StackPanel Grid.Column="2"
+                                            Margin="10,0,0,0">
+                                    <TextBlock Text="A点延时(ms):" />
+                                    <mah:NumericUpDown Value="{Binding ADelay, Mode=TwoWay}"
+                                                       Minimum="50"
+                                                       d:Value="300"
+                                                       TextAlignment="Center"
+                                                       HorizontalContentAlignment="Center"
+                                                       HorizontalAlignment="Stretch"
+                                                       IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}" />
+                                </StackPanel>
+
+                                <!-- B点延时 -->
+                                <StackPanel Grid.Column="3"
+                                            Margin="10,0,0,0">
+                                    <TextBlock Text="B点延时(ms):" />
+                                    <mah:NumericUpDown Value="{Binding BDelay, Mode=TwoWay}"
+                                                       Minimum="50"
+                                                       d:Value="500"
+                                                       TextAlignment="Center"
+                                                       HorizontalContentAlignment="Center"
+                                                       HorizontalAlignment="Stretch"
+                                                       IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}" />
+                                </StackPanel>
                             </Grid>
 
 
@@ -302,7 +329,15 @@
                            Text="测试控制" />
 
                             <WrapPanel HorizontalAlignment="Center"
-                           Margin="0 10 0 0">
+                                       Margin="0 10 0 0">
+                                <CheckBox Content="启用拍照"
+                                          Foreground="Black"
+                                          Style="{StaticResource MaterialDesignCheckBox}"
+                                          VerticalAlignment="Center"
+                                          IsChecked="{Binding IsTakePhoto}"
+                                          Margin="10,0"
+                                          FontSize="15"/>
+
                                 <Button Content="单次测试"
                             Background="#3498DB"
                             Foreground="White"

+ 15 - 1
TeamAAS-VM/Views/Product/VisionStaticAccuracyAnalyzer.xaml

@@ -41,7 +41,7 @@
             <Setter Property="WindowState"
                     Value="Maximized" />
             <Setter Property="Topmost"
-                    Value="True" />
+                    Value="False" />
         </Style>
     </prism:Dialog.WindowStyle>
 
@@ -135,6 +135,7 @@
                                 <ColumnDefinition Width="Auto" />
                                 <ColumnDefinition Width="*" />
                                 <ColumnDefinition Width="Auto" />
+                                <ColumnDefinition Width="*" />
                             </Grid.ColumnDefinitions>
 
                             <TextBlock Text="重复次数:"
@@ -147,6 +148,19 @@
                                                HorizontalContentAlignment="Center"
                                                HorizontalAlignment="Stretch"
                                                IsEnabled="{Binding IsRunning,Converter={StaticResource InvertBooleanConverter}}" />
+
+                            <TextBlock Text="延时时间(ms):"
+                                       Grid.Column="2" />
+                            <mah:NumericUpDown Grid.Column="3"
+                                               Value="{Binding DelayTime, Mode=TwoWay}"
+                                               Minimum="50"
+                                               d:Value="200"
+                                               TextAlignment="Center"
+                                               HorizontalContentAlignment="Center"
+                                               HorizontalAlignment="Stretch"
+                                               IsEnabled="{Binding IsRunning,Converter={StaticResource InvertBooleanConverter}}" />
+
+
                             <!--<Button x:Name="btnSetCount"
                                     Grid.Column="2"
                                     Content="设置"

+ 138 - 15
TeamAAS-VM/Views/SettingView.xaml

@@ -1519,7 +1519,14 @@
                                       Grid.Column="1"
                                       Margin="10,0"
                                       SelectedItem="{Binding SelectLightController.LightModel,Mode=TwoWay}"
-                                      ItemsSource="{ext:EnumBindingSource EnumType=coreLights:LightModel}" />
+                                      ItemsSource="{ext:EnumBindingSource EnumType=coreLights:LightModel}">
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="SelectionChanged">
+                                        <b:InvokeCommandAction Command="{Binding LightModelChangedCommand}"
+                                                               CommandParameter="{Binding SelectLightController}"/>
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ComboBox>
 
                             <!-- Channel count -->
                             <TextBlock Text="{lex:Loc 通道数, Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}"
@@ -1580,6 +1587,11 @@
                                                 <Setter Property="Visibility"
                                                         Value="Visible" />
                                             </DataTrigger>
+                                            <DataTrigger Binding="{Binding SelectLightController.LightModel}"
+                                                         Value="{x:Static coreLights:LightModel.KCS_KDC3_24V300W_8T}">
+                                                <Setter Property="Visibility"
+                                                        Value="Visible" />
+                                            </DataTrigger>
                                         </Style.Triggers>
                                     </Style>
                                 </GroupBox.Style>
@@ -1653,6 +1665,11 @@
                                                 <Setter Property="Visibility"
                                                         Value="Collapsed" />
                                             </DataTrigger>
+                                            <DataTrigger Binding="{Binding SelectLightController.LightModel}"
+                                                         Value="{x:Static coreLights:LightModel.KCS_KDC3_24V300W_8T}">
+                                                <Setter Property="Visibility"
+                                                        Value="Collapsed" />
+                                            </DataTrigger>
                                         </Style.Triggers>
                                     </Style>
                                 </GroupBox.Style>
@@ -1735,7 +1752,7 @@
                         </Button>
 
                     </StackPanel>
-                    <!--PLC列表-->
+                    <!--螺丝供料器列表-->
                     <TreeView Grid.Row="1"
                               Grid.Column="0"
                               SelectedItemChanged="TreeView_SelectedItemChanged">
@@ -1812,7 +1829,7 @@
                             </Grid.RowDefinitions>
                             <Grid.ColumnDefinitions>
                                 <ColumnDefinition Width="auto" />
-                                <ColumnDefinition Width="200" />
+                                <ColumnDefinition MinWidth="200" />
                                 <ColumnDefinition Width="*" />
                             </Grid.ColumnDefinitions>
 
@@ -1864,8 +1881,8 @@
                                        VerticalAlignment="Center" />
                             <mah:NumericUpDown Grid.Row="3"
                                                Grid.Column="1"
-                                               Margin="10,0"
-                                               Width="200"
+                                               Margin="10,5"
+                                               MinWidth="200"
                                                Minimum="0"
                                                Maximum="10000"
                                                Value="{Binding SelectScrewFeeder.PackSize,Mode=TwoWay}"
@@ -1881,7 +1898,7 @@
                             <mah:NumericUpDown Grid.Row="4"
                                                Grid.Column="1"
                                                Margin="10,0"
-                                               Width="200"
+                                               MinWidth="200"
                                                Minimum="0"
                                                Maximum="10000"
                                                Value="{Binding SelectScrewFeeder.LowLevelThreshold,Mode=TwoWay}"
@@ -1896,7 +1913,7 @@
                                        Text="是否启用低量报警:" />
                             <CheckBox Grid.Row="5"
                                       Grid.Column="1"
-                                      Margin="10,0"
+                                      Margin="10,5"
                                       IsChecked="{Binding SelectScrewFeeder.LowLevelAlarmEnabled,Mode=TwoWay}"
                                       VerticalAlignment="Center" />
 
@@ -2159,8 +2176,7 @@
                                    HorizontalAlignment="Stretch" />
                     </StackPanel>
                 </TabItem.Header>
-                <StackPanel Orientation="Vertical"
-                            Margin="20">
+                <StackPanel Orientation="Vertical" Margin="20">
                     <Grid>
                         <Grid.ColumnDefinitions>
                             <ColumnDefinition Width="auto" />
@@ -2179,6 +2195,7 @@
                             <RowDefinition Height="Auto" />
                             <RowDefinition Height="Auto" />
                             <RowDefinition Height="Auto" />
+                            <RowDefinition Height="Auto" />
                         </Grid.RowDefinitions>
 
                         <!-- 相机拍照次数 -->
@@ -2339,6 +2356,28 @@
                                            Maximum="100"
                                            FontSize="{DynamicResource Font.Size.Body3}" />
 
+                        <CheckBox Grid.Row="10"
+                                  Grid.Column="0"
+                                  IsChecked="{Binding IsSaveScrewCurve,Mode=TwoWay}"
+                                  VerticalAlignment="Center"
+                                  HorizontalAlignment="Right"
+                                   FontSize="{DynamicResource Font.Size.Body3}"
+                                  Margin="0,0,6,0">保存锁付曲线图</CheckBox>
+                        <!-- 保存锁付曲线设置 -->
+                        <StackPanel Grid.Row="10"
+                                    Grid.Column="1"
+                                    Grid.ColumnSpan="2"
+                                    Orientation="Horizontal"
+                                    VerticalAlignment="Center"
+                                    IsEnabled="{Binding IsSaveScrewCurve,Converter={StaticResource InvertBooleanConverter}}">
+                            <TextBox MinWidth="200"
+                                     Text="{Binding ScrewCurvePath,Mode=TwoWay}" />
+                            <Button Style="{StaticResource MaterialDesignFloatingActionMiniDarkButton}"
+                                    Command="{Binding BrowseScrewCurvePathCommand}"
+                                    Margin="6,0">
+                                <materialDesign:PackIcon Kind="FolderOpen" />
+                            </Button>
+                        </StackPanel>
                         <!-- 保存按钮 -->
                         <StackPanel Grid.Row="10"
                                     Grid.ColumnSpan="2"
@@ -2346,21 +2385,105 @@
                                     HorizontalAlignment="Right"
                                     VerticalAlignment="Center"
                                     Margin="5">
-                            <Button Style="{StaticResource MaterialDesignRaisedButton}"
+
+
+                        </StackPanel>
+                        <Button Grid.Row="11"
+                                Grid.Column="1"
+                                Margin="0,6"
+                                Style="{StaticResource MaterialDesignRaisedButton}"
+                                materialDesign:ButtonAssist.CornerRadius="10"
+                                MinWidth="120"
+                                Command="{Binding SaveSystemParametersCommand}"
+                                IsEnabled="{Binding IsAllowEdit}">
+                            <StackPanel Orientation="Horizontal"
+                                        HorizontalAlignment="Center">
+                                <materialDesign:PackIcon Kind="ContentSaveCheck"
+                                                         Margin="0,0,6,0" />
+                                <TextBlock VerticalAlignment="Center"
+                                           Text="{lex:Loc 保存系统参数}" />
+                            </StackPanel>
+                        </Button>
+                    </Grid>
+                    
+                    <!--刷卡参数配置-->
+                    <GroupBox Grid.Row="5"
+                              Grid.ColumnSpan="2"
+                              Header="刷卡器配置"
+                              HorizontalAlignment="Left"
+                              MinWidth="400"
+                              Margin="0,12,0,0">
+                        <Grid Margin="10">
+                            <Grid.ColumnDefinitions>
+                                <ColumnDefinition Width="auto" />
+                                <ColumnDefinition Width="*" />
+                            </Grid.ColumnDefinitions>
+                            <Grid.RowDefinitions>
+                                <RowDefinition Height="Auto" />
+                                <RowDefinition Height="Auto" />
+                                <RowDefinition Height="Auto" />
+                                <RowDefinition Height="Auto" />
+                                <RowDefinition Height="Auto" />
+                                <RowDefinition Height="Auto" />
+                            </Grid.RowDefinitions>
+                            <TextBlock Text="PortName:"
+                                       Grid.Row="0"
+                                       Grid.Column="0"
+                                       HorizontalAlignment="Right" />
+                            <TextBox Text="{Binding CardReaderConfig.PortName,Mode=TwoWay}"
+                                     Grid.Row="0"
+                                     Grid.Column="1"
+                                     Margin="6,0" />
+                            <TextBlock Text="BaudRate:"
+                                       Grid.Row="1"
+                                       Grid.Column="0"
+                                       HorizontalAlignment="Right" />
+                            <TextBox Text="{Binding CardReaderConfig.BaudRate,Mode=TwoWay}"
+                                     Grid.Row="1"
+                                     Grid.Column="1"
+                                     Margin="6,0" />
+                            <TextBlock Text="Parity:"
+                                       Grid.Row="2"
+                                       Grid.Column="0"
+                                       HorizontalAlignment="Right" />
+                            <ComboBox Grid.Row="2"
+                                      Grid.Column="1"
+                                      SelectedItem="{Binding CardReaderConfig.Parity,Mode=TwoWay}"
+                                      ItemsSource="{Binding Source={StaticResource Parity}}" />
+                            <TextBlock Text="StopBits:"
+                                       Grid.Row="3"
+                                       Grid.Column="0"
+                                       HorizontalAlignment="Right" />
+                            <ComboBox Grid.Row="3"
+                                      Grid.Column="1"
+                                      SelectedItem="{Binding CardReaderConfig.StopBits,Mode=TwoWay}"
+                                      ItemsSource="{Binding Source={StaticResource StopBits}}" />
+                            <TextBlock Text="DataBits:"
+                                       Grid.Row="4"
+                                       Grid.Column="0"
+                                       HorizontalAlignment="Right" />
+                            <TextBox Text="{Binding CardReaderConfig.DataBits,Mode=TwoWay}"
+                                     Grid.Row="4"
+                                     Grid.Column="1"
+                                     Margin="6,0" />
+
+                            <Button Grid.Row="5"
+                                    Grid.Column="1"
+                                    Margin="0,6"
+                                    Style="{StaticResource MaterialDesignRaisedButton}"
                                     materialDesign:ButtonAssist.CornerRadius="10"
                                     MinWidth="120"
-                                    Command="{Binding SaveSystemParametersCommand}"
-                                    IsEnabled="{Binding IsAllowEdit}">
+                                    Command="{Binding SaveCardReaderConfigCommand}">
                                 <StackPanel Orientation="Horizontal"
                                             HorizontalAlignment="Center">
                                     <materialDesign:PackIcon Kind="ContentSaveCheck"
                                                              Margin="0,0,6,0" />
                                     <TextBlock VerticalAlignment="Center"
-                                               Text="{lex:Loc 保存系统参数}" />
+                                               Text="保存刷卡器配置" />
                                 </StackPanel>
                             </Button>
-                        </StackPanel>
-                    </Grid>
+                        </Grid>
+                    </GroupBox>
                 </StackPanel>
             </TabItem>
 

+ 373 - 0
TeamAAS-VM/Views/User/CardLoginWindow.xaml

@@ -0,0 +1,373 @@
+<Window x:Class="TeamAAS_VP.Views.User.CardLoginWindow"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+        xmlns:prism="http://prismlibrary.com/"
+        xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+        xmlns:vm="clr-namespace:TeamAAS_VP.ViewModels.User"
+        xmlns:local="clr-namespace:TeamAAS_VP"
+        xmlns:converter="clr-namespace:TeamAAS_VP.ValueConverter"
+        xmlns:lex="http://wpflocalizeextension.codeplex.com"
+        lex:LocalizeDictionary.DesignCulture="zh-CN"
+        lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+        lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+        mc:Ignorable="d"
+        d:DataContext="{d:DesignInstance Type=vm:CardLoginWindowViewModel}"
+        prism:ViewModelLocator.AutoWireViewModel="True"
+        Background="Transparent"
+        WindowState="Normal"
+        WindowStyle="None"
+        WindowStartupLocation="CenterScreen"
+        AllowsTransparency="True"
+        Width="563"
+        Height="561"
+        FontFamily="{DynamicResource DefaultFont}">
+    <b:Interaction.Triggers>
+        <b:EventTrigger EventName="Loaded">
+            <b:InvokeCommandAction Command="{Binding LoadedCommand}" />
+        </b:EventTrigger>
+        <b:EventTrigger EventName="Closing">
+            <b:CallMethodAction MethodName="Window_Closing"
+                                TargetObject="{Binding}" />
+        </b:EventTrigger>
+    </b:Interaction.Triggers>
+    <Border Width="563"
+            Height="561"
+            CornerRadius="60"
+            BorderBrush="Black"
+            BorderThickness="1">
+        <Border.Background>
+            <LinearGradientBrush EndPoint="0.497,1.007"
+                                 StartPoint="0.494,0.009">
+                <GradientStop Color="#FF309EAF" />
+                <GradientStop Color="White"
+                              Offset="1" />
+            </LinearGradientBrush>
+        </Border.Background>
+        <Grid>
+            <Button Content="X"
+                    FontSize="16"
+                    FontWeight="Bold"
+                    Width="32"
+                    Height="32"
+                    Padding="0"
+                    HorizontalAlignment="Right"
+                    VerticalAlignment="Top"
+                    Margin="0,20,18,0"
+                    Command="{Binding CloseCommand}"
+                    Background="Transparent"
+                    BorderBrush="Transparent"
+                    Foreground="Black" />
+            <TextBlock Text="用户登录"
+                       HorizontalAlignment="Center"
+                       VerticalAlignment="Top"
+                       FontSize="32"
+                       Margin="0,58,0,0"
+                       FontWeight="Bold" />
+            <materialDesign:Transitioner Margin="20,110,20,20"
+                                         AutoApplyTransitionOrigins="True"
+                                         d:SelectedIndex="1"
+                                         SelectedIndex="{Binding PageIndex}">
+                <materialDesign:TransitionerSlide OpeningEffect="{materialDesign:TransitionEffect FadeIn}">
+                    <Grid Background="Transparent">
+                        <Grid>
+                            <!-- 刷卡动画区域 -->
+                            <Border BorderThickness="1"
+                                    BorderBrush="#bdc3c7"
+                                    Background="#f8f9fa"
+                                    CornerRadius="8"
+                                    Margin="0,10"
+                                    VerticalAlignment="Top"
+                                    HorizontalAlignment="Center"
+                                    Padding="30">
+                                <Canvas Width="300"
+                                        Height="200">
+                                    <!-- 刷卡器主体 -->
+                                    <Rectangle Canvas.Left="50"
+                                               Canvas.Top="70"
+                                               Width="200"
+                                               Height="60"
+                                               Fill="#34495e"
+                                               RadiusX="5"
+                                               RadiusY="5">
+                                        <Rectangle.Effect>
+                                            <DropShadowEffect ShadowDepth="2"
+                                                              Direction="270"
+                                                              BlurRadius="5"
+                                                              Opacity="0.2" />
+                                        </Rectangle.Effect>
+                                    </Rectangle>
+
+                                    <!-- 刷卡槽 -->
+                                    <Rectangle Canvas.Left="60"
+                                               Canvas.Top="75"
+                                               Width="180"
+                                               Height="10"
+                                               Fill="#7f8c8d"
+                                               RadiusX="2"
+                                               RadiusY="2" />
+
+                                    <!-- 动态卡片 -->
+                                    <Border x:Name="AnimatedCard"
+                                            Canvas.Left="50"
+                                            Canvas.Top="10"
+                                            Width="180"
+                                            Height="100"
+                                            Background="#3498db"
+                                            CornerRadius="8"
+                                            BorderThickness="1"
+                                            BorderBrush="#2980b9">
+                                        <Border.Effect>
+                                            <DropShadowEffect ShadowDepth="3"
+                                                              Direction="270"
+                                                              BlurRadius="10"
+                                                              Opacity="0.3" />
+                                        </Border.Effect>
+
+                                        <!-- 卡片动画 -->
+                                        <Border.Triggers>
+                                            <EventTrigger RoutedEvent="Loaded">
+                                                <BeginStoryboard>
+                                                    <Storyboard RepeatBehavior="Forever">
+                                                        <!-- 卡片下落动画 -->
+                                                        <DoubleAnimation Storyboard.TargetProperty="(Canvas.Top)"
+                                                                         From="10"
+                                                                         To="70"
+                                                                         Duration="0:0:1"
+                                                                         AutoReverse="True"
+                                                                         BeginTime="0:0:0" />
+
+                                                        <!-- 卡片透明度变化 -->
+                                                        <DoubleAnimation Storyboard.TargetProperty="Opacity"
+                                                                         From="1"
+                                                                         To="0.7"
+                                                                         Duration="0:0:0.5"
+                                                                         AutoReverse="True"
+                                                                         BeginTime="0:0:0.5" />
+                                                    </Storyboard>
+                                                </BeginStoryboard>
+                                            </EventTrigger>
+                                        </Border.Triggers>
+
+                                        <!-- 卡片内部设计 -->
+                                        <Grid>
+                                            <Grid.RowDefinitions>
+                                                <RowDefinition Height="*" />
+                                                <RowDefinition Height="Auto" />
+                                            </Grid.RowDefinitions>
+
+                                            <TextBlock Text="员工卡"
+                                                       Foreground="White"
+                                                       FontSize="14"
+                                                       FontWeight="Bold"
+                                                       HorizontalAlignment="Center"
+                                                       VerticalAlignment="Center" />
+
+                                            <Rectangle Grid.Row="1"
+                                                       Height="20"
+                                                       Fill="#2980b9"
+                                                       RadiusX="0"
+                                                       RadiusY="0,0,8,8" />
+                                            <TextBlock Grid.Row="1"
+                                                       Text="●●●● 1234"
+                                                       Foreground="White"
+                                                       FontSize="10"
+                                                       HorizontalAlignment="Center"
+                                                       VerticalAlignment="Center" />
+                                        </Grid>
+                                    </Border>
+
+                                    <!-- 扫描光线效果 -->
+                                    <Rectangle x:Name="ScanBeam"
+                                               Canvas.Left="60"
+                                               Canvas.Top="75"
+                                               Width="180"
+                                               Height="2"
+                                               Fill="#2ecc71"
+                                               Opacity="0">
+                                        <Rectangle.Effect>
+                                            <BlurEffect Radius="3" />
+                                        </Rectangle.Effect>
+
+                                        <Rectangle.Triggers>
+                                            <EventTrigger RoutedEvent="Loaded">
+                                                <BeginStoryboard>
+                                                    <Storyboard RepeatBehavior="Forever">
+                                                        <!-- 扫描光束移动动画 -->
+                                                        <DoubleAnimation Storyboard.TargetProperty="(Canvas.Top)"
+                                                                         From="75"
+                                                                         To="125"
+                                                                         Duration="0:0:0.8"
+                                                                         BeginTime="0:0:0.5" />
+
+                                                        <!-- 扫描光束透明度动画 -->
+                                                        <DoubleAnimation Storyboard.TargetProperty="Opacity"
+                                                                         From="0"
+                                                                         To="1"
+                                                                         Duration="0:0:0.2"
+                                                                         AutoReverse="True"
+                                                                         BeginTime="0:0:0.5" />
+                                                    </Storyboard>
+                                                </BeginStoryboard>
+                                            </EventTrigger>
+                                        </Rectangle.Triggers>
+                                    </Rectangle>
+
+                                    <!-- 状态指示灯 -->
+                                    <Ellipse Canvas.Left="20"
+                                             Canvas.Top="80"
+                                             Width="12"
+                                             Height="12"
+                                             Fill="#e74c3c">
+                                        <Ellipse.Triggers>
+                                            <EventTrigger RoutedEvent="Loaded">
+                                                <BeginStoryboard>
+                                                    <Storyboard RepeatBehavior="Forever">
+                                                        <!-- 指示灯颜色变化动画 -->
+                                                        <ColorAnimation Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
+                                                                        From="#e74c3c"
+                                                                        To="#2ecc71"
+                                                                        Duration="0:0:1"
+                                                                        AutoReverse="True"
+                                                                        BeginTime="0:0:0.5" />
+                                                    </Storyboard>
+                                                </BeginStoryboard>
+                                            </EventTrigger>
+                                        </Ellipse.Triggers>
+                                    </Ellipse>
+                                </Canvas>
+                            </Border>
+
+                            <!-- 提示文字 -->
+                            <TextBlock Text="请刷卡..."
+                                       HorizontalAlignment="Center"
+                                       VerticalAlignment="Bottom"
+                                       Margin="0,120"
+                                       FontSize="16"
+                                       Foreground="#2c3e50"
+                                       FontWeight="SemiBold" />
+                        </Grid>
+                        <Button x:Name="NameLoginButton"
+                                Height="50"
+                                Width="50"
+                                materialDesign:ButtonAssist.CornerRadius="5"
+                                HorizontalAlignment="Center"
+                                VerticalAlignment="Bottom"
+                                Margin="0,0,0,44"
+                                ToolTip="账户登录"
+                                Command="{Binding TransitionerCommand}"
+                                CommandParameter="1"
+                                Padding="0"
+                                IsEnabled="{Binding IsLogining,Converter={StaticResource InvertBooleanConverter}}">
+                            <Button.Content>
+                                <materialDesign:PackIcon Kind="User"
+                                                         Height="32"
+                                                         Width="32" />
+                            </Button.Content>
+                        </Button>
+                    </Grid>
+                </materialDesign:TransitionerSlide>
+                <Grid HorizontalAlignment="Center"
+                      Margin="0,50">
+                    <Grid.RowDefinitions>
+                        <RowDefinition Height="Auto" />
+                        <RowDefinition Height="Auto" />
+                        <RowDefinition Height="Auto" />
+
+                        <RowDefinition Height="Auto" />
+                    </Grid.RowDefinitions>
+                    <Grid.ColumnDefinitions>
+                        <ColumnDefinition Width="Auto" />
+                        <ColumnDefinition Width="Auto" />
+                    </Grid.ColumnDefinitions>
+                    <TextBlock Grid.Row="0"
+                               Grid.Column="0"
+                               HorizontalAlignment="Left"
+                               VerticalAlignment="Center"
+                               Margin="20"
+                               FontSize="18"
+                               FontWeight="Bold"
+                               Text="用户名:" />
+                    <ComboBox Grid.Row="0"
+                              Grid.Column="1"
+                              HorizontalAlignment="Left"
+                              VerticalAlignment="Center"
+                              Margin="20"
+                              Width="200"
+                              FontSize="16"
+                              materialDesign:HintAssist.Hint="{lex:Loc 用户}"
+                              HorizontalContentAlignment="Left"
+                              Style="{StaticResource MaterialDesignFloatingHintComboBox}"
+                              ItemsSource="{Binding UserNameList,Mode=TwoWay}"
+                              SelectedItem="{Binding SelectedUserName,Mode=TwoWay}">
+                    </ComboBox>
+                    <TextBlock Grid.Row="1"
+                               Grid.Column="0"
+                               HorizontalAlignment="Left"
+                               VerticalAlignment="Center"
+                               Margin="20"
+                               FontSize="18"
+                               FontWeight="Bold"
+                               Text="密码:" />
+                    <PasswordBox Grid.Row="1"
+                                 Grid.Column="1"
+                                 HorizontalAlignment="Left"
+                                 VerticalAlignment="Center"
+                                 Margin="20"
+                                 Width="200"
+                                 HorizontalContentAlignment="Left"
+                                 VerticalContentAlignment="Center"
+                                 PasswordChar="*"
+                                 Style="{StaticResource MaterialDesignFloatingHintPasswordBox}"
+                                 materialDesign:HintAssist.HelperText="{lex:Loc 请输入用户登录密码}"
+                                 materialDesign:HintAssist.Hint="{lex:Loc 密码}"
+                                 materialDesign:TextFieldAssist.HasClearButton="True"
+                                 materialDesign:PasswordBoxAssist.Password="{Binding Path=Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}" />
+                    <Button Grid.Row="2"
+                            Grid.Column="0"
+                            Grid.ColumnSpan="2"
+                            HorizontalAlignment="Center"
+                            VerticalAlignment="Center"
+                            Content="{lex:Loc 登录}"
+                            Height="30"
+                            Margin="0,50"
+                            MinWidth="200"
+                            BorderThickness="0"
+                            materialDesign:ButtonAssist.CornerRadius="5"
+                            Command="{Binding LoginCommand}">
+                        <Button.Background>
+                            <LinearGradientBrush EndPoint="0.5,1"
+                                                 StartPoint="0.5,0">
+                                <GradientStop Color="#FF73B3BD"
+                                              Offset="0" />
+                                <GradientStop Color="#FF309EAF"
+                                              Offset="1" />
+                            </LinearGradientBrush>
+                        </Button.Background>
+                    </Button>
+                    <Button Grid.Row="3"
+                            Grid.Column="0"
+                            Grid.ColumnSpan="2"
+                            Height="50"
+                            Width="50"
+                            materialDesign:ButtonAssist.CornerRadius="5"
+                            HorizontalAlignment="Center"
+                            VerticalAlignment="Center"
+                            ToolTip="刷卡登录"
+                            Padding="0"
+                            Command="{Binding TransitionerCommand}"
+                            CommandParameter="0"
+                            Visibility="{Binding CardBtnVisibility}"
+                            IsEnabled="{Binding IsLogining,Converter={StaticResource InvertBooleanConverter}}">
+                        <Button.Content>
+                            <materialDesign:PackIcon Kind="CreditCardScanOutline" />
+                        </Button.Content>
+                    </Button>
+                </Grid>
+            </materialDesign:Transitioner>
+            
+        </Grid>
+    </Border>
+</Window>

+ 34 - 0
TeamAAS-VM/Views/User/CardLoginWindow.xaml.cs

@@ -0,0 +1,34 @@
+using System.Windows;
+
+namespace TeamAAS_VP.Views.User
+{
+    /// <summary>
+    /// Interaction logic for CardLoginWindow.xaml
+    /// </summary>
+    public partial class CardLoginWindow : Window
+    {
+        public CardLoginWindow()
+        {
+            InitializeComponent();
+            Loaded += (sender, e) =>
+            {
+                var vm = DataContext as ViewModels.User.CardLoginWindowViewModel;
+                vm.View = this;
+            };
+        }
+
+        public CardLoginWindow(bool isCard)
+        {
+            InitializeComponent();
+            Loaded += (sender, e) =>
+            {
+                var vm = DataContext as ViewModels.User.CardLoginWindowViewModel;
+                vm.View = this;
+            };
+            if (isCard)
+            {
+                this.NameLoginButton.Visibility = Visibility.Collapsed;
+            }
+        }
+    }
+}

+ 16 - 0
TeamAAS-VM/Views/User/LoginView.xaml

@@ -88,6 +88,22 @@
                                        Margin="20,0,0,0" />
                         </StackPanel>
                     </Button>
+                    <Button Grid.Row="4"
+                            Margin="0,55,0,0"
+                            Height="50"
+                            Width="50"
+                            materialDesign:ButtonAssist.CornerRadius="5"
+                            HorizontalAlignment="Center"
+                            VerticalAlignment="Center"
+                            ToolTip="刷卡登录"
+                            Padding="0"
+                            Command="{Binding CardLoginCommand}"
+                            Visibility="{Binding CardBtnVisibility}"
+                            IsEnabled="{Binding IsLogining,Converter={StaticResource InvertBooleanConverter}}">
+                        <Button.Content>
+                            <materialDesign:PackIcon Kind="CreditCardScanOutline" />
+                        </Button.Content>
+                    </Button>
                 </Grid>
             </materialDesign:Card>
         </Grid>