浏览代码

Merge branch 'AOI' of http://49.235.130.76/XXF_1122/DaisyNPILine into AOI

KWD 8 月之前
父节点
当前提交
debacd6712
共有 36 个文件被更改,包括 4661 次插入 和 29 次删除
  1. 3 0
      TeamAAS-VM/App.xaml.cs
  2. 2 0
      TeamAAS-VM/Core/FilePath.cs
  3. 533 10
      TeamAAS-VM/Core/Management.cs
  4. 774 0
      TeamAAS-VM/Core/Scanners/NlsScanner.cs
  5. 27 0
      TeamAAS-VM/Enums/ScannerBrand.cs
  6. 28 0
      TeamAAS-VM/Interfaces/IConfigService.cs
  7. 13 0
      TeamAAS-VM/Interfaces/IProductService.cs
  8. 160 0
      TeamAAS-VM/Interfaces/IScanner.cs
  9. 171 0
      TeamAAS-VM/Interfaces/IScannerService.cs
  10. 9 0
      TeamAAS-VM/Models/DeviceInfo.cs
  11. 44 0
      TeamAAS-VM/Models/ScanRs232ConfigModel.cs
  12. 111 0
      TeamAAS-VM/Models/Scanner/ScannerInfo.cs
  13. 10 0
      TeamAAS-VM/Models/SystemConfiguration.cs
  14. 82 1
      TeamAAS-VM/Resources/Languages/Lang.Designer.cs
  15. 27 0
      TeamAAS-VM/Resources/Languages/Lang.en.resx
  16. 27 0
      TeamAAS-VM/Resources/Languages/Lang.ja-JP.resx
  17. 36 0
      TeamAAS-VM/Resources/Languages/Lang.resx
  18. 27 0
      TeamAAS-VM/Resources/Languages/Lang.zh-TW.resx
  19. 98 0
      TeamAAS-VM/Services/ConfigService.cs
  20. 41 0
      TeamAAS-VM/Services/ProductService.cs
  21. 503 0
      TeamAAS-VM/Services/ScannerService.cs
  22. 33 1
      TeamAAS-VM/TeamAAS-VP.csproj
  23. 593 0
      TeamAAS-VM/ViewModels/ImageViewModel.cs
  24. 18 3
      TeamAAS-VM/ViewModels/MainWindowViewModel.cs
  25. 92 0
      TeamAAS-VM/ViewModels/Setting/AddScannerViewModel.cs
  26. 140 3
      TeamAAS-VM/ViewModels/SettingViewModel.cs
  27. 23 0
      TeamAAS-VM/Views/Dialogs/TextInputDialog.xaml
  28. 30 0
      TeamAAS-VM/Views/Dialogs/TextInputDialog.xaml.cs
  29. 1 1
      TeamAAS-VM/Views/HomeView.xaml
  30. 70 0
      TeamAAS-VM/Views/ImageView.xaml
  31. 260 0
      TeamAAS-VM/Views/ImageView.xaml.cs
  32. 22 8
      TeamAAS-VM/Views/MainWindowView.xaml
  33. 256 0
      TeamAAS-VM/Views/Setting/AddScanner.xaml
  34. 28 0
      TeamAAS-VM/Views/Setting/AddScanner.xaml.cs
  35. 364 2
      TeamAAS-VM/Views/SettingView.xaml
  36. 5 0
      TeamAAS-VM/Views/SettingView.xaml.cs

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

@@ -85,6 +85,7 @@ namespace TeamAAS_VP
             containerRegistry.RegisterForNavigation<ProductsView>();
             containerRegistry.RegisterForNavigation<ProductsView>();
             containerRegistry.RegisterForNavigation<DebugView>();
             containerRegistry.RegisterForNavigation<DebugView>();
             containerRegistry.RegisterForNavigation<SettingView>();
             containerRegistry.RegisterForNavigation<SettingView>();
+            containerRegistry.RegisterForNavigation<ImageView>();
             containerRegistry.RegisterForNavigation<CalibrationView>();
             containerRegistry.RegisterForNavigation<CalibrationView>();
             containerRegistry.RegisterForNavigation<StatisticsView>();
             containerRegistry.RegisterForNavigation<StatisticsView>();
             containerRegistry.RegisterForNavigation<UserView>();
             containerRegistry.RegisterForNavigation<UserView>();
@@ -134,6 +135,7 @@ namespace TeamAAS_VP
             containerRegistry.RegisterSingleton<ICalibrationService, CalibrationService>();
             containerRegistry.RegisterSingleton<ICalibrationService, CalibrationService>();
             containerRegistry.RegisterSingleton<ICameraService, CameraService>();
             containerRegistry.RegisterSingleton<ICameraService, CameraService>();
             containerRegistry.RegisterSingleton<IRobotService, RobotService>();
             containerRegistry.RegisterSingleton<IRobotService, RobotService>();
+            containerRegistry.RegisterSingleton<IScannerService, ScannerService>();
             containerRegistry.RegisterSingleton<IPlcService, PlcService>();
             containerRegistry.RegisterSingleton<IPlcService, PlcService>();
             containerRegistry.RegisterSingleton<IFeederService, FeederService>();
             containerRegistry.RegisterSingleton<IFeederService, FeederService>();
             containerRegistry.RegisterSingleton<IProductService, ProductService>();
             containerRegistry.RegisterSingleton<IProductService, ProductService>();
@@ -186,6 +188,7 @@ namespace TeamAAS_VP
 
 
             //------------------------注册对话框------------------------------------------------
             //------------------------注册对话框------------------------------------------------
             containerRegistry.RegisterDialog<AddRobot>();
             containerRegistry.RegisterDialog<AddRobot>();
+            containerRegistry.RegisterDialog<AddScanner>();
             containerRegistry.RegisterDialog<AddFeeder>();
             containerRegistry.RegisterDialog<AddFeeder>();
             containerRegistry.RegisterDialog<AddPlc>();
             containerRegistry.RegisterDialog<AddPlc>();
             containerRegistry.RegisterDialog<AddCamera>();
             containerRegistry.RegisterDialog<AddCamera>();

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

@@ -61,5 +61,7 @@ namespace TeamAAS_VP.Core
         /// 后台脚本存放文件夹
         /// 后台脚本存放文件夹
         /// </summary>
         /// </summary>
         public static string BackgroundScriptPath = "..//Background Script";
         public static string BackgroundScriptPath = "..//Background Script";
+
+        public static string ScanRS232ConfigPath = "..//Config//ScanRS232Config.cfg";
     }
     }
 }
 }

+ 533 - 10
TeamAAS-VM/Core/Management.cs

@@ -25,6 +25,7 @@ using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.ViewModels;
 using TeamAAS_VP.ViewModels;
 using TeamAAS_VP.ViewModels.Home;
 using TeamAAS_VP.ViewModels.Home;
 using TouchSocket.Core;
 using TouchSocket.Core;
+using TouchSocket.SerialPorts;
 using TouchSocket.Sockets;
 using TouchSocket.Sockets;
 
 
 namespace TeamAAS_VP.Core
 namespace TeamAAS_VP.Core
@@ -37,6 +38,7 @@ namespace TeamAAS_VP.Core
         IContainerProvider _container;
         IContainerProvider _container;
         IConfigService _configService;
         IConfigService _configService;
         IRobotService _robotService;
         IRobotService _robotService;
+        IScannerService _scannerService;
         ICameraService _cameraService;
         ICameraService _cameraService;
         IFeederService _feederService;
         IFeederService _feederService;
         IPlcService _plcService;
         IPlcService _plcService;
@@ -58,6 +60,8 @@ namespace TeamAAS_VP.Core
         #endregion
         #endregion
 
 
         #region 属性
         #region 属性
+        private Guid _defaultScannerId = Guid.Empty;
+        private volatile TaskCompletionSource<string> _scanTcs; // 最简单:只支持单通道“当前一次扫
         public string[] CsvData = new string[50];
         public string[] CsvData = new string[50];
         public int[] ResultData = new int[200];
         public int[] ResultData = new int[200];
         public string code = "";
         public string code = "";
@@ -65,8 +69,20 @@ namespace TeamAAS_VP.Core
         private ObservableCollection<ShowRender> _Renders;
         private ObservableCollection<ShowRender> _Renders;
         private double _CTtime;
         private double _CTtime;
         public int ResultDataCount;
         public int ResultDataCount;
+        // 扫码结果
+        private string ScanValue = "";
+        // 扫码完成事件
+        private readonly ManualResetEventSlim _scanDoneEvent = new ManualResetEventSlim(false);
 
 
 
 
+        private SerialPortClient _Scan_Client;
+
+        public SerialPortClient Scan_Client
+        {
+            get { return _Scan_Client; }
+            set { _Scan_Client = value; }
+        }
+
         private bool _ShowMes_Query;
         private bool _ShowMes_Query;
         /// <summary>
         /// <summary>
         /// 显示查询结果
         /// 显示查询结果
@@ -199,7 +215,7 @@ namespace TeamAAS_VP.Core
 
 
         public Management(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IConfigService configService,
         public Management(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IConfigService configService,
             IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService, IProductService productService,
             IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService, IProductService productService,
-            ICalibrationService calibrationService, IRemoteCommandService remoteCommandService, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService, IMesService mesService)
+            ICalibrationService calibrationService, IRemoteCommandService remoteCommandService, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService, IMesService mesService, IScannerService scannerService)
         {
         {
 
 
             _regionManager = regionManager;
             _regionManager = regionManager;
@@ -207,6 +223,7 @@ namespace TeamAAS_VP.Core
             _container = container;
             _container = container;
             _configService = configService;
             _configService = configService;
             _robotService = robotService;
             _robotService = robotService;
+            _scannerService = scannerService;
             _cameraService = cameraService;
             _cameraService = cameraService;
             _feederService = feederService;
             _feederService = feederService;
             _plcService = plcService;
             _plcService = plcService;
@@ -297,6 +314,44 @@ namespace TeamAAS_VP.Core
             }
             }
         }
         }
 
 
+        /// <summary>
+        /// 初始化扫码枪
+        /// </summary>
+        /// <returns></returns>
+        public async Task<(bool IsSucceed, string Msg)> InitScanners()
+        {
+            var scanners = _configService.GetAllScanners();
+            StringBuilder sb = new StringBuilder();
+            foreach (var item in scanners)
+            {
+                _scannerService.CreateScanner(item.Id, item);
+                try
+                {
+                    Status.Add(new StatusInfo(item.Id, item.ScannerName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
+                    var scanner = _scannerService.GetScanner(item.Id);
+                    scanner.ReceivedEvent += Management_ScannerReceivedEvent;
+                    scanner.SendEvent += Management_ScannerSendEvent; 
+                    scanner.ConnectedEvent += Management_ScannerConnectedEvent;
+                    scanner.DisconnectedEvent += Management_ScannerDisconnectedEvent;
+                    await scanner.ConnectAsync();     //连接Scanner
+                    SendTaskMessage($"{item.ScannerName}{Lang.已连接}!", MessageLevel.Debug);
+                }
+                catch (Exception ex)
+                {
+                    sb.AppendLine($"{item.ScannerName}:{Lang.断开连接}![{ex.Message}]");
+                    SendTaskMessage($"{item.ScannerName}{Lang.断开连接}!", MessageLevel.Alarm);
+                }
+            }
+            if (sb.Length == 0)
+            {
+                return (true, "");
+            }
+            else
+            {
+                return (false, sb.ToString());
+            }
+        }
+
         /// <summary>
         /// <summary>
         /// 初始化PLC
         /// 初始化PLC
         /// </summary>
         /// </summary>
@@ -621,11 +676,73 @@ namespace TeamAAS_VP.Core
                 LogHelper.WriteLogError("连接电批时出错!", ex);
                 LogHelper.WriteLogError("连接电批时出错!", ex);
             }
             }
         }
         }
+
+        public async Task InitScan()
+        {
+            if (!File.Exists(FilePath.ScanRS232ConfigPath))
+            {
+                var scan = new ScanRs232ConfigModel();
+                FileHelper.WriteJsonFile(scan, FilePath.ScanRS232ConfigPath);
+            }
+
+            try
+            {
+                var res = FileHelper.ReadJsonFile<ScanRs232ConfigModel>(FilePath.ScanRS232ConfigPath);
+                if (res != null)
+                {
+                    Scan_Client = new SerialPortClient();
+                    Scan_Client.Connecting = (client1, e) => { return EasyTask.CompletedTask; };//即将连接到端口
+                    Scan_Client.Connected = (client1, e) => { return EasyTask.CompletedTask; };//成功连接到端口
+                    Scan_Client.Closing = (client1, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
+                    Scan_Client.Closed = (client1, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。
+                    Scan_Client.Received = async (c, e) =>
+                    {
+                        //await Console.Out.WriteLineAsync(Encoding.UTF8.GetString(e.ByteBlock.Buffer));
+                        await Console.Out.WriteLineAsync(e.ByteBlock.Span.ToString(Encoding.ASCII));
+                    };
+                    Scan_Client.Received = Scan_DataReceived;
+
+                    await Scan_Client.SetupAsync(new TouchSocketConfig()
+                         .SetSerialPortOption(new SerialPortOption()
+                         {
+                             BaudRate = res.BaudRate,//波特率
+                             DataBits = res.DataBits,//数据位
+                             Parity = res.Parity,//校验位
+                             PortName = res.PortName,//COM
+                             StopBits = res.StopBits//停止位
+                         })
+                         .SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
+                         );
+
+                    await Scan_Client.ConnectAsync();
+
+                    if (Scan_Client.Online)
+                    {
+                        SendTaskMessage(Lang.扫码机已连接, MessageLevel.Debug);
+                    }
+                    else
+                    {
+                        SendTaskMessage(Lang.扫码机未连接, MessageLevel.Debug);
+                    }
+                }
+                else
+                {
+                    SendTaskMessage(Lang.请设置扫码机串口, MessageLevel.Error);
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("初始化扫码枪时出错!", ex);
+                SendTaskMessage(Lang.初始化扫码枪时出错 + ex.Message, MessageLevel.Error);
+            }
+
+        }
         #endregion
         #endregion
 
 
         #region 机器人指令执行
         #region 机器人指令执行
 
 
         public Dictionary<Guid, CancellationTokenSource> RobotTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
         public Dictionary<Guid, CancellationTokenSource> RobotTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
+        public Dictionary<Guid, CancellationTokenSource> ScannerTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
         /// <summary>
         /// <summary>
         /// 机器人TCP接收
         /// 机器人TCP接收
         /// </summary>
         /// </summary>
@@ -684,6 +801,70 @@ namespace TeamAAS_VP.Core
             }
             }
         }
         }
 
 
+        /// <summary>
+        /// 扫码枪TCP接收
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        private async void Management_ScannerReceivedEvent(Guid scannerid, object arg2, TouchSocket.Sockets.ReceivedDataEventArgs e)
+        {
+            try
+            {
+                if (!ScannerTCPCollection.ContainsKey(scannerid))
+                    ScannerTCPCollection.Add(scannerid, new CancellationTokenSource());
+                else
+                {
+                    if (ScannerTCPCollection[scannerid].IsCancellationRequested)
+                    {
+                        ScannerTCPCollection[scannerid] = new CancellationTokenSource();
+                    }
+                }
+                var scanner = await _scannerService.GetScannerAsync(scannerid);
+                //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
+                var buffer = e.ByteBlock.Span.ToString(scanner.GetEncoding());
+                var reply = (buffer ?? string.Empty).Trim();
+                SendTaskMessage($"{scanner.Name}Received:{reply}", MessageLevel.Info);
+                // 只要有人在等扫码结果,就先完成等待(避免被下面 ExecuteAsync 干扰)
+                var tcs = _scanTcs;
+                if (tcs != null && !string.IsNullOrWhiteSpace(reply))
+                {
+                    // 只完成一次
+                    tcs.TrySetResult(reply);
+                }
+                var _ = _remoteCommandService.ExecuteAsync(buffer, ScannerTCPCollection[scannerid].Token, async msg =>
+                {
+                    try
+                    {
+                        if (scanner.ConnectType == TCPConnectType.Client)
+                        {
+                            if (scanner.IsConnected)
+                            {
+                                await scanner.SendAsync($"{msg}");
+                            }
+                        }
+                        else
+                        {
+                            var cient = (ITcpSessionClient)arg2;
+                            if (cient.Online)
+                            {
+                                await scanner.SendAsync(cient, $"{msg}");
+                            }
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        LogHelper.WriteLogError("TCP发送数据时出错!", ex);
+                        SendTaskMessage(ex.Message, MessageLevel.Alarm);
+                    }
+                });
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("处理扫码枪接收的命令时出错!", ex);
+                SendTaskMessage(ex.Message, MessageLevel.Alarm);
+            }
+        }
         #endregion
         #endregion
 
 
         #region 机器人&Feeder&相机连接状态事件
         #region 机器人&Feeder&相机连接状态事件
@@ -700,6 +881,19 @@ namespace TeamAAS_VP.Core
             SendTaskMessage($"{r.Name}Send:{arg3}", MessageLevel.Info);
             SendTaskMessage($"{r.Name}Send:{arg3}", MessageLevel.Info);
         }
         }
 
 
+        /// <summary>
+        /// 扫码枪发送事件
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void Management_ScannerSendEvent(Guid scannerid, object arg2, string arg3)
+        {
+            var r = _scannerService.GetScanner(scannerid);
+            SendTaskMessage($"{r.Name}Send:{arg3}", MessageLevel.Info);
+        }
+
         /// <summary>
         /// <summary>
         /// 机器人断开连接时
         /// 机器人断开连接时
         /// </summary>
         /// </summary>
@@ -746,6 +940,51 @@ namespace TeamAAS_VP.Core
             }
             }
         }
         }
 
 
+        /// <summary>
+        /// 扫码枪断开连接时
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void Management_ScannerDisconnectedEvent(Guid scannerid, object arg2, ClosedEventArgs arg3)
+        {
+            if (ScannerTCPCollection.ContainsKey(scannerid))
+            {
+                ScannerTCPCollection[scannerid].Cancel();
+            }
+            var r = _configService.GetScanner(scannerid);
+            if (r.ConnectType == TCPConnectType.Server)
+            {
+                ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
+                SendTaskMessage($"{r.ScannerName}[{socketClient.Id}:{socketClient.IP}]{Lang.断开连接}!", MessageLevel.Error);
+                var scanner = _scannerService.GetScanner(scannerid);
+                if (scanner.TcpService.Count < 1)
+                {
+                    var sta = Status.FirstOrDefault(s => s.ID == scannerid);
+                    App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{r.ScannerName}{Lang.未连接}";
+                             sta.Background = new SolidColorBrush(Colors.Red);
+                         }));
+
+                }
+            }
+            else
+            {
+                SendTaskMessage($"{r.ScannerName}{Lang.断开连接}!", MessageLevel.Error);
+                var sta = Status.FirstOrDefault(s => s.ID == scannerid);
+                App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{r.ScannerName}{Lang.断开连接}";
+                             sta.Background = new SolidColorBrush(Colors.Red);
+                         }));
+
+            }
+        }
+
         /// <summary>
         /// <summary>
         /// 机器人连接成功时
         /// 机器人连接成功时
         /// </summary>
         /// </summary>
@@ -788,6 +1027,47 @@ namespace TeamAAS_VP.Core
             }
             }
         }
         }
 
 
+        /// <summary>
+        /// 扫码枪连接成功时
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void Management_ScannerConnectedEvent(Guid scannerid, object arg2, ConnectedEventArgs arg3)
+        {
+            var r = _configService.GetScanner(scannerid);
+            if (r.ConnectType == TCPConnectType.Server)
+            {
+                ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
+                SendTaskMessage($"{r.ScannerName}[{socketClient.Id}:{socketClient.IP}]{Lang.已连接}!", MessageLevel.Debug);
+                var scanner = _scannerService.GetScanner(scannerid);
+                if (scanner.TcpService.Count > 0)
+                {
+                    var sta = Status.FirstOrDefault(s => s.ID == scannerid);
+                    App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{r.ScannerName}{Lang.已连接}";
+                             sta.Background = new SolidColorBrush(Colors.Green);
+                         }));
+
+                }
+            }
+            else
+            {
+                SendTaskMessage($"{r.ScannerName}{Lang.已连接}!", MessageLevel.Debug);
+                var sta = Status.FirstOrDefault(s => s.ID == scannerid);
+                App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{r.ScannerName}{Lang.已连接}";
+                             sta.Background = new SolidColorBrush(Colors.Green);
+                         }));
+
+            }
+        }
+
         /// <summary>
         /// <summary>
         /// Feeder连接状态改变时
         /// Feeder连接状态改变时
         /// </summary>
         /// </summary>
@@ -1307,6 +1587,164 @@ namespace TeamAAS_VP.Core
                                 if (targetPoint.CameraProcedureId8 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId8)) procIds.Add(targetPoint.CameraProcedureId8);
                                 if (targetPoint.CameraProcedureId8 != Guid.Empty && !procIds.Contains(targetPoint.CameraProcedureId8)) procIds.Add(targetPoint.CameraProcedureId8);
                             }
                             }
                             catch { }
                             catch { }
+                            var sysConfig = _configService.GetSystemConfiguration();
+                            if (sysConfig.ScannerUse == true && cameraIndex == 1 && sysConfig.CodeUse2 == true)
+                            {
+                                ScanValue = "";
+                                _scanDoneEvent.Reset(); // 重要:先关门
+
+                                await Scan_Client.SendAsync("T\r\n");
+
+                                // 等待扫码结果,最多 3 秒
+                                bool scanOk = await Task.Run(() => _scanDoneEvent.Wait(3000));
+
+                                if (!scanOk || ScanValue.IsNullOrWhiteSpace())
+                                {
+                                    SendTaskMessage("二维码拍照失败或超时", MessageLevel.Alarm);
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
+                                    return;
+                                }
+
+                                code = ScanValue;
+                                SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
+                                //这里缺少从MES获取产品配方的内容,需要补充
+                                _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
+                                //_LastMesCheckTime[1] = DateTime.Now;
+                                LogHelper.WriteLogMes($"【mes开始QUERY】");
+                                SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
+                                (bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
+
+                                if (isSuccess)
+                                {
+                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+
+                                    LogHelper.WriteLogMes($"询问mes成功");
+                                    SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+                                    if (response != "MES功能未启用!")
+                                    {
+                                        string[] items = response.Split('\n');
+                                        if (items[3].Contains("sn="))
+                                        {
+                                            ProductMainSN = items[3].Replace("sn=", "");
+                                            _productService.CurrentProductCode = ProductMainSN;
+                                        }
+                                        SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
+                                        if (items[5].Contains("wo="))
+                                        {
+                                            wo = items[5].Replace("wo=", "");
+                                        }
+                                        SendTaskMessage($"产品wo:{wo}", MessageLevel.Info);
+                                    }
+                                    LogHelper.WriteLogMes($"【mes结束QUERY】");
+                                    SendTaskMessage($"mes结束QUERY", MessageLevel.Info);
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
+                                    return;
+                                }
+                                else
+                                {
+                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
+
+                                    LogHelper.WriteLogMes($"询问mes失败");
+                                    SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
+                                    return;
+                                }
+                            }
+
+                            if (sysConfig.ScannerUse == true && cameraIndex == 1 && sysConfig.CodeUse == true)
+                            {
+                                ScanValue = "";
+                                _scanDoneEvent.Reset(); // 重要:先关门
+
+                                await Scan_Client.SendAsync("T\r\n");
+
+                                // 等待扫码结果,最多 3 秒
+                                bool scanOk = await Task.Run(() => _scanDoneEvent.Wait(3000));
+
+                                if (!scanOk || ScanValue.IsNullOrWhiteSpace())
+                                {
+                                    SendTaskMessage("二维码拍照失败或超时", MessageLevel.Alarm);
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (short)3);
+                                    return;
+                                }
+
+                                code = ScanValue;
+                                SendTaskMessage($"扫码成功,SN:{code}", MessageLevel.Info);
+                                //这里缺少从MES获取产品配方的内容,需要补充
+                                _LastMesCheckTime[0] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
+                                LogHelper.WriteLogMes($"【mes开始QUERY】");
+                                SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
+                                //(bool isSuccess, string response) = await _mesService.StationGetAsync(code, "", 2);//询问mes
+                                (bool isSuccess, string response) = await _mesService.StationGetExAsync(code, "", 2);//基于电池的SN获取产品SN,询问mes
+                                if (isSuccess)
+                                {
+                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+
+
+                                    string ProductMainSN_Temp = "";
+                                    LogHelper.WriteLogMes($"询问mes成功");
+                                    SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+
+                                    if (response != "MES功能未启用!")
+                                    {
+                                        string[] item = response.Split('\n');
+                                        if (item[2].Contains("sn="))
+                                        {
+                                            ProductMainSN_Temp = item[2].Replace("sn=", "");
+                                            SendTaskMessage($"sn:{ProductMainSN_Temp}", MessageLevel.Info);
+                                        }
+                                    }
+                                    LogHelper.WriteLogMes($"询问mes成功");
+                                    SendTaskMessage($"询问mes成功:{response}", MessageLevel.Debug);
+
+                                    //20260214,特别版(电池组装)
+                                    (bool isSuccess2, string response2) = await _mesService.StationGetAsync(ProductMainSN_Temp, "", 2);//询问mes
+                                    if (isSuccess2)
+                                    {
+                                        LogHelper.WriteLogMes($"询问mes成功");
+                                        SendTaskMessage($"询问mes成功:{response2}", MessageLevel.Debug);
+
+                                        if (response2 != "MES功能未启用!")
+                                        {
+                                            string[] item = response2.Split('\n');
+                                            if (item[3].Contains("sn="))
+                                            {
+                                                ProductMainSN = item[3].Replace("sn=", "");
+                                                _productService.CurrentProductCode = ProductMainSN;
+                                                SendTaskMessage($"产品主sn:{ProductMainSN}", MessageLevel.Info);
+                                            }
+                                            if (item[5].Contains("wo="))
+                                            {
+                                                wo = item[5].Replace("wo=", "");
+                                                SendTaskMessage($"产品主wo:{wo}", MessageLevel.Info);
+                                            }
+                                        }
+                                        LogHelper.WriteLogMes($"第二次询问mes成功");
+                                        SendTaskMessage($"第二次询问mes成功:{response2}", MessageLevel.Debug);
+
+                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
+                                    }
+                                    else
+                                    {
+                                        LogHelper.WriteLogMes($"第二次询问mes失败");
+                                        SendTaskMessage($"第二次询问mes失败:{response2}", MessageLevel.Error);
+
+                                        await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
+                                    }
+                                }
+                                else
+                                {
+                                    //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
+
+                                    await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
+
+                                    LogHelper.WriteLogMes($"询问mes失败");
+                                    SendTaskMessage($"询问mes失败:{response}", MessageLevel.Error);
+                                }
+                                return;
+                            }
+
 
 
                             if (procIds.Count == 0)
                             if (procIds.Count == 0)
                             {
                             {
@@ -1337,7 +1775,7 @@ namespace TeamAAS_VP.Core
                                 });
                                 });
                             }
                             }
 
 
-                            var sysConfig = _configService.GetSystemConfiguration();
+                            
                             if (sysConfig.CodeUse==true && cameraIndex == 1)
                             if (sysConfig.CodeUse==true && cameraIndex == 1)
                             {
                             {
                                 var cts = new CancellationTokenSource();
                                 var cts = new CancellationTokenSource();
@@ -1458,7 +1896,6 @@ namespace TeamAAS_VP.Core
                                     SendTaskMessage($"扫码失败", MessageLevel.Alarm);
                                     SendTaskMessage($"扫码失败", MessageLevel.Alarm);
                                     await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
                                     await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
                                 }
                                 }
-
                                 return;
                                 return;
                             }
                             }
 
 
@@ -1553,12 +1990,8 @@ namespace TeamAAS_VP.Core
                                     SendTaskMessage($"扫码失败", MessageLevel.Alarm);
                                     SendTaskMessage($"扫码失败", MessageLevel.Alarm);
                                     await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
                                     await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)3);
                                 }
                                 }
-
                                 return;
                                 return;
                             }
                             }
-
-
-
                             foreach (var prcId in procIds)
                             foreach (var prcId in procIds)
                             {
                             {
                                 if (Is3D(prcId))
                                 if (Is3D(prcId))
@@ -1675,7 +2108,11 @@ namespace TeamAAS_VP.Core
                                 {
                                 {
                                     //这里缺少从MES获取产品配方的内容,需要补充
                                     //这里缺少从MES获取产品配方的内容,需要补充
                                     _LastMesCheckTime[i] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
                                     _LastMesCheckTime[i] = (await _mesService.GetServerTimeAsync(code, 2)).Now;
-
+                                    if (homeview.IsNoCode == false)
+                                    {
+                                        var device = _configService.GetDeviceInfo();
+                                        code = device.XnSN;
+                                    }
                                     LogHelper.WriteLogMes($"【mes开始QUERY】");
                                     LogHelper.WriteLogMes($"【mes开始QUERY】");
                                     SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
                                     SendTaskMessage($"mes开始QUERY", MessageLevel.Info);
                                     ShowMes_Query = false;
                                     ShowMes_Query = false;
@@ -1954,7 +2391,18 @@ namespace TeamAAS_VP.Core
 
 
                             string[] strpoints1 = visionResult.Items[i].Split(',');
                             string[] strpoints1 = visionResult.Items[i].Split(',');
                             lockResult1.PhotoName = strpoints1[0];
                             lockResult1.PhotoName = strpoints1[0];
-                            lockResult1.ResultData = strpoints1[1];
+                            string[] body1 = strpoints1[1].Split(";");
+                            string body2 = null;
+
+                            if (body1.Length == 8)
+                            {
+                                body2 = $"{body1[0]},{body1[2]},{body1[4]},{body1[6]}";
+                            }
+                            else
+                            {
+                                body2 = strpoints1[1];
+                            }
+                            lockResult1.ResultData = body2;
                             lockResult1.PhotoCode = ProductMainSN;
                             lockResult1.PhotoCode = ProductMainSN;
                             var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
                             var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
                             if (globalParam != null)
                             if (globalParam != null)
@@ -2113,7 +2561,18 @@ namespace TeamAAS_VP.Core
 
 
                             string[] strpoints1 = visionResult.Items[i].Split(',');
                             string[] strpoints1 = visionResult.Items[i].Split(',');
                             lockResult1.PhotoName = strpoints1[0];
                             lockResult1.PhotoName = strpoints1[0];
-                            lockResult1.ResultData = strpoints1[1];
+                            string[] body1 = strpoints1[1].Split(";");
+                            string body2 = null;
+
+                            if (body1.Length == 8)
+                            {
+                                body2 = $"{body1[0]},{body1[2]},{body1[4]},{body1[6]}";
+                            }
+                            else
+                            {
+                                body2 = strpoints1[1];
+                            }
+                            lockResult1.ResultData = body2;
                             lockResult1.PhotoCode = ProductMainSN;
                             lockResult1.PhotoCode = ProductMainSN;
                             var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
                             var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == strpoints1[0]);
                             if (globalParam != null)
                             if (globalParam != null)
@@ -2560,6 +3019,70 @@ namespace TeamAAS_VP.Core
 
 
         //    return true;
         //    return true;
         //}
         //}
+        // ====== 新增:最简等待:TCS + 超时(比 SemaphoreSlim + CurrentCount 轮询更轻、更可靠)======
+        private async Task<string> ScanT1Async(int timeoutMs)
+        {
+            var scannerId = GetDefaultScannerId();
+            if (scannerId == Guid.Empty) return null;
+
+            var scanner = _scannerService.GetScanner(scannerId);
+            if (scanner == null || !scanner.IsConnected) return null;
+
+            // 关键:先注册等待,再发送 T1,避免“回包先到”导致丢信号
+            var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
+            _scanTcs = tcs;
+
+            await scanner.SendAsync("T1").ConfigureAwait(false);
 
 
+            var completed = await Task.WhenAny(tcs.Task, Task.Delay(timeoutMs)).ConfigureAwait(false);
+            if (completed != tcs.Task)
+            {
+                // 超时:清掉本次等待,避免下次误用
+                if (ReferenceEquals(_scanTcs, tcs)) _scanTcs = null;
+                return null;
+            }
+
+            var reply = await tcs.Task.ConfigureAwait(false);
+            if (ReferenceEquals(_scanTcs, tcs)) _scanTcs = null;
+            return reply;
+        }
+        private Guid GetDefaultScannerId()
+        {
+            if (_defaultScannerId != Guid.Empty) return _defaultScannerId;
+
+            var scannerInfo = _configService.GetAllScanners()
+                .OrderBy(s => s.ScannerNo)
+                .FirstOrDefault();
+
+            _defaultScannerId = scannerInfo == null ? Guid.Empty : scannerInfo.Id;
+            return _defaultScannerId;
+        }
+
+        private async Task Scan_DataReceived(ISerialPortClient client, ReceivedDataEventArgs e)
+        {
+            try
+            {
+                // 串口名
+                string portName = client.MainSerialPort.PortName;
+                // 注意:DataReceived 可能一次收到多段/包含回车换行
+                string data = e.ByteBlock.Span.ToString(Encoding.ASCII);
+                await Console.Out.WriteLineAsync(data);
+                // 取第一段(到 \r 之前),并去掉首尾空白
+                string response = data.Split('\r')[0].Trim();
+                // 过滤:空数据不要当成一次有效扫码
+                if (string.IsNullOrWhiteSpace(response))
+                    return;
+                SendTaskMessage($"扫码机:{portName} Receive:{response}", MessageLevel.Info);
+                // 写入结果
+                ScanValue = response;
+                // 通知等待方继续执行(PLC 逻辑里 Wait 的地方)
+                _scanDoneEvent.Set();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("扫码枪接收信息时出错!", ex);
+                SendTaskMessage(Lang.扫码枪接收信息时出错 + ex.Message, MessageLevel.Error);
+            }
+        }
     }
     }
 }
 }

+ 774 - 0
TeamAAS-VM/Core/Scanners/NlsScanner.cs

@@ -0,0 +1,774 @@
+using Opc.Ua;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Net;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Models.Scanner;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace TeamAAS_VP.Core.Scanners
+{
+    public class NlsScanner : IScanner, INotifyPropertyChanged
+    {
+        private IWaitingClient<ITcpClient, IReceiverResult> WaitClient;
+        private IWaitingClient<ITcpSessionClient, IReceiverResult> WaitClientServer;
+        //private bool isFirstConnect=true;
+        private Task bgConnectTask;
+        public event Action<Guid, object, ConnectedEventArgs> ConnectedEvent;
+        public event Action<Guid, object, ClosedEventArgs> DisconnectedEvent;
+        public event Action<Guid, object, ReceivedDataEventArgs> ReceivedEvent;
+        public event Action<Guid, object, string> SendEvent;
+
+        public NlsScanner(ScannerInfo scanner)
+        {
+            Id = scanner.Id;
+            Name = scanner.ScannerName;
+            ScannerNo = scanner.ScannerNo;
+            ScannerIp = scanner.IP;
+            ScannerPort = scanner.Port;
+            ConnectType = scanner.ConnectType;
+            Terminator = scanner.Terminator;
+            DataEncoding = scanner.DataEncoding;
+            //Brand = scanner.ScannerBrand;
+            if (ConnectType == TCPConnectType.Client)
+            {
+                TcpClient = new TouchSocket.Sockets.TcpClient();
+                var config = new TouchSocketConfig();
+                config.SetRemoteIPHost(new IPHost(IPAddress.Parse(ScannerIp), ScannerPort));
+                config.ConfigurePlugins(a => { a.UseTcpReconnection(); });       ////如需永远尝试连接,tryCount设置为-1即可。
+                ////设置结束符
+                if (Terminator == Terminator.None)
+                {
+                    config.SetTcpDataHandlingAdapter(() => { return new NormalDataHandlingAdapter(); });       ////亦或者省略\r\n,但此时调用方不能高速调用,会粘包
+                }
+                else if (Terminator == Terminator.CR)
+                {
+                    config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r"); });       //命令行中使用\r结尾 
+                }
+                else if (Terminator == Terminator.LF)
+                {
+                    config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\n"); });       //命令行中使用\n结尾 
+                }
+                else if (Terminator == Terminator.CRLF)
+                {
+                    config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r\n"); });       //命令行中使用\r\n结尾 
+                }
+                //载入配置
+                TcpClient.Setup(config);
+                ////调用CreateWaitingClient获取到IWaitingClient的对象。
+                WaitClient = TcpClient.CreateWaitingClient(new WaitingOptions()
+                {
+                    FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                    {
+                        return true;
+
+                        //if (response.Data.Length == 1)
+                        //{
+                        //    return true;
+                        //}
+                        //return false;
+                    }
+                });
+
+                TcpClient.Connected = ConnectedVoid;//成功连接到服务器
+                //有客户端断开连接
+                TcpClient.Closed = DisconnectedVoid;
+                //从客户端收到信息
+                TcpClient.Received = ReceivedVoid;
+            }
+            else
+            {
+                TcpService = new TcpService();
+
+                var config = new TouchSocketConfig();
+                config.SetListenIPHosts(new IPHost[] { new IPHost($"{ScannerIp}:{ScannerPort}"), new IPHost(ScannerPort + 1) }); //同时监听两个地址
+                ////设置结束符
+                if (Terminator == Terminator.None)
+                {
+                    config.SetTcpDataHandlingAdapter(() => { return new NormalDataHandlingAdapter(); });       ////亦或者省略\r\n,但此时调用方不能高速调用,会粘包
+                }
+                else if (Terminator == Terminator.CR)
+                {
+                    config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r"); });       //命令行中使用\r结尾 
+                }
+                else if (Terminator == Terminator.LF)
+                {
+                    config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\n"); });       //命令行中使用\n结尾 
+                }
+                else if (Terminator == Terminator.CRLF)
+                {
+                    config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r\n"); });       //命令行中使用\r\n结尾 
+                }
+                //载入配置
+                TcpService.Setup(config);
+
+                /////有客户端成功连接
+                TcpService.Connected = ConnectedVoid;
+                //有客户端断开连接
+                TcpService.Closed = DisconnectedVoid;
+                //从客户端收到信息
+                TcpService.Received = ReceivedVoid;
+
+            }
+        }
+
+        #region 属性
+        public TcpClient TcpClient { get; private set; }
+
+        public TcpService TcpService { get; private set; }
+
+        public Guid Id { get; set; }
+
+        public string Name { get; set; }
+
+        /// <summary>
+        /// 扫码枪编号
+        /// </summary>
+        public int ScannerNo { get; set; }
+
+        public int ScannerPort { get; private set; }
+        public string ScannerIp { get; private set; }
+
+        public TCPConnectType ConnectType { get; private set; }
+
+        public Terminator Terminator { get; private set; }
+
+        public DataEncoding DataEncoding { get; private set; }
+
+        public bool IsConnected
+        {
+            get
+            {
+                if (ConnectType == TCPConnectType.Client)
+                {
+                    return TcpClient.Online;
+                }
+                else
+                {
+                    if (TcpService.Count > 0)
+                        return true;
+                    else return false;
+                }
+            }
+        }
+
+        public int Timeout { get; set; } = 5000;
+
+        private bool _CanExecute = false;
+
+        public bool CanExecute
+        {
+            get { return _CanExecute; }
+            set { SetProperty(ref _CanExecute, value); }
+        }
+
+        public int SelectedTool { get; private set; } = 0;
+
+        public ScannerBrand Brand { get; private set; }
+
+        /// <summary>
+        /// 进入调试模式
+        /// </summary>
+        /// <returns></returns>
+        public bool EnterDebugMode { get; set; }
+
+        private RPoint _CurrentPosition = new RPoint();
+        /// <summary>
+        /// 当前位置
+        /// </summary>
+        public RPoint CurrentPosition
+        {
+            get { return _CurrentPosition; }
+            set { SetProperty(ref _CurrentPosition, value); }
+        }
+        #endregion
+
+        #region 事件接收
+        //-----------------------------------------------服务器---------------------------------------------
+        /// <summary>
+        /// 有客户端成功连接
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ConnectedVoid(ITcpSessionClient client, ConnectedEventArgs e)
+        {
+            CanExecute = true;
+            //调用CreateWaitingClient获取到IWaitingClient的对象。
+            WaitClientServer = client.CreateWaitingClient(new WaitingOptions()
+            {
+                FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                {
+                    return true;
+
+                    //if (response.Data.Length == 1)
+                    //{
+                    //    return true;
+                    //}
+                    //return false;
+                }
+            });
+            ConnectedEvent?.Invoke(this.Id, client, e);
+            return EasyTask.CompletedTask;
+        }
+        /// <summary>
+        /// 有客户端断开连接
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task DisconnectedVoid(ITcpSessionClient client, ClosedEventArgs e)
+        {
+            if (TcpService.Count < 1)
+            {
+                CanExecute = false;
+            }
+            DisconnectedEvent?.Invoke(this.Id, client, e);
+            if (WaitClientServer != null)
+            {
+                if (WaitClientServer.Client.Id == client.Id)
+                {
+                    if (TcpService.Count > 0)
+                    {
+                        WaitClientServer = ((ITcpSessionClient)(TcpService.Clients.First())).CreateWaitingClient(new WaitingOptions()
+                        {
+                            FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                            {
+                                return true;
+
+                                //if (response.Data.Length == 1)
+                                //{
+                                //    return true;
+                                //}
+                                //return false;
+                            }
+                        });
+                    }
+                }
+            }
+            return EasyTask.CompletedTask;
+        }
+        /// <summary>
+        /// 从客户端收到信息
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ReceivedVoid(ITcpSessionClient client, ReceivedDataEventArgs e)
+        {
+            ReceivedEvent?.Invoke(this.Id, client, e);
+            //调用CreateWaitingClient获取到IWaitingClient的对象。
+            WaitClientServer = client.CreateWaitingClient(new WaitingOptions()
+            {
+                FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                {
+                    return true;
+
+                    //if (response.Data.Length == 1)
+                    //{
+                    //    return true;
+                    //}
+                    //return false;
+                }
+            });
+            return EasyTask.CompletedTask;
+        }
+
+        //---------------------------------------------客户端--------------------------------------------
+        /// <summary>
+        /// 连接到服务器时
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ConnectedVoid(ITcpClient client, ConnectedEventArgs e)
+        {
+            CanExecute = true;
+            ConnectedEvent?.Invoke(this.Id, client, e);
+            return EasyTask.CompletedTask;
+        }
+
+        /// <summary>
+        /// 有客户端断开连接
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task DisconnectedVoid(ITcpClient client, ClosedEventArgs e)
+        {
+            CanExecute = false;
+            DisconnectedEvent?.Invoke(this.Id, client, e);
+            return EasyTask.CompletedTask;
+        }
+        /// <summary>
+        /// 从客户端收到信息
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ReceivedVoid(ITcpClient client, ReceivedDataEventArgs e)
+        {
+            ReceivedEvent?.Invoke(this.Id, client, e);
+            return EasyTask.CompletedTask;
+        }
+        #endregion
+
+        #region 连接
+        public void Connect()
+        {
+            if (ConnectType == TCPConnectType.Client)
+            {
+                try
+                {
+                    TcpClient.Connect();
+                    //isFirstConnect = false;
+                }
+                catch (Exception)
+                {
+                    if (bgConnectTask == null)
+                    {
+                        bgConnectTask = Task.Run(async () =>
+                        {
+                            while (true)
+                            {
+                                try
+                                {
+                                    TcpClient.Connect();
+                                    //isFirstConnect = false;
+                                    return;
+                                }
+                                catch (Exception)
+                                {
+                                    await Task.Delay(1000);
+                                }
+                            }
+                        });
+                    }
+                    throw;
+                }
+            }
+            else
+            {
+                TcpService.Start();
+            }
+        }
+
+        public async Task ConnectAsync()
+        {
+            if (ConnectType == TCPConnectType.Client)
+            {
+                try
+                {
+                    await TcpClient.ConnectAsync();
+                    //isFirstConnect = false;
+                }
+                catch (Exception)
+                {
+                    if (bgConnectTask == null)
+                    {
+                        bgConnectTask = Task.Run(async () =>
+                        {
+                            while (true)
+                            {
+                                try
+                                {
+                                    TcpClient.Connect();
+                                    //isFirstConnect = false;
+                                    return;
+                                }
+                                catch (Exception)
+                                {
+                                    await Task.Delay(1000);
+                                }
+                            }
+                        });
+                    }
+                    throw;
+                }
+            }
+            else
+            {
+                await TcpService.StartAsync();
+            }
+        }
+
+        public void Disconnect()
+        {
+            if (TcpClient != null)
+            {
+                TcpClient.Close();
+            }
+            if (TcpService != null)
+            {
+                TcpService.Stop();
+            }
+        }
+
+        public void Dispose()
+        {
+            if (TcpClient != null)
+            {
+                TcpClient.Dispose();
+            }
+            if (TcpService != null)
+            {
+                TcpService.Dispose();
+            }
+        }
+        #endregion
+
+       
+
+        #region 收发数据
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public string SendAndReceive(string send)
+        {
+            if (ConnectType == TCPConnectType.Client)
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+                var returnData = WaitClient.SendThenReturn(encoding.GetBytes(send), Timeout);
+                ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+                ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+                return encoding.GetString(returnData);
+            }
+            else
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClientServer.Client, send);
+                var returnData = WaitClientServer.SendThenReturn(encoding.GetBytes(send), Timeout);
+                ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+                ReceivedEvent?.Invoke(this.Id, WaitClientServer.Client, receivedDataEvent);
+                return encoding.GetString(returnData);
+            }
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public async Task<string> SendAndReceiveAsync(string send)
+        {
+            if (ConnectType == TCPConnectType.Client)
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+                var returnData = await WaitClient.SendThenReturnAsync(encoding.GetBytes(send), Timeout);
+                ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+                ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+                return encoding.GetString(returnData);
+            }
+            else
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClientServer.Client, send);
+                var returnData = await WaitClientServer.SendThenReturnAsync(encoding.GetBytes(send), Timeout);
+                ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+                ReceivedEvent?.Invoke(this.Id, WaitClientServer.Client, receivedDataEvent);
+                return encoding.GetString(returnData);
+            }
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public string SendAndReceive(ITcpSessionClient client, string send)
+        {
+            if (ConnectType == TCPConnectType.Client)
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+                var returnData = WaitClient.SendThenReturn(encoding.GetBytes(send), Timeout);
+                ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+                ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+                return encoding.GetString(returnData);
+            }
+            else
+            {
+                //调用CreateWaitingClient获取到IWaitingClient的对象。
+                var waitClientServer = client.CreateWaitingClient(new WaitingOptions()
+                {
+                    FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                    {
+                        return true;
+
+                        //if (response.Data.Length == 1)
+                        //{
+                        //    return true;
+                        //}
+                        //return false;
+                    }
+                });
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClientServer.Client, send);
+                var returnData = waitClientServer.SendThenReturn(encoding.GetBytes(send), Timeout);
+                ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+                ReceivedEvent?.Invoke(this.Id, WaitClientServer.Client, receivedDataEvent);
+                return encoding.GetString(returnData);
+            }
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public async Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send)
+        {
+            if (ConnectType == TCPConnectType.Client)
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+                var returnData = await WaitClient.SendThenReturnAsync(encoding.GetBytes(send), Timeout);
+                ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+                ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+                return encoding.GetString(returnData);
+            }
+            else
+            {
+                //调用CreateWaitingClient获取到IWaitingClient的对象。
+                var waitClientServer = client.CreateWaitingClient(new WaitingOptions()
+                {
+                    FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                    {
+                        return true;
+
+                        //if (response.Data.Length == 1)
+                        //{
+                        //    return true;
+                        //}
+                        //return false;
+                    }
+                });
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClientServer.Client, send);
+                var returnData = await waitClientServer.SendThenReturnAsync(encoding.GetBytes(send), Timeout);
+                ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+                ReceivedEvent?.Invoke(this.Id, WaitClientServer.Client, receivedDataEvent);
+                return encoding.GetString(returnData);
+            }
+        }
+
+        public void Send(string send)
+        {
+            if (ConnectType == TCPConnectType.Client)
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, TcpClient, send);
+                TcpClient.Send(encoding.GetBytes(send));
+            }
+            else
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClientServer.Client, send);
+                TcpService.Send(WaitClientServer.Client.Id, encoding.GetBytes(send));
+            }
+        }
+
+        public async Task SendAsync(string send)
+        {
+            if (ConnectType == TCPConnectType.Client)
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, TcpClient, send);
+                await TcpClient.SendAsync(encoding.GetBytes(send));
+            }
+            else
+            {
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, WaitClientServer.Client, send);
+                await TcpService.SendAsync(WaitClientServer.Client.Id, encoding.GetBytes(send));
+            }
+        }
+
+        public void Send(ITcpSessionClient client, string send)
+        {
+            try
+            {
+                if (ConnectType == TCPConnectType.Client)
+                {
+                    Encoding encoding = GetEncoding();
+                    SendEvent?.Invoke(this.Id, TcpClient, send);
+                    TcpClient.Send(encoding.GetBytes(send));
+                }
+                else
+                {
+                    Encoding encoding = GetEncoding();
+                    SendEvent?.Invoke(this.Id, client, send);
+                    TcpService.Send(client.Id, encoding.GetBytes(send));
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("给机器人发送数据时出错", ex);
+            }
+
+        }
+
+        public async Task SendAsync(ITcpSessionClient client, string send)
+        {
+            try
+            {
+                if (ConnectType == TCPConnectType.Client)
+                {
+                    Encoding encoding = GetEncoding();
+                    SendEvent?.Invoke(this.Id, TcpClient, send);
+                    await TcpClient.SendAsync(encoding.GetBytes(send));
+                }
+                else
+                {
+                    Encoding encoding = GetEncoding();
+                    SendEvent?.Invoke(this.Id, client, send);
+                    await TcpService.SendAsync(client.Id, encoding.GetBytes(send));
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("给机器人发送数据时出错", ex);
+            }
+
+        }
+        /// <summary>
+        /// 获取编码
+        /// </summary>
+        /// <param name="dataEncoding"></param>
+        /// <returns></returns>
+        public Encoding GetEncoding()
+        {
+            DataEncoding dataEncoding = this.DataEncoding;
+            Encoding encoding;
+            if (dataEncoding == DataEncoding.Default)
+            {
+                encoding = Encoding.Default;
+            }
+            else if (dataEncoding == DataEncoding.ASCII)
+            {
+                encoding = Encoding.ASCII;
+            }
+            else if (dataEncoding == DataEncoding.UTF7)
+            {
+                encoding = Encoding.UTF7;
+            }
+            else if (dataEncoding == DataEncoding.UTF8)
+            {
+                encoding = Encoding.UTF8;
+            }
+            else if (dataEncoding == DataEncoding.UTF32)
+            {
+                encoding = Encoding.UTF32;
+            }
+            else if (dataEncoding == DataEncoding.Unicode)
+            {
+                encoding = Encoding.Unicode;
+            }
+            else if (dataEncoding == DataEncoding.BigEndianUnicode)
+            {
+                encoding = Encoding.BigEndianUnicode;
+            }
+            else if (dataEncoding == DataEncoding.GB2312)
+            {
+
+                encoding = Encoding.GetEncoding("gb2312");
+            }
+            else
+            {
+                encoding = Encoding.Default;
+            }
+            return encoding;
+        }
+        #endregion
+
+        #region 属性通知
+        /// <summary>
+        /// Occurs when a property value changes.
+        /// </summary>
+        public event PropertyChangedEventHandler PropertyChanged;
+
+        /// <summary>
+        /// Checks if a property already matches a desired value. Sets the property and
+        /// notifies listeners only when necessary.
+        /// </summary>
+        /// <typeparam name="T">Type of the property.</typeparam>
+        /// <param name="storage">Reference to a property with both getter and setter.</param>
+        /// <param name="value">Desired value for the property.</param>
+        /// <param name="propertyName">Name of the property used to notify listeners. This
+        /// value is optional and can be provided automatically when invoked from compilers that
+        /// support CallerMemberName.</param>
+        /// <returns>True if the value was changed, false if the existing value matched the
+        /// desired value.</returns>
+        protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
+        {
+            if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
+
+            storage = value;
+            RaisePropertyChanged(propertyName);
+
+            return true;
+        }
+
+        /// <summary>
+        /// Checks if a property already matches a desired value. Sets the property and
+        /// notifies listeners only when necessary.
+        /// </summary>
+        /// <typeparam name="T">Type of the property.</typeparam>
+        /// <param name="storage">Reference to a property with both getter and setter.</param>
+        /// <param name="value">Desired value for the property.</param>
+        /// <param name="propertyName">Name of the property used to notify listeners. This
+        /// value is optional and can be provided automatically when invoked from compilers that
+        /// support CallerMemberName.</param>
+        /// <param name="onChanged">Action that is called after the property value has been changed.</param>
+        /// <returns>True if the value was changed, false if the existing value matched the
+        /// desired value.</returns>
+        protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
+        {
+            if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
+
+            storage = value;
+            onChanged?.Invoke();
+            RaisePropertyChanged(propertyName);
+
+            return true;
+        }
+
+        /// <summary>
+        /// Raises this object's PropertyChanged event.
+        /// </summary>
+        /// <param name="propertyName">Name of the property used to notify listeners. This
+        /// value is optional and can be provided automatically when invoked from compilers
+        /// that support <see cref="CallerMemberNameAttribute"/>.</param>
+        protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
+        {
+            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
+        }
+
+        /// <summary>
+        /// Raises this object's PropertyChanged event.
+        /// </summary>
+        /// <param name="args">The PropertyChangedEventArgs</param>
+        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
+        {
+            PropertyChanged?.Invoke(this, args);
+        }
+
+        public List<DataValue> GetNodesValue()
+        {
+            throw new NotImplementedException();
+        }
+        #endregion
+    }
+}

+ 27 - 0
TeamAAS-VM/Enums/ScannerBrand.cs

@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Attributes;
+using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.ValueConverter;
+
+namespace TeamAAS_VP.Enums
+{
+    /// <summary>
+    /// s扫码枪品牌
+    /// </summary>
+    [TypeConverter(typeof(EnumLocalizationConverter))]
+    public enum ScannerBrand
+    {
+        [Description("默认")]
+        [Localization(ResourceName = "ScannerBrand_默认", ResourceType = typeof(Lang))]
+        Default = 0,
+
+        [Description("新大陆")]
+        [Localization(ResourceName = "ScannerBrand_NLS", ResourceType = typeof(Lang))]
+        NLS = 1,
+    }
+}

+ 28 - 0
TeamAAS-VM/Interfaces/IConfigService.cs

@@ -8,6 +8,7 @@ using TeamAAS_VP.Models.Calibration;
 using TeamAAS_VP.Models.Feeder;
 using TeamAAS_VP.Models.Feeder;
 using TeamAAS_VP.Models.Lights;
 using TeamAAS_VP.Models.Lights;
 using TeamAAS_VP.Models.PLC;
 using TeamAAS_VP.Models.PLC;
+using TeamAAS_VP.Models.Scanner;
 using TeamAAS_VP.Models.ScrewDriver;
 using TeamAAS_VP.Models.ScrewDriver;
 
 
 namespace TeamAAS_VP.Interfaces
 namespace TeamAAS_VP.Interfaces
@@ -64,6 +65,8 @@ namespace TeamAAS_VP.Interfaces
         /// <returns>对应的 <see cref="CameraInfo"/> 实例;若未找到则返回 null。</returns>
         /// <returns>对应的 <see cref="CameraInfo"/> 实例;若未找到则返回 null。</returns>
         CameraInfo GetCamera(Guid id);
         CameraInfo GetCamera(Guid id);
 
 
+
+
         /// <summary>
         /// <summary>
         /// 新增或更新指定的相机信息。
         /// 新增或更新指定的相机信息。
         /// </summary>
         /// </summary>
@@ -93,6 +96,12 @@ namespace TeamAAS_VP.Interfaces
         /// <returns>机器人信息的只读集合快照。</returns>
         /// <returns>机器人信息的只读集合快照。</returns>
         IReadOnlyCollection<RobotInfo> GetAllRobots();
         IReadOnlyCollection<RobotInfo> GetAllRobots();
 
 
+        /// <summary>
+        /// 获取所有已注册的扫码枪信息的只读集合。
+        /// </summary>
+        /// <returns>扫码枪信息的只读集合快照。</returns>
+        IReadOnlyCollection<ScannerInfo> GetAllScanners();
+
         /// <summary>
         /// <summary>
         /// 根据标识获取单个机器人信息。
         /// 根据标识获取单个机器人信息。
         /// </summary>
         /// </summary>
@@ -100,6 +109,12 @@ namespace TeamAAS_VP.Interfaces
         /// <returns>对应的 <see cref="RobotInfo"/> 实例;若未找到则返回 null。</returns>
         /// <returns>对应的 <see cref="RobotInfo"/> 实例;若未找到则返回 null。</returns>
         RobotInfo GetRobot(Guid id);
         RobotInfo GetRobot(Guid id);
 
 
+        /// <summary>
+        /// 根据标识获取单个扫码枪信息。
+        /// </summary>
+        /// <param name="id">扫码枪的唯一标识符。</param>
+        /// <returns>对应的 <see cref="ScannerInfo"/> 实例;若未找到则返回 null。</returns>
+        ScannerInfo GetScanner(Guid id);
         /// <summary>
         /// <summary>
         /// 新增或更新指定的机器人信息。
         /// 新增或更新指定的机器人信息。
         /// </summary>
         /// </summary>
@@ -107,6 +122,12 @@ namespace TeamAAS_VP.Interfaces
         /// <exception cref="ArgumentNullException">当 <paramref name="robot"/> 为 null 时抛出。</exception>
         /// <exception cref="ArgumentNullException">当 <paramref name="robot"/> 为 null 时抛出。</exception>
         RobotInfo AddOrUpdateRobot(RobotInfo robot);
         RobotInfo AddOrUpdateRobot(RobotInfo robot);
 
 
+        /// <summary>
+        /// 新增或更新指定的扫码枪信息。
+        /// </summary>
+        /// <param name="scanner">要新增或更新的扫码枪信息,不能为 null。</param>
+        /// <exception cref="ArgumentNullException">当 <paramref name="scanner"/> 为 null 时抛出。</exception>
+        ScannerInfo AddOrUpdateScanner(ScannerInfo scanner);
         /// <summary>
         /// <summary>
         /// 移除指定标识的机器人信息。
         /// 移除指定标识的机器人信息。
         /// </summary>
         /// </summary>
@@ -114,6 +135,13 @@ namespace TeamAAS_VP.Interfaces
         /// <returns>如果找到并移除成功则返回 true;否则返回 false。</returns>
         /// <returns>如果找到并移除成功则返回 true;否则返回 false。</returns>
         bool RemoveRobot(Guid id);
         bool RemoveRobot(Guid id);
 
 
+        /// <summary>
+        /// 移除指定标识的扫码枪信息。
+        /// </summary>
+        /// <param name="id">要移除的扫码枪的唯一标识符。</param>
+        /// <returns>如果找到并移除成功则返回 true;否则返回 false。</returns>
+        bool RemoveScanner(Guid id);
+
         /// <summary>
         /// <summary>
         /// 判断是否包含指定标识的机器人配置。
         /// 判断是否包含指定标识的机器人配置。
         /// </summary>
         /// </summary>

+ 13 - 0
TeamAAS-VM/Interfaces/IProductService.cs

@@ -345,6 +345,13 @@ namespace TeamAAS_VP.Interfaces
         /// <param name="robotPointName"></param>
         /// <param name="robotPointName"></param>
         void AddRobotPointToProduct(Guid robotId, string robotPointName);
         void AddRobotPointToProduct(Guid robotId, string robotPointName);
 
 
+
+        /// <summary>
+        /// 增加扫码枪时,需要对产品的扫码枪点位进行增加
+        /// </summary>
+        /// <param name="scannerId"></param>
+        /// <param name="scannerPointName"></param>
+        void AddScannerPointToProduct(Guid scannerId, string scannerPointName);
         /// <summary>
         /// <summary>
         /// 增加机器人时,需要对产品的机器人点位进行增加
         /// 增加机器人时,需要对产品的机器人点位进行增加
         /// </summary>
         /// </summary>
@@ -359,6 +366,12 @@ namespace TeamAAS_VP.Interfaces
         /// <param name="robotId"></param>
         /// <param name="robotId"></param>
         void RemoveRobotPointFromProduct(Guid robotId);
         void RemoveRobotPointFromProduct(Guid robotId);
 
 
+        /// <summary>
+        /// 删除扫码枪时,需要对产品的扫码枪点位进行删除
+        /// </summary>
+        /// <param name="scannerId"></param>
+        void RemoveScannerPointFromProduct(Guid scannerId);
+
         /// <summary>
         /// <summary>
         /// 删除机器人时,需要对产品的机器人点位进行删除
         /// 删除机器人时,需要对产品的机器人点位进行删除
         /// </summary>
         /// </summary>

+ 160 - 0
TeamAAS-VM/Interfaces/IScanner.cs

@@ -0,0 +1,160 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Models;
+using TouchSocket.Sockets;
+
+namespace TeamAAS_VP.Interfaces
+{
+    public interface IScanner : IDisposable
+    {
+        #region 基础信息
+        /// <summary>
+        /// 客户端
+        /// </summary>
+        TcpClient TcpClient { get; }
+        /// <summary>
+        /// 服务器
+        /// </summary>
+        TcpService TcpService { get; }
+        /// <summary>
+        /// 扫码枪ID
+        /// </summary>
+        Guid Id { get; set; }
+
+        string Name { get; set; }
+
+        /// <summary>
+        /// 扫码枪编号
+        /// </summary>
+        int ScannerNo { get; set; }
+
+        /// <summary>
+        /// 扫码枪端口
+        /// </summary>
+        int ScannerPort { get; }
+        /// <summary>
+        /// 扫码枪IP地址
+        /// </summary>
+        string ScannerIp { get; }
+        /// <summary>
+        /// 扫码枪通讯方式
+        /// </summary>
+        TCPConnectType ConnectType { get; }
+        /// <summary>
+        /// 结束符
+        /// </summary>
+        Terminator Terminator { get; }
+        /// <summary>
+        /// 通讯数据编码
+        /// </summary>
+        DataEncoding DataEncoding { get; }
+
+        //RobotBrand Brand { get; }
+
+        event Action<Guid, object, ConnectedEventArgs> ConnectedEvent;
+        event Action<Guid, object, ClosedEventArgs> DisconnectedEvent;
+        event Action<Guid, object, ReceivedDataEventArgs> ReceivedEvent;
+        event Action<Guid, object, string> SendEvent;
+
+        bool CanExecute { get; }
+
+        int SelectedTool { get; }
+
+        /// <summary>
+        /// 进入调试模式
+        /// </summary>
+        /// <returns></returns>
+        bool EnterDebugMode { get; set; }
+
+        //当前位置
+        RPoint CurrentPosition { get; }
+
+        #endregion
+
+        #region 连接通讯
+        /// <summary>
+        /// 扫码枪连接状态
+        /// </summary>
+        bool IsConnected { get; }
+        /// <summary>
+        /// 超时时间
+        /// </summary>
+        int Timeout { get; set; }
+        /// <summary>
+        /// 连接扫码枪
+        /// </summary>
+        void Connect();
+        /// <summary>
+        /// 连接扫码枪
+        /// </summary>
+        /// <returns></returns>
+        Task ConnectAsync();
+        /// <summary>
+        /// 断开连接
+        /// </summary>
+        void Disconnect();
+        #endregion
+
+        
+
+        #region 数据发送接收
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        string SendAndReceive(string send);
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        Task<string> SendAndReceiveAsync(string send);
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        string SendAndReceive(ITcpSessionClient client, string send);
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send);
+
+        /// <summary>
+        /// 发送数据
+        /// </summary>
+        /// <param name="send"></param>
+        void Send(string send);
+
+        /// <summary>
+        /// 发送数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        Task SendAsync(string send);
+
+        /// <summary>
+        /// 发送数据
+        /// </summary>
+        /// <param name="send"></param>
+        void Send(ITcpSessionClient client, string send);
+
+        /// <summary>
+        /// 发送数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        Task SendAsync(ITcpSessionClient client, string send);
+
+        Encoding GetEncoding();
+        #endregion
+    }
+}

+ 171 - 0
TeamAAS-VM/Interfaces/IScannerService.cs

@@ -0,0 +1,171 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Models.Scanner;
+
+namespace TeamAAS_VP.Interfaces
+{
+    /// <summary>
+    /// 提供扫码枪生命周期管理的接口,包括创建、获取及注销扫码枪实例。
+    /// </summary>
+    public interface IScannerService
+    {
+        /// <summary>
+        /// 异步创建并注册一个扫码枪实例。
+        /// </summary>
+        /// <param name="id">要创建扫码枪的唯一标识(GUID)。</param>
+        /// <param name="scannerInfo">用于初始化扫码枪的信息对象,不能为空。</param>
+        /// <returns>
+        /// 返回一个 <see cref="Task{Boolean}"/>;任务完成时布尔值指示创建是否成功。
+        /// </returns>
+        /// <exception cref="ArgumentNullException">当 <paramref name="scannerInfo"/> 为 null 时抛出。</exception>
+        Task<bool> CreateScannerAsync(Guid id, ScannerInfo scannerInfo);
+
+        /// <summary>
+        /// 同步创建并注册一个扫码枪实例。
+        /// </summary>
+        /// <param name="id">要创建扫码枪的唯一标识(GUID)。</param>
+        /// <param name="scannerInfo">用于初始化扫码枪的信息对象,不能为空。</param>
+        /// <returns>返回布尔值,指示创建是否成功。</returns>
+        /// <exception cref="ArgumentNullException">当 <paramref name="scannerInfo"/> 为 null 时抛出。</exception>
+        bool CreateScanner(Guid id, ScannerInfo scannerInfo);
+
+        /// <summary>
+        /// 获取已注册的扫码枪实例(同步)。通过 GUID 查找。
+        /// </summary>
+        /// <param name="id">要获取的扫码枪唯一标识(GUID)。</param>
+        /// <returns>
+        /// 已注册的 <see cref="IScanner"/> 实例;如果未找到对应扫码枪,返回 null(或实现可选择抛出异常)。
+        /// </returns>
+        IScanner GetScanner(Guid id);
+        /// <summary>
+        /// 异步获取已注册的扫码枪实例。通过 GUID 查找。
+        /// </summary>
+        /// <param name="id">要获取的扫码枪唯一标识(GUID)。</param>
+        /// <returns>
+        /// 一个任务,完成时返回对应的 <see cref="IScanner"/> 实例;若未找到可返回 null。
+        /// </returns>
+        Task<IScanner> GetScannerAsync(Guid id);
+        /// <summary>
+        /// 获取所有已注册的扫码枪实例(同步)。
+        /// </summary>
+        /// <returns></returns>
+        IReadOnlyCollection<IScanner> GetAllScanners();
+
+        /// <summary>
+        /// 获取所有已注册的扫码枪实例(异步)。
+        /// </summary>
+        /// <returns></returns>
+        Task<IReadOnlyCollection<IScanner>> GetAllScannersAsync();
+     
+
+        /// <summary>
+        /// 尝试获取已注册的扫码枪实例(同步)。通过 GUID 查找。
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="scanner"></param>
+        /// <returns></returns>
+        bool TryGetScanner(Guid id, out IScanner scanner);
+
+        /// <summary>
+        /// 尝试获取已注册的扫码枪实例(异步)。通过 GUID 查找。
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        Task<(bool found, IScanner scanner)> TryGetScannerAsync(Guid id);
+        /// <summary>
+        /// 检查扫码枪是否已注册(同步)。通过 GUID 检查。
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        bool ContainsScanner(Guid id);
+        /// <summary>
+        /// 检查扫码枪是否已注册(异步)。通过 GUID 检查。
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        Task<bool> ContainsScannerAsync(Guid id);
+        /// <summary>
+        /// 移除已注册的扫码枪实例(同步)。通过 GUID 移除。
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns>返回是否成功移除</returns>
+        bool RemoveScanner(Guid id);
+        /// <summary>
+        /// 移除已注册的扫码枪实例(异步)。通过 GUID 移除。
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        Task<bool> RemoveScannerAsync(Guid id);
+        /// <summary>
+        /// 异步注销并移除指定的扫码枪注册信息。通过 GUID 注销。
+        /// </summary>
+        /// <param name="id">要注销的扫码枪唯一标识(GUID)。</param>
+        /// <returns>表示注销操作完成的任务。</returns>
+        Task UnRegisterScannerAsync(Guid id);
+
+        /// <summary>
+        /// 同步注销并移除指定的扫码枪注册信息。通过 GUID 注销。
+        /// </summary>
+        /// <param name="id">要注销的扫码枪唯一标识(GUID)。</param>
+        void UnRegisterScanner(Guid id);
+
+        /// <summary>
+        /// 获取已注册的扫码枪实例(同步)。通过扫码枪编号(int)查找。
+        /// </summary>
+        /// <param name="number">扫码枪编号(整型)。</param>
+        /// <returns>
+        /// 已注册的 <see cref="IScanner"/> 实例;如果未找到对应扫码枪,返回 null(或实现可选择抛出异常)。
+        /// </returns>
+        IScanner GetScannerByNumber(int number);
+
+        /// <summary>
+        /// 异步获取已注册的扫码枪实例。通过扫码枪编号(int)查找。
+        /// </summary>
+        /// <param name="number">扫码枪编号(整型)。</param>
+        /// <returns>
+        /// 一个任务,完成时返回对应的 <see cref="IScanner"/> 实例;若未找到可返回 null。
+        /// </returns>
+        Task<IScanner> GetScannerByNumberAsync(int number);
+        /// <summary>
+        /// 异步注销并移除指定的扫码枪注册信息。通过扫码枪编号(int)注销。
+        /// </summary>
+        /// <param name="number">要注销的扫码枪编号(整型)。</param>
+        /// <returns>表示注销操作完成的任务。</returns>
+        Task UnRegisterScannerByNumberAsync(int number);
+
+        /// <summary>
+        /// 同步注销并移除指定的扫码枪注册信息。通过扫码枪编号(int)注销。
+        /// </summary>
+        /// <param name="number">要注销的扫码枪编号(整型)。</param>
+        void UnRegisterScannerByNumber(int number);
+
+        /// <summary>
+        /// 移除所有扫码枪
+        /// </summary>
+        void RemoveAllScanners();
+
+        /// <summary>
+        /// 初始化所有扫码枪
+        /// </summary>
+        /// <param name="scanners"></param>
+        /// <returns></returns>
+        (bool IsSucceed, string Message) InitializeAllScanners(ScannerInfo[] scanners);
+
+        /// <summary>
+        /// 初始化所有扫码枪 (异步)
+        /// </summary>
+        /// <param name="scanners"></param>
+        Task<(bool IsSucceed, string Message)> InitializeAllScannersAsync(ScannerInfo[] scanners);
+
+        /// <summary>
+        /// 更新扫码枪编号
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="newNumber"></param>
+        void UpdateScannerNumber(Guid id, int newNumber);
+    }
+}

+ 9 - 0
TeamAAS-VM/Models/DeviceInfo.cs

@@ -72,6 +72,13 @@ namespace TeamAAS_VP.Models
         /// </summary>
         /// </summary>
         public string comp { get => _comp; set => SetProperty(ref _comp, value); }
         public string comp { get => _comp; set => SetProperty(ref _comp, value); }
 
 
+        private string _XnSN;
+        /// <summary>
+        /// 虚拟SN
+        /// 
+        /// </summary>
+        public string XnSN { get => _XnSN; set => SetProperty(ref _XnSN, value); }
+
         private bool _saveCsv;
         private bool _saveCsv;
         /// <summary>
         /// <summary>
         /// 是否保存CSV文件,默认不保存
         /// 是否保存CSV文件,默认不保存
@@ -107,6 +114,7 @@ namespace TeamAAS_VP.Models
             comp = string.Empty;
             comp = string.Empty;
             MesUrl = string.Empty;
             MesUrl = string.Empty;
             EnableMES = false;
             EnableMES = false;
+            XnSN = string.Empty;
         }
         }
 
 
         public DeviceInfo Copy()
         public DeviceInfo Copy()
@@ -123,6 +131,7 @@ namespace TeamAAS_VP.Models
                 comp = this.comp,
                 comp = this.comp,
                 MesUrl = this.MesUrl,
                 MesUrl = this.MesUrl,
                 EnableMES = this.EnableMES,
                 EnableMES = this.EnableMES,
+                XnSN=this.XnSN,
                 SaveCsv = this.SaveCsv,
                 SaveCsv = this.SaveCsv,
                 SaveCsvPath = this.SaveCsvPath,
                 SaveCsvPath = this.SaveCsvPath,
                 EnableDoubleMes = this.EnableDoubleMes,
                 EnableDoubleMes = this.EnableDoubleMes,

+ 44 - 0
TeamAAS-VM/Models/ScanRs232ConfigModel.cs

@@ -0,0 +1,44 @@
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Models
+{
+    public class ScanRs232ConfigModel : BindableBase
+    {
+        private string _PortName = "COM9";
+        public string PortName
+        {
+            get { return _PortName; }
+            set { SetProperty(ref _PortName, value); }
+        }
+        private int _BaudRate = 9600;
+        public int BaudRate
+        {
+            get { return _BaudRate; }
+            set { SetProperty(ref _BaudRate, value); }
+        }
+        private Parity _Parity = Parity.None;
+        public Parity Parity
+        {
+            get { return _Parity; }
+            set { SetProperty(ref _Parity, value); }
+        }
+        private StopBits _StopBits = StopBits.One;
+        public StopBits StopBits
+        {
+            get { return _StopBits; }
+            set { SetProperty(ref _StopBits, value); }
+        }
+        private int _DataBits = 8;
+        public int DataBits
+        {
+            get { return _DataBits; }
+            set { SetProperty(ref _DataBits, value); }
+        }
+    }
+}

+ 111 - 0
TeamAAS-VM/Models/Scanner/ScannerInfo.cs

@@ -0,0 +1,111 @@
+using Newtonsoft.Json;
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Enums;
+
+namespace TeamAAS_VP.Models.Scanner
+{
+    /// <summary>
+    /// 扫码枪参数
+    /// </summary>
+    public class ScannerInfo:BindableBase
+    {
+        private Guid _Id;
+
+        public Guid Id
+        {
+            get { return _Id; }
+            set { SetProperty(ref _Id, value); }
+        }
+
+        private int _ScannerNo;
+        /// <summary>
+        /// 扫码枪编号
+        /// </summary>
+        public int ScannerNo
+        {
+            get { return _ScannerNo; }
+            set { SetProperty(ref _ScannerNo, value); }
+        }
+
+        private string _ScannerName;
+        /// <summary>
+        /// 扫码枪名称
+        /// </summary>
+        public string ScannerName
+        {
+            get { return _ScannerName; }
+            set { SetProperty(ref _ScannerName, value); }
+        }
+
+        private ScannerBrand _ScannerBrand = ScannerBrand.Default;
+        /// <summary>
+        /// 扫码枪品牌
+        /// </summary>
+        public ScannerBrand ScannerBrand
+        {
+            get { return _ScannerBrand; }
+            set { SetProperty(ref _ScannerBrand , value); }
+        }
+
+        private TCPConnectType _ConnectType = TCPConnectType.Client;
+        /// <summary>
+        /// 通讯方式
+        /// </summary>
+        public TCPConnectType ConnectType
+        {
+            get { return _ConnectType; }
+            set { SetProperty(ref _ConnectType, value); }
+        }
+
+        private string _IP = "192.168.0.1";
+        /// <summary>
+        /// IP地址
+        /// </summary>
+        public string IP
+        {
+            get { return _IP; }
+            set { SetProperty(ref _IP, value); }
+        }
+
+        private int _Port = 3600;
+        /// <summary>
+        /// 端口号
+        /// </summary>
+        public int Port
+        {
+            get { return _Port; }
+            set { SetProperty(ref _Port, value); }
+        }
+
+        private Terminator _Terminator = Terminator.CRLF;
+        /// <summary>
+        /// 结束符
+        /// </summary>
+        public Terminator Terminator
+        {
+            get { return _Terminator; }
+            set { SetProperty(ref _Terminator, value); }
+        }
+
+        private DataEncoding _DataEncoding = DataEncoding.Default;
+
+        /// <summary>
+        /// 数据编码格式
+        /// </summary>
+        public DataEncoding DataEncoding
+        {
+            get { return _DataEncoding; }
+            set { SetProperty(ref _DataEncoding, value); }
+        }
+
+        public ScannerInfo Clone()
+        {
+            return JsonConvert.DeserializeObject<ScannerInfo>(JsonConvert.SerializeObject(this)); ;
+        }
+    }
+}

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

@@ -296,6 +296,16 @@ namespace TeamAAS_VP.Models
             get => _CodeUse2;
             get => _CodeUse2;
             set => SetProperty(ref _CodeUse2, value);
             set => SetProperty(ref _CodeUse2, value);
         }
         }
+
+        private bool _ScannerUse;
+        /// <summary>
+        /// 扫码器是否使用
+        /// </summary>
+        public bool ScannerUse
+        {
+            get => _ScannerUse;
+            set => SetProperty(ref _ScannerUse, value);
+        }
         private bool _Camera1Use;
         private bool _Camera1Use;
         /// <summary>
         /// <summary>
         /// 相机1是否使用
         /// 相机1是否使用

+ 82 - 1
TeamAAS-VM/Resources/Languages/Lang.Designer.cs

@@ -19,7 +19,7 @@ namespace TeamAAS_VP.Resources.Languages {
     // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
     // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
     // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
     // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
     // (以 /str 作为命令选项),或重新生成 VS 项目。
     // (以 /str 作为命令选项),或重新生成 VS 项目。
-    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")]
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
     [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
     [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
     [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
     [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
     public class Lang {
     public class Lang {
@@ -1563,6 +1563,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
             }
         }
         }
         
         
+        /// <summary>
+        ///   查找类似 初始化扫码枪时出错 的本地化字符串。
+        /// </summary>
+        public static string 初始化扫码枪时出错 {
+            get {
+                return ResourceManager.GetString("初始化扫码枪时出错", resourceCulture);
+            }
+        }
+        
         /// <summary>
         /// <summary>
         ///   查找类似 初始化数据库 的本地化字符串。
         ///   查找类似 初始化数据库 的本地化字符串。
         /// </summary>
         /// </summary>
@@ -2904,6 +2913,51 @@ namespace TeamAAS_VP.Resources.Languages {
             }
             }
         }
         }
         
         
+        /// <summary>
+        ///   查找类似 扫码机已连接 的本地化字符串。
+        /// </summary>
+        public static string 扫码机已连接 {
+            get {
+                return ResourceManager.GetString("扫码机已连接", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   查找类似 扫码机未连接 的本地化字符串。
+        /// </summary>
+        public static string 扫码机未连接 {
+            get {
+                return ResourceManager.GetString("扫码机未连接", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   查找类似 扫码枪 的本地化字符串。
+        /// </summary>
+        public static string 扫码枪 {
+            get {
+                return ResourceManager.GetString("扫码枪", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   查找类似 扫码枪列表 的本地化字符串。
+        /// </summary>
+        public static string 扫码枪列表 {
+            get {
+                return ResourceManager.GetString("扫码枪列表", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   查找类似 扫码枪接收信息时出错 的本地化字符串。
+        /// </summary>
+        public static string 扫码枪接收信息时出错 {
+            get {
+                return ResourceManager.GetString("扫码枪接收信息时出错", resourceCulture);
+            }
+        }
+        
         /// <summary>
         /// <summary>
         ///   查找类似 抛料数 的本地化字符串。
         ///   查找类似 抛料数 的本地化字符串。
         /// </summary>
         /// </summary>
@@ -3291,6 +3345,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
             }
         }
         }
         
         
+        /// <summary>
+        ///   查找类似 是否保存扫码枪 的本地化字符串。
+        /// </summary>
+        public static string 是否保存扫码枪 {
+            get {
+                return ResourceManager.GetString("是否保存扫码枪", resourceCulture);
+            }
+        }
+        
         /// <summary>
         /// <summary>
         ///   查找类似 是否保存机器人? 的本地化字符串。
         ///   查找类似 是否保存机器人? 的本地化字符串。
         /// </summary>
         /// </summary>
@@ -3453,6 +3516,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
             }
         }
         }
         
         
+        /// <summary>
+        ///   查找类似 是否移除扫码枪 的本地化字符串。
+        /// </summary>
+        public static string 是否移除扫码枪 {
+            get {
+                return ResourceManager.GetString("是否移除扫码枪", resourceCulture);
+            }
+        }
+        
         /// <summary>
         /// <summary>
         ///   查找类似 是否删除机器人? 的本地化字符串。
         ///   查找类似 是否删除机器人? 的本地化字符串。
         /// </summary>
         /// </summary>
@@ -5253,6 +5325,15 @@ namespace TeamAAS_VP.Resources.Languages {
             }
             }
         }
         }
         
         
+        /// <summary>
+        ///   查找类似 请设置扫码机串口 的本地化字符串。
+        /// </summary>
+        public static string 请设置扫码机串口 {
+            get {
+                return ResourceManager.GetString("请设置扫码机串口", resourceCulture);
+            }
+        }
+        
         /// <summary>
         /// <summary>
         ///   查找类似 请输入产品名称 的本地化字符串。
         ///   查找类似 请输入产品名称 的本地化字符串。
         /// </summary>
         /// </summary>

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

@@ -2041,4 +2041,31 @@
   <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" type="System.Resources.ResXNullRef, System.Windows.Forms">
   <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" type="System.Resources.ResXNullRef, System.Windows.Forms">
     <value />
     <value />
   </data>
   </data>
+  <data name="是否移除扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="是否保存扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪列表" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机已连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机未连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="请设置扫码机串口" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="初始化扫码枪时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪接收信息时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
 </root>
 </root>

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

@@ -2041,4 +2041,31 @@
   <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" type="System.Resources.ResXNullRef, System.Windows.Forms">
   <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" type="System.Resources.ResXNullRef, System.Windows.Forms">
     <value />
     <value />
   </data>
   </data>
+  <data name="是否移除扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="是否保存扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪列表" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机已连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机未连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="请设置扫码机串口" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="初始化扫码枪时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪接收信息时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
 </root>
 </root>

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

@@ -2187,4 +2187,40 @@
     <value>NG数量</value>
     <value>NG数量</value>
     <comment>NG数量</comment>
     <comment>NG数量</comment>
   </data>
   </data>
+  <data name="是否移除扫码枪" xml:space="preserve">
+    <value>是否移除扫码枪</value>
+    <comment>是否移除扫码枪</comment>
+  </data>
+  <data name="是否保存扫码枪" xml:space="preserve">
+    <value>是否保存扫码枪</value>
+    <comment>是否保存扫码枪</comment>
+  </data>
+  <data name="扫码枪" xml:space="preserve">
+    <value>扫码枪</value>
+    <comment>扫码枪</comment>
+  </data>
+  <data name="扫码枪列表" xml:space="preserve">
+    <value>扫码枪列表</value>
+    <comment>扫码枪列表</comment>
+  </data>
+  <data name="扫码机已连接" xml:space="preserve">
+    <value>扫码机已连接</value>
+    <comment>扫码机已连接</comment>
+  </data>
+  <data name="扫码机未连接" xml:space="preserve">
+    <value>扫码机未连接</value>
+    <comment>扫码机未连接</comment>
+  </data>
+  <data name="请设置扫码机串口" xml:space="preserve">
+    <value>请设置扫码机串口</value>
+    <comment>请设置扫码机串口</comment>
+  </data>
+  <data name="初始化扫码枪时出错" xml:space="preserve">
+    <value>初始化扫码枪时出错</value>
+    <comment>初始化扫码枪时出错</comment>
+  </data>
+  <data name="扫码枪接收信息时出错" xml:space="preserve">
+    <value>扫码枪接收信息时出错</value>
+    <comment>扫码枪接收信息时出错</comment>
+  </data>
 </root>
 </root>

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

@@ -2041,4 +2041,31 @@
   <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" type="System.Resources.ResXNullRef, System.Windows.Forms">
   <data name="ProcedureSaveImagePathModel_Month_Day_Formula_ProductSN_Time" type="System.Resources.ResXNullRef, System.Windows.Forms">
     <value />
     <value />
   </data>
   </data>
+  <data name="是否移除扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="是否保存扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪列表" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机已连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码机未连接" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="请设置扫码机串口" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="初始化扫码枪时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
+  <data name="扫码枪接收信息时出错" type="System.Resources.ResXNullRef, System.Windows.Forms">
+    <value />
+  </data>
 </root>
 </root>

+ 98 - 0
TeamAAS-VM/Services/ConfigService.cs

@@ -18,6 +18,7 @@ using TeamAAS_VP.Models.Calibration;
 using TeamAAS_VP.Models.Feeder;
 using TeamAAS_VP.Models.Feeder;
 using TeamAAS_VP.Models.Lights;
 using TeamAAS_VP.Models.Lights;
 using TeamAAS_VP.Models.PLC;
 using TeamAAS_VP.Models.PLC;
+using TeamAAS_VP.Models.Scanner;
 using TeamAAS_VP.Models.ScrewDriver;
 using TeamAAS_VP.Models.ScrewDriver;
 using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.Resources.Languages;
 using WPFLocalizeExtension.Engine;
 using WPFLocalizeExtension.Engine;
@@ -36,6 +37,7 @@ namespace TeamAAS_VP.Services
             // 将路径集中管理于本类,当前使用现有 FilePath 值以保持兼容
             // 将路径集中管理于本类,当前使用现有 FilePath 值以保持兼容
             public static readonly string CamerasConfigurationPath = "..//Config//CameraConfiguration.cfg";
             public static readonly string CamerasConfigurationPath = "..//Config//CameraConfiguration.cfg";
             public static readonly string RobotsConfigurationPath = "..//Config//RobotsConfiguration.cfg";
             public static readonly string RobotsConfigurationPath = "..//Config//RobotsConfiguration.cfg";
+            public static readonly string ScannersConfigurationPath = "..//Config//ScannersConfiguration.cfg";
             public static readonly string FeedersConfigurationPath = "..//Config//FeedersConfiguration.cfg";
             public static readonly string FeedersConfigurationPath = "..//Config//FeedersConfiguration.cfg";
             public static readonly string PlcConfigurationPath = "..//Config//PlcConfiguration.cfg";
             public static readonly string PlcConfigurationPath = "..//Config//PlcConfiguration.cfg";
             public static readonly string BgTcpIpConfigurationPath = "..//Config//BgTcpIpConfiguration.cfg";
             public static readonly string BgTcpIpConfigurationPath = "..//Config//BgTcpIpConfiguration.cfg";
@@ -58,6 +60,8 @@ namespace TeamAAS_VP.Services
         private readonly object _sync = new object();
         private readonly object _sync = new object();
         private ObservableCollection<CameraInfo> Cameras { get; set; }
         private ObservableCollection<CameraInfo> Cameras { get; set; }
         private ObservableCollection<RobotInfo> Robots { get; set; }
         private ObservableCollection<RobotInfo> Robots { get; set; }
+
+        private ObservableCollection<ScannerInfo> Scanners { get; set; }
         private ObservableCollection<FeederInfo> Feeders { get; set; }
         private ObservableCollection<FeederInfo> Feeders { get; set; }
         // 螺丝供料器(物料)集合
         // 螺丝供料器(物料)集合
         private ObservableCollection<ScrewFeederInfo> ScrewFeeders { get; set; }
         private ObservableCollection<ScrewFeederInfo> ScrewFeeders { get; set; }
@@ -155,6 +159,13 @@ namespace TeamAAS_VP.Services
                     Robots = new ObservableCollection<RobotInfo>();
                     Robots = new ObservableCollection<RobotInfo>();
                     FileHelper.WriteJsonFile(Robots, ConfigPaths.RobotsConfigurationPath);
                     FileHelper.WriteJsonFile(Robots, ConfigPaths.RobotsConfigurationPath);
                 }
                 }
+                if (File.Exists(ConfigPaths.ScannersConfigurationPath))
+                    Scanners = FileHelper.ReadJsonFile<ObservableCollection<ScannerInfo>>(ConfigPaths.ScannersConfigurationPath);
+                else
+                {
+                    Scanners = new ObservableCollection<ScannerInfo>();
+                    FileHelper.WriteJsonFile(Scanners, ConfigPaths.ScannersConfigurationPath);
+                }
                 if (File.Exists(ConfigPaths.FeedersConfigurationPath))
                 if (File.Exists(ConfigPaths.FeedersConfigurationPath))
                     Feeders = FileHelper.ReadJsonFile<ObservableCollection<FeederInfo>>(ConfigPaths.FeedersConfigurationPath);
                     Feeders = FileHelper.ReadJsonFile<ObservableCollection<FeederInfo>>(ConfigPaths.FeedersConfigurationPath);
                 else
                 else
@@ -277,6 +288,7 @@ namespace TeamAAS_VP.Services
             {
             {
                 FileHelper.WriteJsonFile(Cameras, ConfigPaths.CamerasConfigurationPath);
                 FileHelper.WriteJsonFile(Cameras, ConfigPaths.CamerasConfigurationPath);
                 FileHelper.WriteJsonFile(Robots, ConfigPaths.RobotsConfigurationPath);
                 FileHelper.WriteJsonFile(Robots, ConfigPaths.RobotsConfigurationPath);
+                FileHelper.WriteJsonFile(Scanners, ConfigPaths.ScannersConfigurationPath);
                 FileHelper.WriteJsonFile(Feeders, ConfigPaths.FeedersConfigurationPath);
                 FileHelper.WriteJsonFile(Feeders, ConfigPaths.FeedersConfigurationPath);
                 FileHelper.WriteJsonFile(Plcs, ConfigPaths.PlcConfigurationPath);
                 FileHelper.WriteJsonFile(Plcs, ConfigPaths.PlcConfigurationPath);
                 FileHelper.WriteJsonFile(BgCommunicate, ConfigPaths.BgTcpIpConfigurationPath);
                 FileHelper.WriteJsonFile(BgCommunicate, ConfigPaths.BgTcpIpConfigurationPath);
@@ -538,6 +550,92 @@ namespace TeamAAS_VP.Services
 
 
         }
         }
 
 
+        #endregion
+
+        #region Scanners
+        /// <summary>
+        /// 获取所有扫码枪配置的只读集合。
+        /// </summary>
+        /// <returns>扫码枪配置的只读集合。</returns>
+        public IReadOnlyCollection<ScannerInfo> GetAllScanners() { lock (_sync) { return Scanners.ToList().AsReadOnly(); } }
+
+        /// <summary>
+        /// 根据标识获取单个扫码枪配置。
+        /// </summary>
+        /// <param name="id">扫码枪的 Guid 标识。</param>
+        /// <returns>找到则返回对应的 <see cref="ScannerInfo"/>,否则返回 <c>null</c>。</returns>
+        public ScannerInfo GetScanner(Guid id) { lock (_sync) { return Scanners.FirstOrDefault(r => r.Id == id); } }
+
+        /// <summary>
+        /// 新增或更新扫码枪配置,操作后持久化至配置文件。
+        /// 新增时为扫码枪分配连续的 ScannerNo 编号。
+        /// </summary>
+        /// <param name="scanner">要添加或更新的扫码枪配置。</param>
+        /// <returns>已添加或更新的 <see cref="ScannerInfo"/>;输入为 <c>null</c> 时返回 <c>null</c>。</returns>
+        public ScannerInfo AddOrUpdateScanner(ScannerInfo scanner)
+        {
+            if (scanner == null) return null;
+            lock (_sync)
+            {
+                var exist = Scanners.FirstOrDefault(r => r.Id == scanner.Id);
+                if (exist != null)
+                {
+                    var idx = Scanners.IndexOf(exist);
+                    Scanners[idx] = scanner;
+                }
+                else
+                {
+                    scanner.ScannerNo = Scanners.Count + 1;
+                    Scanners.Add(scanner);
+                }
+
+            }
+            FileHelper.WriteJsonFile(Scanners, ConfigPaths.ScannersConfigurationPath);
+            return scanner;
+        }
+
+        /// <summary>
+        /// 根据标识移除扫码枪配置并重新编号剩余扫码枪。
+        /// 操作后持久化配置文件。
+        /// </summary>
+        /// <param name="id">要移除的扫码枪 Guid。</param>
+        /// <returns>移除成功返回 <c>true</c>,否则返回 <c>false</c>。</returns>
+        public bool RemoveScanner(Guid id)
+        {
+            bool result = false;
+            lock (_sync)
+            {
+                var e = Scanners.FirstOrDefault(r => r.Id == id);
+                if (e != null)
+                    result = Scanners.Remove(e);
+                //重新编号
+                int no = 1;
+                //对所有扫码枪按ScannerNo排序
+                var sortedScanners = Scanners.OrderBy(r => r.ScannerNo).ToList();
+                foreach (var r in sortedScanners)
+                {
+                    r.ScannerNo = no;
+                    no++;
+                }
+                Scanners.Clear();
+                foreach (var r in sortedScanners)
+                {
+                    Scanners.Add(r);
+                }
+            }
+            FileHelper.WriteJsonFile(Scanners, ConfigPaths.ScannersConfigurationPath);
+            return result;
+        }
+
+        /// <summary>
+        /// 判断是否包含指定 Id 的扫码枪配置。
+        /// </summary>
+        /// <param name="id">扫码枪的 Guid。</param>
+        /// <returns>存在返回 <c>true</c>,否则返回 <c>false</c>。</returns>
+        public bool ContainsScanner(Guid id) { lock (_sync) { return Scanners.Any(r => r.Id == id); } }
+
+        
+
         #endregion
         #endregion
 
 
         #region Feeders
         #region Feeders

+ 41 - 0
TeamAAS-VM/Services/ProductService.cs

@@ -931,6 +931,28 @@ namespace TeamAAS_VP.Services
 
 
         }
         }
 
 
+        /// <summary>
+        /// 在所有产品中增加扫码枪点位表条目并保存对应产品文件(当系统新增扫码枪或点位时调用)。
+        /// </summary>
+        /// <param name="scannerId">扫码枪 ID。</param>
+        /// <param name="scannerPointName">点位名称。</param>
+        public void AddScannerPointToProduct(Guid scannerId, string scannerPointName)
+        {
+            //获取所有产品
+            var products = GetAllProducts();
+            if (products == null) return;
+            //遍历所有产品,增加扫码枪点位表
+            foreach (var item in products)
+            {
+                //item.ScannerPoint.AddScanner(scannerId, scannerPointName);
+                //单个产品的配置文件路径
+                string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
+                //保存产品
+                FileHelper.WriteJsonFile(item, productFilePath);
+            }
+
+        }
+
         /// <summary>
         /// <summary>
         /// 异步为所有产品增加机器人点位。
         /// 异步为所有产品增加机器人点位。
         /// </summary>
         /// </summary>
@@ -961,6 +983,25 @@ namespace TeamAAS_VP.Services
             }
             }
         }
         }
 
 
+        /// <summary>
+        /// 在所有产品中移除指定扫码枪相关的点位配置并保存产品文件。
+        /// </summary>
+        /// <param name="scannerId">扫码枪 ID。</param>
+        public void RemoveScannerPointFromProduct(Guid scannerId)
+        {
+            var products = GetAllProducts();
+            if (products == null) return;
+            //遍历所有产品,删除扫码枪点位表
+            foreach (var item in products)
+            {
+                //item.ScannerPoint.RemoveScanner(scannerId);
+                //单个产品的配置文件路径
+                string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
+                //保存产品
+                FileHelper.WriteJsonFile(item, productFilePath);
+            }
+        }
+
         /// <summary>
         /// <summary>
         /// 异步在所有产品中移除机器人点位。
         /// 异步在所有产品中移除机器人点位。
         /// </summary>
         /// </summary>

+ 503 - 0
TeamAAS-VM/Services/ScannerService.cs

@@ -0,0 +1,503 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Core.PLCs;
+using TeamAAS_VP.Core.Robots;
+using TeamAAS_VP.Core.Scanners;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Models.Scanner;
+
+namespace TeamAAS_VP.Services
+{
+    public class ScannerService : IScannerService, IDisposable
+    {
+        private readonly IPlcService _plcService;
+        private readonly Dictionary<Guid, IScanner> _scannerCollection;
+        private readonly object _sync = new object();
+
+        public ScannerService(IPlcService plcService)
+        {
+            _scannerCollection = new Dictionary<Guid, IScanner>();
+            _plcService = plcService;
+        }
+
+        /// <summary>
+        /// 创建扫码枪
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="robotInfo"></param>
+        /// <returns></returns>
+        /// <exception cref="ArgumentNullException"></exception>
+        public bool CreateScanner(Guid id, ScannerInfo scannerInfo)
+        {
+            if (scannerInfo == null) throw new ArgumentNullException(nameof(scannerInfo));
+
+            var scanner = CreateScannerInstance(scannerInfo);
+            scanner.Id = id;
+
+            lock (_sync)
+            {
+                if (_scannerCollection.ContainsKey(id))
+                {
+                    var currentScanner = _scannerCollection[id];
+                    try
+                    {
+                        currentScanner.Dispose();
+                    }
+                    catch
+                    {
+                        // 忽略单个扫码枪 Dispose 异常,继续替换
+                    }
+                }
+
+                _scannerCollection[id] = scanner;
+            }
+
+            return true;
+        }
+
+        /// <summary>
+        /// 创建扫码枪
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="scannerInfo"></param>
+        /// <returns></returns>
+        public Task<bool> CreateScannerAsync(Guid id, ScannerInfo scannerInfo)
+        {
+            return Task.Run(() =>
+            {
+                return CreateScanner(id, scannerInfo);
+            });
+        }
+
+        public IScanner GetScanner(Guid id)
+        {
+            lock (_sync)
+            {
+                if (_scannerCollection.TryGetValue(id, out var scanner))
+                {
+                    return scanner;
+                }
+            }
+            return null;
+        }
+
+        public Task<IScanner> GetScannerAsync(Guid id)
+        {
+            return Task.Run(() =>
+            {
+                return GetScanner(id);
+            });
+        }
+
+        public void UnRegisterScanner(Guid id)
+        {
+            IScanner scanner = null;
+            lock (_sync)
+            {
+                if (_scannerCollection.TryGetValue(id, out scanner))
+                {
+                    _scannerCollection.Remove(id);
+                }
+            }
+            if (scanner != null)
+            {
+                try
+                {
+                    scanner.Dispose();
+                }
+                catch
+                {
+                    // 忽略释放异常
+                }
+            }
+        }
+
+        public Task UnRegisterScannerAsync(Guid id)
+        {
+
+            return Task.Run(() => UnRegisterScanner(id));
+        }
+
+        /// <summary>
+        /// 获取所有扫码枪
+        /// </summary>
+        /// <returns></returns>
+        public IReadOnlyCollection<IScanner> GetAllScanners()
+        {
+            lock (_sync)
+            {
+                return _scannerCollection.Values.ToList().AsReadOnly();
+            }
+        }
+
+        public Task<IReadOnlyCollection<IScanner>> GetAllScannersAsync()
+        {
+            return Task.Run(() =>
+            {
+                return GetAllScanners();
+            });
+        }
+
+        /// <summary>
+        /// 尝试获取扫码枪
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="scanner"></param>
+        /// <returns></returns>
+        public bool TryGetScanner(Guid id, out IScanner scanner)
+        {
+            lock (_sync)
+            {
+                return _scannerCollection.TryGetValue(id, out scanner);
+            }
+        }
+
+        public Task<(bool found, IScanner scanner)> TryGetScannerAsync(Guid id)
+        {
+
+            return Task.Run(() =>
+            {
+                IScanner scanner;
+                bool found;
+                lock (_sync)
+                {
+                    found = _scannerCollection.TryGetValue(id, out scanner);
+                }
+                return (found, scanner);
+            });
+        }
+
+        /// <summary>
+        /// 检查是否存在
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        public bool ContainsScanner(Guid id)
+        {
+            lock (_sync)
+            {
+                return _scannerCollection.ContainsKey(id);
+            }
+        }
+
+        public Task<bool> ContainsScannerAsync(Guid id)
+        {
+            return Task.Run(() =>
+            {
+                return ContainsScanner(id);
+            });
+        }
+
+        /// <summary>
+        /// 移除扫码枪并释放资源,返回是否成功移除
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        public bool RemoveScanner(Guid id)
+        {
+            IScanner scanner = null;
+            lock (_sync)
+            {
+                if (_scannerCollection.TryGetValue(id, out scanner))
+                {
+                    _scannerCollection.Remove(id);
+                }
+            }
+            if (scanner != null)
+            {
+                try
+                {
+                    scanner.Dispose();
+                }
+                catch
+                {
+                    // 忽略释放异常
+                }
+                return true;
+            }
+            return false;
+        }
+
+        public Task<bool> RemoveScannerAsync(Guid id)
+        {
+            return Task.Run(() =>
+            {
+                return RemoveScanner(id);
+            });
+        }
+
+        public IScanner GetScannerByNumber(int scannerNo)
+        {
+            if (TryFindScannerByNumber(scannerNo, out _, out var scanner))
+            {
+                return scanner;
+            }
+            return null;
+        }
+
+        public Task<IScanner> GetScannerByNumberAsync(int scannerNo)
+        {
+            return Task.Run(() =>
+            {
+                return GetScannerByNumber(scannerNo);
+            });
+        }
+
+        public Task UnRegisterScannerByNumberAsync(int scannerNo)
+        {
+            return Task.Run(() => UnRegisterScannerByNumber(scannerNo));
+        }
+
+        public void UnRegisterScannerByNumber(int scannerNo)
+        {
+            if (TryFindScannerByNumber(scannerNo, out var id, out var scanner))
+            {
+                // 复用已有的方法以保持行为一致(线程安全、异常处理)
+                UnRegisterScanner(id);
+            }
+        }
+
+        /// <summary>
+        /// 移除所有扫码枪
+        /// </summary>
+        public void RemoveAllScanners()
+        {
+            //依次移除每个扫码枪,确保资源释放
+            List<Guid> scannerIds;
+            lock (_sync)
+            {
+                scannerIds = _scannerCollection.Keys.ToList();
+            }
+            foreach (var id in scannerIds)
+            {
+                RemoveScanner(id);
+            }
+        }
+
+        /// <summary>
+        /// 初始化所有扫码枪
+        /// </summary>
+        /// <param name="scanners"></param>
+        /// <returns></returns>
+        public (bool IsSucceed, string Message) InitializeAllScanners(ScannerInfo[] scanners)
+        {
+            //清除现有扫码枪集合
+            RemoveAllScanners();
+
+            //根据传入的扫码枪信息数组,依次创建并注册扫码枪实例
+            foreach (var scannerInfo in scanners)
+            {
+                var scanner = CreateScannerInstance(scannerInfo);
+                lock (_sync)
+                {
+                    _scannerCollection[scanner.Id] = scanner;
+                }
+            }
+
+            bool allConnected = true;
+            StringBuilder errorMessages = new StringBuilder();
+            //获取所有扫码枪并连接
+            var allScanners = GetAllScanners();
+            foreach (var scanner in allScanners)
+            {
+                try
+                {
+                    scanner.Connect();
+                }
+                catch
+                {
+                    //忽略单个扫码枪连接异常,继续连接其他扫码枪
+                }
+                if (!scanner.IsConnected)
+                {
+                    allConnected = false;
+                    errorMessages.AppendLine($"扫码枪[{scanner.Name}]连接失败。");
+                }
+            }
+            if (allConnected)
+            {
+                return (true, "所有扫码枪初始化并连接成功。");
+            }
+            else
+            {
+                return (false, errorMessages.ToString());
+            }
+        }
+
+        /// <summary>
+        /// 初始化所有扫码枪 (异步)
+        /// </summary>
+        /// <param name="scanners"></param>
+        /// <returns></returns>
+        public Task<(bool IsSucceed, string Message)> InitializeAllScannersAsync(ScannerInfo[] scanners)
+        {
+
+            return Task.Run(() =>
+            {
+                return InitializeAllScanners(scanners);
+            });
+
+        }
+
+        // 私有工厂方法,避免重复代码
+        private IScanner CreateScannerInstance(ScannerInfo scannerInfo)
+        {
+            if (scannerInfo == null) throw new ArgumentNullException(nameof(scannerInfo));
+
+            IScanner scanner;
+            if (scannerInfo.ScannerBrand == Enums.ScannerBrand.NLS)
+            {
+                scanner = new NlsScanner(scannerInfo);
+            }
+            
+            else
+            {
+                scanner = new NlsScanner(scannerInfo);
+            }
+
+            return scanner;
+        }
+
+        /// <summary>
+        /// 更新扫码枪编号
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="newNumber"></param>
+        public void UpdateScannerNumber(Guid id, int newNumber)
+        {
+            IScanner scanner;
+            lock (_sync)
+            {
+                if (_scannerCollection.TryGetValue(id, out scanner))
+                {
+                    scanner.ScannerNo = newNumber;
+                }
+            }
+        }
+
+        // 私有帮助方法:通过扫码枪编号查找字典中的条目(线程安全)
+        private bool TryFindScannerByNumber(int scannerNo, out Guid id, out IScanner scanner)
+        {
+            lock (_sync)
+            {
+                foreach (var kvp in _scannerCollection)
+                {
+                    var r = kvp.Value;
+                    if (r == null) continue;
+
+                    object rawValue = null;
+                    var type = r.GetType();
+
+                    // 1. 直接在扫码枪对象上查找常见编号属性
+                    var prop = type.GetProperty("ScannerNo") ??
+                               type.GetProperty("ScannerNumber") ??
+                               type.GetProperty("Number") ??
+                               type.GetProperty("No");
+                    if (prop != null)
+                    {
+                        try
+                        {
+                            rawValue = prop.GetValue(r);
+                        }
+                        catch
+                        {
+                            rawValue = null;
+                        }
+                    }
+
+                    // 2. 如果未找到,尝试从 RobotInfo / Info 属性中获取编号
+                    if (rawValue == null)
+                    {
+                        var infoProp = type.GetProperty("ScannerInfo") ?? type.GetProperty("Info");
+                        if (infoProp != null)
+                        {
+                            try
+                            {
+                                var infoObj = infoProp.GetValue(r);
+                                if (infoObj != null)
+                                {
+                                    var infoType = infoObj.GetType();
+                                    var numberProp = infoType.GetProperty("ScannerNo") ??
+                                                     infoType.GetProperty("ScannerNumber") ??
+                                                     infoType.GetProperty("Number") ??
+                                                     infoType.GetProperty("No");
+                                    if (numberProp != null)
+                                    {
+                                        try
+                                        {
+                                            rawValue = numberProp.GetValue(infoObj);
+                                        }
+                                        catch
+                                        {
+                                            rawValue = null;
+                                        }
+                                    }
+                                }
+                            }
+                            catch
+                            {
+                                // 忽略反射读取错误
+                                rawValue = null;
+                            }
+                        }
+                    }
+
+                    if (rawValue != null)
+                    {
+                        int parsed;
+                        try
+                        {
+                            if (rawValue is int) parsed = (int)rawValue;
+                            else parsed = Convert.ToInt32(rawValue);
+                        }
+                        catch
+                        {
+                            // 不能转换则跳过
+                            continue;
+                        }
+
+                        if (parsed == scannerNo)
+                        {
+                            id = kvp.Key;
+                            scanner = r;
+                            return true;
+                        }
+                    }
+                }
+            }
+
+            id = Guid.Empty;
+            scanner = null;
+            return false;
+        }
+
+        // 实现 IDisposable,释放所有扫码枪并清空集合
+        public void Dispose()
+        {
+            List<IScanner> scanners;
+            lock (_sync)
+            {
+                scanners = _scannerCollection.Values.ToList();
+                _scannerCollection.Clear();
+            }
+
+            foreach (var r in scanners)
+            {
+                try
+                {
+                    r.Dispose();
+                }
+                catch
+                {
+                    // 忽略单个释放异常
+                }
+            }
+
+            GC.SuppressFinalize(this);
+        }
+    }
+}

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

@@ -555,9 +555,13 @@
     <Compile Include="Core\Lights\LightModel.cs" />
     <Compile Include="Core\Lights\LightModel.cs" />
     <Compile Include="Core\Lights\SerialPortProtocol.cs" />
     <Compile Include="Core\Lights\SerialPortProtocol.cs" />
     <Compile Include="Core\Lights\TcpProtocol.cs" />
     <Compile Include="Core\Lights\TcpProtocol.cs" />
+    <Compile Include="Core\Scanners\NlsScanner.cs" />
     <Compile Include="Core\StabilityAnalyzer.cs" />
     <Compile Include="Core\StabilityAnalyzer.cs" />
+    <Compile Include="Enums\ScannerBrand.cs" />
     <Compile Include="Events\MainTabSwitchNotification.cs" />
     <Compile Include="Events\MainTabSwitchNotification.cs" />
     <Compile Include="Interfaces\IMesService.cs" />
     <Compile Include="Interfaces\IMesService.cs" />
+    <Compile Include="Interfaces\IScanner.cs" />
+    <Compile Include="Interfaces\IScannerService.cs" />
     <Compile Include="Models\CTQ_Data.cs" />
     <Compile Include="Models\CTQ_Data.cs" />
     <Compile Include="Models\DataFormCtq.cs" />
     <Compile Include="Models\DataFormCtq.cs" />
     <Compile Include="Models\DeviceInfo.cs" />
     <Compile Include="Models\DeviceInfo.cs" />
@@ -571,6 +575,8 @@
     <Compile Include="Models\PLC\PlcPointAddress.cs" />
     <Compile Include="Models\PLC\PlcPointAddress.cs" />
     <Compile Include="Models\PLC\PlcRobotParameter.cs" />
     <Compile Include="Models\PLC\PlcRobotParameter.cs" />
     <Compile Include="Models\ProductionRecord.cs" />
     <Compile Include="Models\ProductionRecord.cs" />
+    <Compile Include="Models\Scanner\ScannerInfo.cs" />
+    <Compile Include="Models\ScanRs232ConfigModel.cs" />
     <Compile Include="Models\ScrewFeederBatchRecord.cs" />
     <Compile Include="Models\ScrewFeederBatchRecord.cs" />
     <Compile Include="Resources\Languages\Lang.Designer.cs">
     <Compile Include="Resources\Languages\Lang.Designer.cs">
       <AutoGen>True</AutoGen>
       <AutoGen>True</AutoGen>
@@ -578,10 +584,13 @@
       <DependentUpon>Lang.resx</DependentUpon>
       <DependentUpon>Lang.resx</DependentUpon>
     </Compile>
     </Compile>
     <Compile Include="Services\MesService.cs" />
     <Compile Include="Services\MesService.cs" />
+    <Compile Include="Services\ScannerService.cs" />
     <Compile Include="ValueConverter\ImageFileNameFormatConverter.cs" />
     <Compile Include="ValueConverter\ImageFileNameFormatConverter.cs" />
+    <Compile Include="ViewModels\ImageViewModel.cs" />
     <Compile Include="ViewModels\Product\PlcPointParamsViewModel.cs" />
     <Compile Include="ViewModels\Product\PlcPointParamsViewModel.cs" />
     <Compile Include="ViewModels\Product\VisionDynamicAccuracyAnalyzerViewModel.cs" />
     <Compile Include="ViewModels\Product\VisionDynamicAccuracyAnalyzerViewModel.cs" />
     <Compile Include="ViewModels\Setting\AddLightControllerViewModel.cs" />
     <Compile Include="ViewModels\Setting\AddLightControllerViewModel.cs" />
+    <Compile Include="ViewModels\Setting\AddScannerViewModel.cs" />
     <Compile Include="ViewModels\Statistics\LockResultRecoredQueryViewModel.cs" />
     <Compile Include="ViewModels\Statistics\LockResultRecoredQueryViewModel.cs" />
     <Compile Include="ViewModels\User\CardLoginWindowViewModel.cs" />
     <Compile Include="ViewModels\User\CardLoginWindowViewModel.cs" />
     <Compile Include="ViewModels\User\LoginViewModel.cs" />
     <Compile Include="ViewModels\User\LoginViewModel.cs" />
@@ -949,9 +958,15 @@
     <Compile Include="Views\DebugView.xaml.cs">
     <Compile Include="Views\DebugView.xaml.cs">
       <DependentUpon>DebugView.xaml</DependentUpon>
       <DependentUpon>DebugView.xaml</DependentUpon>
     </Compile>
     </Compile>
+    <Compile Include="Views\Dialogs\TextInputDialog.xaml.cs">
+      <DependentUpon>TextInputDialog.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Views\Home\ShowVisionRender.xaml.cs">
     <Compile Include="Views\Home\ShowVisionRender.xaml.cs">
       <DependentUpon>ShowVisionRender.xaml</DependentUpon>
       <DependentUpon>ShowVisionRender.xaml</DependentUpon>
     </Compile>
     </Compile>
+    <Compile Include="Views\ImageView.xaml.cs">
+      <DependentUpon>ImageView.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Views\ProductsView.xaml.cs">
     <Compile Include="Views\ProductsView.xaml.cs">
       <DependentUpon>ProductsView.xaml</DependentUpon>
       <DependentUpon>ProductsView.xaml</DependentUpon>
     </Compile>
     </Compile>
@@ -1045,6 +1060,9 @@
     <Compile Include="Views\Setting\AddRobot.xaml.cs">
     <Compile Include="Views\Setting\AddRobot.xaml.cs">
       <DependentUpon>AddRobot.xaml</DependentUpon>
       <DependentUpon>AddRobot.xaml</DependentUpon>
     </Compile>
     </Compile>
+    <Compile Include="Views\Setting\AddScanner.xaml.cs">
+      <DependentUpon>AddScanner.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Views\Setting\EditCamera.xaml.cs">
     <Compile Include="Views\Setting\EditCamera.xaml.cs">
       <DependentUpon>EditCamera.xaml</DependentUpon>
       <DependentUpon>EditCamera.xaml</DependentUpon>
     </Compile>
     </Compile>
@@ -1255,6 +1273,10 @@
       <SubType>Designer</SubType>
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
       <Generator>MSBuild:Compile</Generator>
     </Page>
     </Page>
+    <Page Include="Views\Dialogs\TextInputDialog.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
     <Page Include="Views\HomeView.xaml">
     <Page Include="Views\HomeView.xaml">
       <SubType>Designer</SubType>
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
       <Generator>MSBuild:Compile</Generator>
@@ -1263,6 +1285,10 @@
       <SubType>Designer</SubType>
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
       <Generator>MSBuild:Compile</Generator>
     </Page>
     </Page>
+    <Page Include="Views\ImageView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
     <Page Include="Views\MainWindowView.xaml">
     <Page Include="Views\MainWindowView.xaml">
       <Generator>MSBuild:Compile</Generator>
       <Generator>MSBuild:Compile</Generator>
       <SubType>Designer</SubType>
       <SubType>Designer</SubType>
@@ -1407,6 +1433,10 @@
       <SubType>Designer</SubType>
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
       <Generator>MSBuild:Compile</Generator>
     </Page>
     </Page>
+    <Page Include="Views\Setting\AddScanner.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
     <Page Include="Views\Setting\EditCamera.xaml">
     <Page Include="Views\Setting\EditCamera.xaml">
       <SubType>Designer</SubType>
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
       <Generator>MSBuild:Compile</Generator>
@@ -1624,7 +1654,9 @@
       <Install>false</Install>
       <Install>false</Install>
     </BootstrapperPackage>
     </BootstrapperPackage>
   </ItemGroup>
   </ItemGroup>
-  <ItemGroup />
+  <ItemGroup>
+    <Folder Include="ViewModels\Dialogs\" />
+  </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
   <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
     <PropertyGroup>
     <PropertyGroup>

+ 593 - 0
TeamAAS-VM/ViewModels/ImageViewModel.cs

@@ -0,0 +1,593 @@
+using Microsoft.Win32;
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using TeamAAS_VP.Views.Dialogs;
+
+namespace TeamAAS_VP.ViewModels
+{
+    public class ImageViewModel : BindableBase
+    {
+        private const string AppFolderName = "TeamAAS-VM";
+        private const string ImageFileName = "LastImage.png";
+        private const string XmlFileName = "LastAnno.xml";
+
+        private string _folder;
+        private string _imagePath;
+        private string _xmlPath;
+
+        private FrameworkElement _renderTarget;
+        private Canvas _canvas;
+
+        private Grid _lastArrowGroup;
+
+        public ImageViewModel()
+        {
+            InitPaths();
+
+            ImportImageCommand = new DelegateCommand(ImportImage);
+            SaveCommand = new DelegateCommand(Save);
+            ClearCommand = new DelegateCommand(Clear);
+
+            Tool = "Rect";
+            ColorName = "Red";
+            Thickness = 2;
+        }
+
+        #region Commands
+
+        public DelegateCommand ImportImageCommand { get; }
+        public DelegateCommand SaveCommand { get; }
+        public DelegateCommand ClearCommand { get; }
+
+        #endregion
+
+        #region Bindable Properties
+
+        private ImageSource _ImageSource;
+        public ImageSource ImageSource
+        {
+            get { return _ImageSource; }
+            set { SetProperty(ref _ImageSource, value); }
+        }
+
+        private int _PixelWidth;
+        public int PixelWidth
+        {
+            get { return _PixelWidth; }
+            set { SetProperty(ref _PixelWidth, value); }
+        }
+
+        private int _PixelHeight;
+        public int PixelHeight
+        {
+            get { return _PixelHeight; }
+            set { SetProperty(ref _PixelHeight, value); }
+        }
+
+        /// <summary>
+        /// Rect / Arrow / Text / Select
+        /// </summary>
+        private string _Tool;
+        public string Tool
+        {
+            get { return _Tool; }
+            set { SetProperty(ref _Tool, value); }
+        }
+
+        private string _ColorName;
+        public string ColorName
+        {
+            get { return _ColorName; }
+            set { SetProperty(ref _ColorName, value); }
+        }
+
+        private double _Thickness;
+        public double Thickness
+        {
+            get { return _Thickness; }
+            set { SetProperty(ref _Thickness, value); }
+        }
+
+        #endregion
+
+        #region Public API (called from ImageView.xaml.cs)
+
+        public void AttachRenderTarget(FrameworkElement renderTarget, Canvas canvas)
+        {
+            _renderTarget = renderTarget;
+            _canvas = canvas;
+        }
+
+        public void LoadLast()
+        {
+            try
+            {
+                if (File.Exists(_imagePath))
+                {
+                    var bmp = LoadBitmap(_imagePath);
+                    ImageSource = bmp;
+                    PixelWidth = bmp.PixelWidth;
+                    PixelHeight = bmp.PixelHeight;
+                }
+
+                if (_canvas != null && File.Exists(_xmlPath))
+                {
+                    var list = ReadXml<List<AnnoItem>>(_xmlPath);
+                    if (list != null)
+                    {
+                        _canvas.Children.Clear();
+                        foreach (var item in list)
+                        {
+                            RestoreItem(item);
+                        }
+                    }
+                }
+            }
+            catch
+            {
+            }
+        }
+
+        public Rectangle CreateRect()
+        {
+            return new Rectangle
+            {
+                Stroke = GetStrokeBrush(),
+                StrokeThickness = Thickness,
+                Fill = Brushes.Transparent
+            };
+        }
+
+        public void CreateTextAt(Canvas canvas, Point pixelPoint)
+        {
+            var dlg = new TextInputDialog();
+            dlg.Owner = Application.Current?.MainWindow;
+            if (dlg.ShowDialog() != true) return;
+
+            var input = dlg.InputText;
+            if (string.IsNullOrWhiteSpace(input)) return;
+
+            var tb = new TextBlock
+            {
+                Text = input,
+                Foreground = GetStrokeBrush(),
+                FontSize = 20,
+                Background = Brushes.Transparent
+            };
+
+            Canvas.SetLeft(tb, pixelPoint.X);
+            Canvas.SetTop(tb, pixelPoint.Y);
+            canvas.Children.Add(tb);
+        }
+
+        public Grid CreateArrowGroup(Point start, Point end)
+        {
+            var brush = GetStrokeBrush();
+
+            var line = new Line
+            {
+                X1 = start.X,
+                Y1 = start.Y,
+                X2 = end.X,
+                Y2 = end.Y,
+                Stroke = brush,
+                StrokeThickness = Thickness
+            };
+
+            var head = new Polygon
+            {
+                Fill = brush,
+                Stroke = brush,
+                StrokeThickness = 1
+            };
+
+            var group = new Grid();
+            group.Children.Add(line);
+            group.Children.Add(head);
+            group.Tag = line;
+
+            _lastArrowGroup = group;
+            UpdateArrowHead(line, head);
+
+            return group;
+        }
+
+        public void UpdateLastArrow(Canvas canvas, Point current)
+        {
+            if (_lastArrowGroup == null) return;
+
+            var line = _lastArrowGroup.Children.OfType<Line>().FirstOrDefault();
+            var head = _lastArrowGroup.Children.OfType<Polygon>().FirstOrDefault();
+            if (line == null || head == null) return;
+
+            line.X2 = current.X;
+            line.Y2 = current.Y;
+
+            UpdateArrowHead(line, head);
+        }
+
+        public void CommitLastArrow(Canvas canvas, Point end)
+        {
+            UpdateLastArrow(canvas, end);
+        }
+
+        #endregion
+
+        #region Command handlers
+
+        private void ImportImage()
+        {
+            var dlg = new OpenFileDialog();
+            dlg.Title = "导入图片";
+            dlg.Filter = "Image Files|*.png;*.jpg;*.jpeg;*.bmp|All Files|*.*";
+            if (dlg.ShowDialog() != true) return;
+
+            var bmp = LoadBitmap(dlg.FileName);
+            ImageSource = bmp;
+
+            PixelWidth = bmp.PixelWidth;
+            PixelHeight = bmp.PixelHeight;
+
+            _canvas?.Children.Clear();
+            _lastArrowGroup = null;
+        }
+
+        private void Clear()
+        {
+            _canvas?.Children.Clear();
+            _lastArrowGroup = null;
+        }
+
+        private void Save()
+        {
+            if (ImageSource == null)
+            {
+                MessageBox.Show("请先导入图片", "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
+                return;
+            }
+
+            if (_renderTarget == null || _canvas == null)
+            {
+                MessageBox.Show("保存失败:界面尚未初始化完成", "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
+                return;
+            }
+
+            if (PixelWidth <= 0 || PixelHeight <= 0)
+            {
+                MessageBox.Show("图片像素尺寸无效", "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
+                return;
+            }
+
+            try
+            {
+                var merged = RenderPixelElement(_renderTarget, PixelWidth, PixelHeight);
+                SavePng(merged, _imagePath);
+
+                var items = DumpAnnoItems();
+                WriteXml(_xmlPath, items);
+
+                MessageBox.Show("保存成功", "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message, "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
+            }
+        }
+
+        #endregion
+
+        #region Persistence (PNG + XML)
+
+        private void InitPaths()
+        {
+            _folder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), AppFolderName);
+            Directory.CreateDirectory(_folder);
+
+            _imagePath = System.IO.Path.Combine(_folder, ImageFileName);
+            _xmlPath = System.IO.Path.Combine(_folder, XmlFileName);
+        }
+
+        private BitmapImage LoadBitmap(string path)
+        {
+            var bmp = new BitmapImage();
+            bmp.BeginInit();
+            bmp.CacheOption = BitmapCacheOption.OnLoad;
+            bmp.UriSource = new Uri(path, UriKind.Absolute);
+            bmp.EndInit();
+            bmp.Freeze();
+            return bmp;
+        }
+
+        private BitmapSource RenderPixelElement(FrameworkElement element, int pixelWidth, int pixelHeight)
+        {
+            element.Measure(new Size(pixelWidth, pixelHeight));
+            element.Arrange(new Rect(0, 0, pixelWidth, pixelHeight));
+            element.UpdateLayout();
+
+            var rtb = new RenderTargetBitmap(pixelWidth, pixelHeight, 96, 96, PixelFormats.Pbgra32);
+            rtb.Render(element);
+            rtb.Freeze();
+            return rtb;
+        }
+
+        private void SavePng(BitmapSource source, string path)
+        {
+            var encoder = new PngBitmapEncoder();
+            encoder.Frames.Add(BitmapFrame.Create(source));
+            using (var fs = File.Create(path))
+            {
+                encoder.Save(fs);
+            }
+        }
+
+        private void WriteXml<T>(string path, T data)
+        {
+            var ser = new XmlSerializer(typeof(T));
+            using (var fs = File.Create(path))
+            {
+                ser.Serialize(fs, data);
+            }
+        }
+
+        private T ReadXml<T>(string path) where T : class
+        {
+            var ser = new XmlSerializer(typeof(T));
+            using (var fs = File.OpenRead(path))
+            {
+                return ser.Deserialize(fs) as T;
+            }
+        }
+
+        #endregion
+
+        #region Dump/Restore items
+
+        private List<AnnoItem> DumpAnnoItems()
+        {
+            var list = new List<AnnoItem>();
+            if (_canvas == null) return list;
+
+            foreach (var child in _canvas.Children)
+            {
+                if (child is Rectangle r)
+                {
+                    list.Add(new AnnoItem
+                    {
+                        Type = "Rect",
+                        X = SafeGetLeft(r),
+                        Y = SafeGetTop(r),
+                        W = r.Width,
+                        H = r.Height,
+                        Color = BrushToColorString(r.Stroke),
+                        Thickness = r.StrokeThickness
+                    });
+                }
+                else if (child is TextBlock t)
+                {
+                    list.Add(new AnnoItem
+                    {
+                        Type = "Text",
+                        X = SafeGetLeft(t),
+                        Y = SafeGetTop(t),
+                        Text = t.Text,
+                        Color = BrushToColorString(t.Foreground),
+                        FontSize = t.FontSize
+                    });
+                }
+                else if (child is Grid g)
+                {
+                    var line = g.Children.OfType<Line>().FirstOrDefault();
+                    if (line != null)
+                    {
+                        list.Add(new AnnoItem
+                        {
+                            Type = "Arrow",
+                            X1 = line.X1,
+                            Y1 = line.Y1,
+                            X2 = line.X2,
+                            Y2 = line.Y2,
+                            Color = BrushToColorString(line.Stroke),
+                            Thickness = line.StrokeThickness
+                        });
+                    }
+                }
+            }
+
+            return list;
+        }
+
+        private void RestoreItem(AnnoItem item)
+        {
+            if (_canvas == null || item == null) return;
+
+            if (item.Type == "Rect")
+            {
+                var rect = new Rectangle
+                {
+                    Stroke = BrushFrom(item.Color),
+                    StrokeThickness = item.Thickness <= 0 ? 2 : item.Thickness,
+                    Fill = Brushes.Transparent,
+                    Width = item.W,
+                    Height = item.H
+                };
+                Canvas.SetLeft(rect, item.X);
+                Canvas.SetTop(rect, item.Y);
+                _canvas.Children.Add(rect);
+                return;
+            }
+
+            if (item.Type == "Text")
+            {
+                var tb = new TextBlock
+                {
+                    Text = item.Text ?? string.Empty,
+                    Foreground = BrushFrom(item.Color),
+                    FontSize = item.FontSize <= 0 ? 20 : item.FontSize,
+                    Background = Brushes.Transparent
+                };
+                Canvas.SetLeft(tb, item.X);
+                Canvas.SetTop(tb, item.Y);
+                _canvas.Children.Add(tb);
+                return;
+            }
+
+            if (item.Type == "Arrow")
+            {
+                var brush = BrushFrom(item.Color);
+
+                var line = new Line
+                {
+                    X1 = item.X1,
+                    Y1 = item.Y1,
+                    X2 = item.X2,
+                    Y2 = item.Y2,
+                    Stroke = brush,
+                    StrokeThickness = item.Thickness <= 0 ? 2 : item.Thickness
+                };
+
+                var head = new Polygon
+                {
+                    Fill = brush,
+                    Stroke = brush,
+                    StrokeThickness = 1
+                };
+
+                var group = new Grid();
+                group.Children.Add(line);
+                group.Children.Add(head);
+                group.Tag = line;
+
+                UpdateArrowHead(line, head);
+
+                _canvas.Children.Add(group);
+            }
+        }
+
+        #endregion
+
+        #region Helpers
+
+        private Brush GetStrokeBrush()
+        {
+            try
+            {
+                var obj = ColorConverter.ConvertFromString(ColorName);
+                if (obj != null)
+                {
+                    return new SolidColorBrush((Color)obj);
+                }
+            }
+            catch { }
+            return Brushes.Red;
+        }
+
+        private Brush BrushFrom(string color)
+        {
+            try
+            {
+                if (!string.IsNullOrWhiteSpace(color))
+                {
+                    var c = (Color)ColorConverter.ConvertFromString(color);
+                    return new SolidColorBrush(c);
+                }
+            }
+            catch { }
+            return Brushes.Red;
+        }
+
+        private string BrushToColorString(Brush brush)
+        {
+            if (brush is SolidColorBrush s)
+            {
+                return s.Color.ToString();
+            }
+            return Colors.Red.ToString();
+        }
+
+        private double SafeGetLeft(UIElement e)
+        {
+            var v = Canvas.GetLeft(e);
+            return double.IsNaN(v) ? 0 : v;
+        }
+
+        private double SafeGetTop(UIElement e)
+        {
+            var v = Canvas.GetTop(e);
+            return double.IsNaN(v) ? 0 : v;
+        }
+
+        private void UpdateArrowHead(Line line, Polygon head)
+        {
+            var dx = line.X2 - line.X1;
+            var dy = line.Y2 - line.Y1;
+            var len = Math.Sqrt(dx * dx + dy * dy);
+            if (len < 1) len = 1;
+
+            var ux = dx / len;
+            var uy = dy / len;
+
+            const double size = 12.0;
+            var px = -uy;
+            var py = ux;
+
+            var tip = new Point(line.X2, line.Y2);
+            var p1 = new Point(line.X2 - ux * size + px * (size / 2), line.Y2 - uy * size + py * (size / 2));
+            var p2 = new Point(line.X2 - ux * size - px * (size / 2), line.Y2 - uy * size - py * (size / 2));
+
+            head.Points.Clear();
+            head.Points.Add(tip);
+            head.Points.Add(p1);
+            head.Points.Add(p2);
+        }
+
+        #endregion
+
+        [Serializable]
+        public class AnnoItem
+        {
+            public string Type { get; set; }
+
+            public double X { get; set; }
+            public double Y { get; set; }
+            public double W { get; set; }
+            public double H { get; set; }
+            public string Text { get; set; }
+            public double FontSize { get; set; }
+
+            public double X1 { get; set; }
+            public double Y1 { get; set; }
+            public double X2 { get; set; }
+            public double Y2 { get; set; }
+
+            public string Color { get; set; }
+            public double Thickness { get; set; }
+        }
+
+        public void RemoveAnnotation(UIElement element)
+        {
+            if (element == null) return;
+            if (_canvas == null) return;
+
+            if (_canvas.Children.Contains(element))
+            {
+                _canvas.Children.Remove(element);
+            }
+
+            // 如果删的是最后一根箭头,清理引用避免后续更新异常
+            if (ReferenceEquals(_lastArrowGroup, element))
+            {
+                _lastArrowGroup = null;
+            }
+        }
+    }
+}

+ 18 - 3
TeamAAS-VM/ViewModels/MainWindowViewModel.cs

@@ -197,19 +197,24 @@ namespace TeamAAS_VP.ViewModels
                     NavigationIndex = 3;
                     NavigationIndex = 3;
                     _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
                     _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
                     break;
                     break;
+                case "Image":
+                    _regionManager.RequestNavigate("MainRegionContext", "ImageView");
+                    NavigationIndex = 5;
+                    _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
+                    break;
                 case "Calib":
                 case "Calib":
                     _regionManager.RequestNavigate("MainRegionContext", "CalibrationView");
                     _regionManager.RequestNavigate("MainRegionContext", "CalibrationView");
-                    NavigationIndex = 5;
+                    NavigationIndex = 6;
                     _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
                     _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
                     break;
                     break;
                 case "Statistics":
                 case "Statistics":
                     _regionManager.RequestNavigate("MainRegionContext", "StatisticsView");
                     _regionManager.RequestNavigate("MainRegionContext", "StatisticsView");
-                    NavigationIndex = 6;
+                    NavigationIndex = 7;
                     _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
                     _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
                     break;
                     break;
                 case "User":
                 case "User":
                     _regionManager.RequestNavigate("MainRegionContext", "UserView");
                     _regionManager.RequestNavigate("MainRegionContext", "UserView");
-                    NavigationIndex = 7;
+                    NavigationIndex = 8;
                     _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
                     _eventAggregator.GetEvent<MainTabSwitchNotification>().Publish(NavigationIndex);
                     break;
                     break;
                 default:
                 default:
@@ -322,6 +327,14 @@ namespace TeamAAS_VP.ViewModels
             }));
             }));
             await management.InitRobots();
             await management.InitRobots();
 
 
+            //-------------------SETP 4.1: 初始化Scanner-----------------------------------------------------------------------
+            curvalue += 1;
+            _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
+            {
+                _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在初始化机器人}...", Value = curvalue });
+            }));
+            await management.InitScanners();
+
             //-------------------SETP 5: 初始化Camera-----------------------------------------------------------------------
             //-------------------SETP 5: 初始化Camera-----------------------------------------------------------------------
             curvalue += 1;
             curvalue += 1;
             _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
             _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
@@ -378,6 +391,8 @@ namespace TeamAAS_VP.ViewModels
             }));
             }));
             management.InitBackgroundcript();
             management.InitBackgroundcript();
 
 
+            await management.InitScan();
+
             //当前日期
             //当前日期
             CurrentTime = Guid.NewGuid();
             CurrentTime = Guid.NewGuid();
             Status.Add(new StatusInfo(CurrentTime, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), new SolidColorBrush(Colors.White)));
             Status.Add(new StatusInfo(CurrentTime, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), new SolidColorBrush(Colors.White)));

+ 92 - 0
TeamAAS-VM/ViewModels/Setting/AddScannerViewModel.cs

@@ -0,0 +1,92 @@
+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 System.Windows;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.Models.Scanner;
+
+namespace TeamAAS_VP.ViewModels.Setting
+{
+    public class AddScannerViewModel : BindableBase, IDialogAware
+    {
+        private readonly IConfigService _configService;
+        private ScannerInfo _Scanner;
+        /// <summary>
+        /// 扫码枪
+        /// </summary>
+        public ScannerInfo Scanner
+        {
+            get { return _Scanner   ; }
+            set
+            {
+                SetProperty(ref _Scanner, value);
+            }
+        }
+
+        private DelegateCommand _ConfirmCommand;
+        public DelegateCommand ConfirmCommand =>
+            _ConfirmCommand ?? (_ConfirmCommand = new DelegateCommand(ExecuteConfirmCommand));
+
+        void ExecuteConfirmCommand()
+        {
+            if (string.IsNullOrEmpty(Scanner.ScannerName))
+            {
+                return;
+            }
+            if (!FileHelper.CheckFileName(Scanner.ScannerName))
+            {
+                string lbuffer1 = System.Windows.Application.Current.Resources["CalibrationHomeViewModel.Info2"] as string;
+                MessageBox.Show($"{lbuffer1}");
+                return;
+            }
+
+            IDialogParameters parameters = new DialogParameters();
+            parameters.Add("Scanner", Scanner);
+            Tuple<bool, ScannerInfo> rest = new Tuple<bool, ScannerInfo>(false, Scanner);
+            RequestClose?.Invoke(new DialogResult(ButtonResult.OK, parameters));
+        }
+
+        private DelegateCommand _CancelCommand;
+        public DelegateCommand CancelCommand =>
+            _CancelCommand ?? (_CancelCommand = new DelegateCommand(ExecuteCancelCommand));
+
+        void ExecuteCancelCommand()
+        {
+            IDialogParameters parameters = new DialogParameters();
+            parameters.Add("Scanner", Scanner);
+            Tuple<bool, ScannerInfo> rest = new Tuple<bool, ScannerInfo>(false, Scanner);
+            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel, parameters));
+        }
+
+        public AddScannerViewModel()
+        {
+
+        }
+        public string Title { get; set; } = "添加扫码枪";
+
+        public event Action<IDialogResult> RequestClose;
+
+        public bool CanCloseDialog()
+        {
+            return true;
+        }
+
+        public void OnDialogClosed()
+        {
+
+        }
+
+        public void OnDialogOpened(IDialogParameters parameters)
+        {
+            Title = System.Windows.Application.Current.Resources["AddRobotViewModel.Info1"] as string;
+            Scanner = new ScannerInfo() { Id = Guid.NewGuid() };
+        }
+    }
+}

+ 140 - 3
TeamAAS-VM/ViewModels/SettingViewModel.cs

@@ -14,6 +14,7 @@ using System.Collections.ObjectModel;
 using System.ComponentModel;
 using System.ComponentModel;
 using System.Drawing.Drawing2D;
 using System.Drawing.Drawing2D;
 using System.Globalization;
 using System.Globalization;
+using System.IO;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
 using System.Windows;
 using System.Windows;
@@ -27,6 +28,7 @@ using TeamAAS_VP.Events;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Models.Lights;
 using TeamAAS_VP.Models.Lights;
+using TeamAAS_VP.Models.Scanner;
 using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.Services;
 using TeamAAS_VP.Services;
 using TeamAAS_VP.ViewModels.User;
 using TeamAAS_VP.ViewModels.User;
@@ -43,6 +45,7 @@ namespace TeamAAS_VP.ViewModels
         IDialogService _dialogService;
         IDialogService _dialogService;
         IConfigService _configService;
         IConfigService _configService;
         IRobotService _robotService;
         IRobotService _robotService;
+        IScannerService _scannerService;
         ICameraService _cameraService;
         ICameraService _cameraService;
         IFeederService _feeder_service;
         IFeederService _feeder_service;
         IFeederService _feederService;
         IFeederService _feederService;
@@ -54,6 +57,15 @@ namespace TeamAAS_VP.ViewModels
 
 
         #region 属性
         #region 属性
 
 
+
+        private ScanRs232ConfigModel _ScanConfig;
+
+        public ScanRs232ConfigModel ScanConfig
+        {
+            get { return _ScanConfig; }
+            set { SetProperty(ref _ScanConfig, value); }
+        }
+
         private bool _IsSaveScrewCurve;
         private bool _IsSaveScrewCurve;
         /// <summary>
         /// <summary>
         /// 是否保存锁付曲线图
         /// 是否保存锁付曲线图
@@ -79,6 +91,13 @@ namespace TeamAAS_VP.ViewModels
             set { SetProperty(ref _RobotList, value); }
             set { SetProperty(ref _RobotList, value); }
         }
         }
 
 
+        private ObservableCollection<ScannerInfo> _ScannerList;
+        public ObservableCollection<ScannerInfo> ScannerList
+        {
+            get { return _ScannerList; }
+            set { SetProperty(ref _ScannerList, value); }
+        }
+
         private ObservableCollection<CameraInfo> _CameraList;
         private ObservableCollection<CameraInfo> _CameraList;
         public ObservableCollection<CameraInfo> CameraList
         public ObservableCollection<CameraInfo> CameraList
         {
         {
@@ -141,6 +160,19 @@ namespace TeamAAS_VP.ViewModels
             }
             }
         }
         }
 
 
+        private ScannerInfo _SelectScanner;
+        /// <summary>
+        /// 选中的扫码枪
+        /// </summary>
+        public ScannerInfo SelectScanner
+        {
+            get { return _SelectScanner; }
+            set
+            {
+                SetProperty(ref _SelectScanner, value);
+            }
+        }
+
         private FeederInfo _SelectFeeder;
         private FeederInfo _SelectFeeder;
         /// <summary>
         /// <summary>
         /// 选中的Feeder
         /// 选中的Feeder
@@ -352,10 +384,18 @@ namespace TeamAAS_VP.ViewModels
         public DelegateCommand AddRobotCommand =>
         public DelegateCommand AddRobotCommand =>
             _AddRobotCommand ?? (_AddRobotCommand = new DelegateCommand(ExecuteAddRobotCommand));
             _AddRobotCommand ?? (_AddRobotCommand = new DelegateCommand(ExecuteAddRobotCommand));
 
 
+        private DelegateCommand _AddScannerCommand;
+        public DelegateCommand AddScannerCommand =>
+            _AddScannerCommand ?? (_AddScannerCommand = new DelegateCommand(ExecuteAddScannerCommand));
+
         private DelegateCommand _RemoveCommand;
         private DelegateCommand _RemoveCommand;
         public DelegateCommand RemoveCommand =>
         public DelegateCommand RemoveCommand =>
             _RemoveCommand ?? (_RemoveCommand = new DelegateCommand(ExecuteRemoveCommand));
             _RemoveCommand ?? (_RemoveCommand = new DelegateCommand(ExecuteRemoveCommand));
 
 
+        private DelegateCommand _RemoveScannerCommand;
+        public DelegateCommand RemoveScannerCommand =>
+            _RemoveScannerCommand ?? (_RemoveScannerCommand = new DelegateCommand(ExecuteRemoveScannerCommand));
+
         private DelegateCommand _AddFeederCommand;
         private DelegateCommand _AddFeederCommand;
         public DelegateCommand AddFeederCommand =>
         public DelegateCommand AddFeederCommand =>
             _AddFeederCommand ?? (_AddFeederCommand = new DelegateCommand(ExecuteAddFeederCommand));
             _AddFeederCommand ?? (_AddFeederCommand = new DelegateCommand(ExecuteAddFeederCommand));
@@ -372,6 +412,10 @@ namespace TeamAAS_VP.ViewModels
         public DelegateCommand SaveRobotsCommand =>
         public DelegateCommand SaveRobotsCommand =>
             _SaveRobotsCommand ?? (_SaveRobotsCommand = new DelegateCommand(ExecuteSaveRobotsCommand));
             _SaveRobotsCommand ?? (_SaveRobotsCommand = new DelegateCommand(ExecuteSaveRobotsCommand));
 
 
+        private DelegateCommand _SaveScannerCommand;
+        public DelegateCommand SaveScannerCommand =>
+            _SaveScannerCommand ?? (_SaveScannerCommand = new DelegateCommand(ExecuteSaveScannersCommand));
+
         private DelegateCommand _SaveFeedersCommand;
         private DelegateCommand _SaveFeedersCommand;
         public DelegateCommand SaveFeedersCommand =>
         public DelegateCommand SaveFeedersCommand =>
             _SaveFeedersCommand ?? (_SaveFeedersCommand = new DelegateCommand(ExecuteSaveFeedersCommand));
             _SaveFeedersCommand ?? (_SaveFeedersCommand = new DelegateCommand(ExecuteSaveFeedersCommand));
@@ -430,6 +474,8 @@ namespace TeamAAS_VP.ViewModels
         private DelegateCommand _SaveCardReaderConfigCommand;
         private DelegateCommand _SaveCardReaderConfigCommand;
         public DelegateCommand SaveCardReaderConfigCommand =>
         public DelegateCommand SaveCardReaderConfigCommand =>
             _SaveCardReaderConfigCommand ?? (_SaveCardReaderConfigCommand = new DelegateCommand(ExecuteSaveCardReaderConfigCommand));
             _SaveCardReaderConfigCommand ?? (_SaveCardReaderConfigCommand = new DelegateCommand(ExecuteSaveCardReaderConfigCommand));
+
+        
         #endregion
         #endregion
 
 
         #region 事件
         #region 事件
@@ -438,7 +484,7 @@ namespace TeamAAS_VP.ViewModels
 
 
         public SettingViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IDialogService dialogService,
         public SettingViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IDialogService dialogService,
             IConfigService configService, IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService,
             IConfigService configService, IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService,
-            IProductService productService, ISystemDatabaseService systemDatabaseService)
+            IProductService productService, ISystemDatabaseService systemDatabaseService,IScannerService scannerService)
         {
         {
             _regionManager = regionManager;
             _regionManager = regionManager;
             _eventAggregator = ea;
             _eventAggregator = ea;
@@ -450,6 +496,7 @@ namespace TeamAAS_VP.ViewModels
             _feederService = feederService;
             _feederService = feederService;
             _plcService = plcService;
             _plcService = plcService;
             _productService = productService;
             _productService = productService;
+            _scannerService = scannerService;
             _systemDatabaseService = systemDatabaseService;
             _systemDatabaseService = systemDatabaseService;
             management = _container.Resolve<Management>();
             management = _container.Resolve<Management>();
             LoadedCommand = new DelegateCommand(OnLoad);
             LoadedCommand = new DelegateCommand(OnLoad);
@@ -460,6 +507,75 @@ namespace TeamAAS_VP.ViewModels
 
 
         #region 方法
         #region 方法
 
 
+        #region 扫码枪
+        private void ExecuteAddScannerCommand()
+        {
+            _dialogService.ShowDialog("AddScanner", rst =>
+            {
+                //对话框关闭之后的回调函数,可以在这解析结果。
+                ButtonResult result1 = rst.Result;
+
+                if (result1 == ButtonResult.OK)
+                {
+                    var param = rst.Parameters.GetValue<ScannerInfo>("Scanner");
+                    var scanner = new ScannerInfo()
+                    {
+                        Id = param.Id,
+                        ScannerName = param.ScannerName,
+                        ConnectType = param.ConnectType,
+                        ScannerBrand = param.ScannerBrand,
+                        IP = param.IP,
+                        Port = param.Port,
+                        Terminator = param.Terminator,
+                    };
+                    ScannerList.Add(scanner);
+                    _configService.AddOrUpdateScanner(scanner);
+                    _scannerService.CreateScanner(scanner.Id, scanner);
+                    //对所有产品也进行添加
+                    _productService.AddScannerPointToProduct(scanner.Id, scanner.ScannerName);
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = $"{Lang.添加完成}", Duration = 1 });
+                }
+
+            });
+        }
+        void ExecuteRemoveScannerCommand()
+        {
+            if (MessageBox.Show(Lang.是否移除扫码枪, $"AAS", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
+            {
+
+                // 找到要删除的扫描枪
+                var scannerToRemove = ScannerList.FirstOrDefault(s => s.Id == SelectScanner.Id);
+                if (scannerToRemove != null)
+                {
+                    ScannerList.Remove(scannerToRemove);
+                    _configService.RemoveScanner(scannerToRemove.Id);
+                    _scannerService.RemoveScanner(scannerToRemove.Id);
+                    //对所有产品也进行移除
+                    _productService.RemoveScannerPointFromProduct(scannerToRemove.Id);
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.移除完成, Duration = 1 });
+                }
+            }
+        }
+
+        async void ExecuteSaveScannersCommand()
+        {
+            var view = new ShowMessage($"AAS", Lang.是否保存扫码枪);
+            //show the dialog
+            var result = await DialogHost.Show(view, "RootDialog", null, null, null);
+            if (result != null && result is bool)
+            {
+                if (((bool)result))
+                {
+                    foreach (var item in ScannerList)
+                    {
+                        _configService.AddOrUpdateScanner(item);
+                    }
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.完成, Duration = 1 });
+                }
+            }
+        }
+        #endregion
+
         #region 机器人
         #region 机器人
         private void ExecuteAddRobotCommand()
         private void ExecuteAddRobotCommand()
         {
         {
@@ -1080,7 +1196,12 @@ namespace TeamAAS_VP.ViewModels
 
 
         private void OnLoad()
         private void OnLoad()
         {
         {
-
+            if (!File.Exists(FilePath.ScanRS232ConfigPath))
+            {
+                var scan = new ScanRs232ConfigModel();
+                FileHelper.WriteJsonFile(scan, FilePath.ScanRS232ConfigPath);
+            }
+            this.ScanConfig = FileHelper.ReadJsonFile<ScanRs232ConfigModel>(FilePath.ScanRS232ConfigPath);
         }
         }
 
 
         private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
         private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -1166,6 +1287,16 @@ namespace TeamAAS_VP.ViewModels
                 }
                 }
             }
             }
 
 
+            if (ScannerList == null)
+            {
+                ScannerList = new ObservableCollection<ScannerInfo>();
+                var scanners = _configService.GetAllScanners();
+                foreach (var scanner in scanners)
+                {
+                    ScannerList.Add(scanner);
+                }
+            }
+
             if (CameraList == null)
             if (CameraList == null)
             {
             {
                 CameraList = new ObservableCollection<CameraInfo>();
                 CameraList = new ObservableCollection<CameraInfo>();
@@ -1221,7 +1352,11 @@ namespace TeamAAS_VP.ViewModels
             {
             {
                 DeviceInfo = _configService.GetDeviceInfo();
                 DeviceInfo = _configService.GetDeviceInfo();
             }
             }
-
+            if (CardReaderConfig == null)
+            {
+                // load card reader config
+                CardReaderConfig = _configService.GetCardReaderConfig();
+            }
             CurrentLanguage = _configService.GetSystemConfiguration().CurrentLanguage;
             CurrentLanguage = _configService.GetSystemConfiguration().CurrentLanguage;
 
 
             // load system parameters into UI
             // load system parameters into UI
@@ -1402,6 +1537,8 @@ namespace TeamAAS_VP.ViewModels
             {
             {
                 try
                 try
                 {
                 {
+                    ExecuteSaveCardReaderConfigCommand();
+                    FileHelper.WriteJsonFile(this.ScanConfig, FilePath.ScanRS232ConfigPath);
                     var sysConfig = _configService.GetSystemConfiguration();
                     var sysConfig = _configService.GetSystemConfiguration();
                     sysConfig.WorkMode = WorkMode;
                     sysConfig.WorkMode = WorkMode;
                     sysConfig.PickPointNum = PickPointNum;
                     sysConfig.PickPointNum = PickPointNum;

+ 23 - 0
TeamAAS-VM/Views/Dialogs/TextInputDialog.xaml

@@ -0,0 +1,23 @@
+<Window x:Class="TeamAAS_VP.Views.Dialogs.TextInputDialog"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        Title="AAS" SizeToContent="WidthAndHeight"
+        WindowStartupLocation="CenterOwner"
+        ResizeMode="NoResize"
+        MinWidth="320">
+    <Grid Margin="12">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto"/>
+            <RowDefinition Height="Auto"/>
+            <RowDefinition Height="Auto"/>
+        </Grid.RowDefinitions>
+
+        <TextBlock Text="输入文字:" Margin="0,0,0,6"/>
+        <TextBox x:Name="InputBox" Grid.Row="1" MinWidth="280" Margin="0,0,0,10"/>
+
+        <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right">
+            <Button Content="确定" Width="80" Margin="0,0,8,0" Click="Ok_Click"/>
+            <Button Content="取消" Width="80" Click="Cancel_Click"/>
+        </StackPanel>
+    </Grid>
+</Window>

+ 30 - 0
TeamAAS-VM/Views/Dialogs/TextInputDialog.xaml.cs

@@ -0,0 +1,30 @@
+using System.Windows;
+
+namespace TeamAAS_VP.Views.Dialogs
+{
+    public partial class TextInputDialog : Window
+    {
+        public TextInputDialog()
+        {
+            InitializeComponent();
+        }
+
+        public string InputText
+        {
+            get { return InputBox.Text; }
+            set { InputBox.Text = value; }
+        }
+
+        private void Ok_Click(object sender, RoutedEventArgs e)
+        {
+            DialogResult = true;
+            Close();
+        }
+
+        private void Cancel_Click(object sender, RoutedEventArgs e)
+        {
+            DialogResult = false;
+            Close();
+        }
+    }
+}

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

@@ -480,7 +480,7 @@
                           VerticalAlignment="Bottom"
                           VerticalAlignment="Bottom"
                           Margin=" 120,3"
                           Margin=" 120,3"
                           HorizontalAlignment="Right"
                           HorizontalAlignment="Right"
-                          Content="无SN"
+                          Content="虚拟SN"
                           IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}"
                           IsEnabled="{Binding IsRunning, Converter={StaticResource InvertBooleanConverter}}"
                           IsChecked="{Binding IsNoCode, Mode=TwoWay, Converter={StaticResource InvertBooleanConverter}}" />
                           IsChecked="{Binding IsNoCode, Mode=TwoWay, Converter={StaticResource InvertBooleanConverter}}" />
                 <CheckBox Grid.Row="2"
                 <CheckBox Grid.Row="2"

+ 70 - 0
TeamAAS-VM/Views/ImageView.xaml

@@ -0,0 +1,70 @@
+<UserControl x:Class="TeamAAS_VP.Views.ImageView"
+             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:prism="http://prismlibrary.com/"
+             mc:Ignorable="d"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             d:DesignHeight="450" d:DesignWidth="800">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto"/>
+            <RowDefinition Height="*"/>
+        </Grid.RowDefinitions>
+
+        <StackPanel Orientation="Horizontal" Margin="8">
+            <Button Content="导入图片" Command="{Binding ImportImageCommand}" Margin="0,0,8,0"/>
+            <Button Content="保存" Command="{Binding SaveCommand}" Margin="0,0,8,0"/>
+            <Button Content="清空批注" Command="{Binding ClearCommand}" Margin="0,0,16,0"/>
+
+            <TextBlock VerticalAlignment="Center" Text="工具:" Margin="0,0,4,0"/>
+            <ComboBox Width="120" SelectedValue="{Binding Tool}" SelectedValuePath="Tag">
+                <ComboBoxItem Content="矩形" Tag="Rect"/>
+                <ComboBoxItem Content="箭头" Tag="Arrow"/>
+                <ComboBoxItem Content="文字" Tag="Text"/>
+                <ComboBoxItem Content="选择/移动" Tag="Select"/>
+            </ComboBox>
+
+            <TextBlock VerticalAlignment="Center" Text="颜色:" Margin="16,0,4,0"/>
+            <ComboBox Width="110" SelectedValue="{Binding ColorName}">
+                <ComboBoxItem Content="Red"/>
+                <ComboBoxItem Content="Yellow"/>
+                <ComboBoxItem Content="Lime"/>
+                <ComboBoxItem Content="DodgerBlue"/>
+                <ComboBoxItem Content="White"/>
+                <ComboBoxItem Content="Black"/>
+            </ComboBox>
+
+            <TextBlock VerticalAlignment="Center" Text="线宽:" Margin="16,0,4,0"/>
+            <Slider Width="120" Minimum="1" Maximum="10" Value="{Binding Thickness}"/>
+        </StackPanel>
+
+        <Border Grid.Row="1" Margin="8" BorderBrush="#33000000" BorderThickness="1" Background="Black">
+            <!-- 显示缩放层:只用于显示,不参与保存 -->
+            <Viewbox x:Name="DisplayViewbox" Stretch="Uniform">
+                <!-- 像素层:尺寸=原图像素,批注也在这个坐标系 -->
+                <Grid x:Name="RootPixelRender"
+                      Width="{Binding PixelWidth}"
+                      Height="{Binding PixelHeight}"
+                      Background="Black">
+                    <Image x:Name="Img"
+                           Source="{Binding ImageSource}"
+                           Width="{Binding PixelWidth}"
+                           Height="{Binding PixelHeight}"
+                           Stretch="Fill" />
+                    <Canvas x:Name="AnnoCanvas"
+                            Width="{Binding PixelWidth}"
+                            Height="{Binding PixelHeight}"
+                            Background="Transparent"
+                            Focusable="True"
+                            MouseLeftButtonDown="AnnoCanvas_MouseLeftButtonDown"
+                            MouseMove="AnnoCanvas_MouseMove"
+                            MouseLeftButtonUp="AnnoCanvas_MouseLeftButtonUp"
+                            MouseRightButtonDown="AnnoCanvas_MouseRightButtonDown"
+                            KeyDown="AnnoCanvas_KeyDown"/>
+                </Grid>
+            </Viewbox>
+        </Border>
+    </Grid>
+</UserControl>

+ 260 - 0
TeamAAS-VM/Views/ImageView.xaml.cs

@@ -0,0 +1,260 @@
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Shapes;
+using TeamAAS_VP.ViewModels;
+
+namespace TeamAAS_VP.Views
+{
+    public partial class ImageView : UserControl
+    {
+        private Point _start;
+        private Shape _previewShape;
+        private bool _isDown;
+
+        private UIElement _dragTarget;
+        private Point _dragOffset;
+
+        // 新增:记录当前选中的批注元素
+        private UIElement _selectedAnnotation;
+
+        public ImageView()
+        {
+            InitializeComponent();
+            Loaded += ImageView_Loaded;
+        }
+
+        private void ImageView_Loaded(object sender, RoutedEventArgs e)
+        {
+            var vm = DataContext as ImageViewModel;
+            vm?.AttachRenderTarget(RootPixelRender, AnnoCanvas);
+            vm?.LoadLast();
+
+            // 让 KeyDown 可用
+            AnnoCanvas.Focus();
+        }
+
+        private ImageViewModel Vm => DataContext as ImageViewModel;
+
+        private Point GetPixelPoint(MouseEventArgs e)
+        {
+            var p = e.GetPosition(AnnoCanvas);
+
+            var vm = Vm;
+            if (vm == null || vm.PixelWidth <= 0 || vm.PixelHeight <= 0)
+            {
+                return p;
+            }
+
+            var actualW = AnnoCanvas.ActualWidth;
+            var actualH = AnnoCanvas.ActualHeight;
+            if (actualW <= 0 || actualH <= 0) return p;
+
+            var scaleX = actualW / vm.PixelWidth;
+            var scaleY = actualH / vm.PixelHeight;
+
+            if (scaleX <= 0) scaleX = 1;
+            if (scaleY <= 0) scaleY = 1;
+
+            return new Point(p.X / scaleX, p.Y / scaleY);
+        }
+
+        private UIElement GetAnnotationElementFromOriginalSource(object originalSource)
+        {
+            // 右键/左键命中的可能是:Rectangle/TextBlock/Grid/Line/Polygon 等子元素
+            var element = originalSource as DependencyObject;
+            while (element != null)
+            {
+                if (element is Rectangle) return (UIElement)element;
+                if (element is TextBlock) return (UIElement)element;
+                if (element is Grid) return (UIElement)element;
+
+                // 命中箭头内部:Line/Polygon -> 往上找 Grid
+                element = System.Windows.Media.VisualTreeHelper.GetParent(element);
+            }
+
+            return null;
+        }
+
+        private void SelectAnnotation(UIElement element)
+        {
+            _selectedAnnotation = element;
+
+            // 简单选中效果(可选):给选中项加虚线描边
+            // 只处理 Rectangle / Grid(箭头) 的视觉效果;TextBlock 不做边框避免影响显示
+            foreach (var child in AnnoCanvas.Children)
+            {
+                if (child is Rectangle rr)
+                {
+                    rr.StrokeDashArray = null;
+                }
+            }
+
+            if (_selectedAnnotation is Rectangle r)
+            {
+                r.StrokeDashArray = new System.Windows.Media.DoubleCollection() { 2, 2 };
+            }
+        }
+
+        private void DeleteSelectedAnnotation()
+        {
+            if (Vm == null) return;
+            if (_selectedAnnotation == null) return;
+
+            Vm.RemoveAnnotation(_selectedAnnotation);
+            _selectedAnnotation = null;
+        }
+
+        private void AnnoCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            if (Vm == null) return;
+
+            var hit = GetAnnotationElementFromOriginalSource(e.OriginalSource);
+            if (hit == null || hit == AnnoCanvas)
+            {
+                _selectedAnnotation = null;
+                return;
+            }
+
+            SelectAnnotation(hit);
+            AnnoCanvas.Focus();
+
+            var menu = new ContextMenu();
+            var deleteItem = new MenuItem() { Header = "删除" };
+            deleteItem.Click += (s, ev) => DeleteSelectedAnnotation();
+            menu.Items.Add(deleteItem);
+
+            // 打开菜单
+            menu.PlacementTarget = AnnoCanvas;
+            menu.IsOpen = true;
+
+            e.Handled = true;
+        }
+
+        private void AnnoCanvas_KeyDown(object sender, KeyEventArgs e)
+        {
+            if (e.Key == Key.Delete)
+            {
+                DeleteSelectedAnnotation();
+                e.Handled = true;
+            }
+        }
+
+        private void AnnoCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            if (Vm == null) return;
+
+            _isDown = true;
+            _start = GetPixelPoint(e);
+            AnnoCanvas.CaptureMouse();
+
+            // Select 模式:左键点中即选中
+            if (Vm.Tool == "Select")
+            {
+                var hit = GetAnnotationElementFromOriginalSource(e.OriginalSource);
+                if (hit != null && hit != AnnoCanvas)
+                {
+                    SelectAnnotation(hit);
+                    _dragTarget = hit;
+
+                    var p = _start;
+                    var left = Canvas.GetLeft(_dragTarget);
+                    var top = Canvas.GetTop(_dragTarget);
+                    if (double.IsNaN(left)) left = 0;
+                    if (double.IsNaN(top)) top = 0;
+
+                    _dragOffset = new Point(p.X - left, p.Y - top);
+                }
+                else
+                {
+                    _selectedAnnotation = null;
+                    _dragTarget = null;
+                }
+                return;
+            }
+
+            if (Vm.Tool == "Rect")
+            {
+                var rect = Vm.CreateRect();
+                Canvas.SetLeft(rect, _start.X);
+                Canvas.SetTop(rect, _start.Y);
+                rect.Width = 1;
+                rect.Height = 1;
+
+                _previewShape = rect;
+                AnnoCanvas.Children.Add(rect);
+                return;
+            }
+
+            if (Vm.Tool == "Arrow")
+            {
+                var g = Vm.CreateArrowGroup(_start, _start);
+                AnnoCanvas.Children.Add(g);
+                _previewShape = g.Tag as Shape;
+                return;
+            }
+
+            if (Vm.Tool == "Text")
+            {
+                Vm.CreateTextAt(AnnoCanvas, _start);
+                _isDown = false;
+                AnnoCanvas.ReleaseMouseCapture();
+            }
+        }
+
+        private void AnnoCanvas_MouseMove(object sender, MouseEventArgs e)
+        {
+            if (!_isDown || Vm == null) return;
+
+            var p = GetPixelPoint(e);
+
+            if (Vm.Tool == "Select")
+            {
+                if (_dragTarget != null && _dragTarget != AnnoCanvas && e.LeftButton == MouseButtonState.Pressed)
+                {
+                    Canvas.SetLeft(_dragTarget, p.X - _dragOffset.X);
+                    Canvas.SetTop(_dragTarget, p.Y - _dragOffset.Y);
+                }
+                return;
+            }
+
+            if (Vm.Tool == "Rect" && _previewShape is Rectangle r)
+            {
+                var x = Math.Min(p.X, _start.X);
+                var y = Math.Min(p.Y, _start.Y);
+                var w = Math.Abs(p.X - _start.X);
+                var h = Math.Abs(p.Y - _start.Y);
+
+                Canvas.SetLeft(r, x);
+                Canvas.SetTop(r, y);
+                r.Width = Math.Max(1, w);
+                r.Height = Math.Max(1, h);
+                return;
+            }
+
+            if (Vm.Tool == "Arrow")
+            {
+                Vm.UpdateLastArrow(AnnoCanvas, p);
+            }
+        }
+
+        private void AnnoCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
+        {
+            if (Vm == null) return;
+
+            _isDown = false;
+            AnnoCanvas.ReleaseMouseCapture();
+
+            var p = GetPixelPoint(e);
+
+            if (Vm.Tool == "Arrow")
+            {
+                Vm.CommitLastArrow(AnnoCanvas, p);
+            }
+
+            _previewShape = null;
+            _dragTarget = null;
+        }
+    }
+}

+ 22 - 8
TeamAAS-VM/Views/MainWindowView.xaml

@@ -58,6 +58,7 @@
                     <ColumnDefinition Width="100" />
                     <ColumnDefinition Width="100" />
                     <ColumnDefinition Width="100" />
                     <ColumnDefinition Width="100" />
                     <ColumnDefinition Width="100" />
                     <ColumnDefinition Width="100" />
+                    <ColumnDefinition Width="100" />
                 </Grid.ColumnDefinitions>
                 </Grid.ColumnDefinitions>
                 <Grid.Resources>
                 <Grid.Resources>
 
 
@@ -124,43 +125,56 @@
                                FontWeight="Bold"/>
                                FontWeight="Bold"/>
                 </materialDesign:Card>
                 </materialDesign:Card>
                 <Button Grid.Column="5"
                 <Button Grid.Column="5"
+        Style="{StaticResource MaterialDesignIconButton}"
+        ToolTip="{lex:Loc 图片}"
+        Width="90"
+        Height="90"
+        Background="{Binding NavigationIndex,Converter={StaticResource _NavigationState},ConverterParameter=5}"
+        Command="{Binding NavigationCommand}"
+        CommandParameter="Image">
+                    <materialDesign:PackIcon Kind="Image"
+                             Width="70"
+                             Height="70"
+                             Foreground="{Binding NavigationIndex,Converter={StaticResource _NavigationState1},ConverterParameter=5}" />
+                </Button>
+                <Button Grid.Column="6"
                         Style="{StaticResource MaterialDesignIconButton}"
                         Style="{StaticResource MaterialDesignIconButton}"
                         ToolTip="{lex:Loc 校准}"
                         ToolTip="{lex:Loc 校准}"
                         Width="90"
                         Width="90"
                         Height="90"
                         Height="90"
-                        Background="{Binding NavigationIndex,Converter={StaticResource _NavigationState},ConverterParameter=5}"
+                        Background="{Binding NavigationIndex,Converter={StaticResource _NavigationState},ConverterParameter=6}"
                         Command="{Binding NavigationCommand}"
                         Command="{Binding NavigationCommand}"
                         CommandParameter="Calib">
                         CommandParameter="Calib">
                     <materialDesign:PackIcon Kind="CrosshairsGps"
                     <materialDesign:PackIcon Kind="CrosshairsGps"
                                              Width="70"
                                              Width="70"
                                              Height="70"
                                              Height="70"
-                                             Foreground="{Binding NavigationIndex,Converter={StaticResource _NavigationState1},ConverterParameter=5}" />
+                                             Foreground="{Binding NavigationIndex,Converter={StaticResource _NavigationState1},ConverterParameter=6}" />
                 </Button>
                 </Button>
-                <Button Grid.Column="6"
+                <Button Grid.Column="7"
                         Style="{StaticResource MaterialDesignIconButton}"
                         Style="{StaticResource MaterialDesignIconButton}"
                         ToolTip="{lex:Loc 统计}"
                         ToolTip="{lex:Loc 统计}"
                         Width="90"
                         Width="90"
                         Height="90"
                         Height="90"
-                        Background="{Binding NavigationIndex,Converter={StaticResource _NavigationState},ConverterParameter=6}"
+                        Background="{Binding NavigationIndex,Converter={StaticResource _NavigationState},ConverterParameter=7}"
                         Command="{Binding NavigationCommand}"
                         Command="{Binding NavigationCommand}"
                         CommandParameter="Statistics">
                         CommandParameter="Statistics">
                     <materialDesign:PackIcon Kind="ChartBellCurveCumulative"
                     <materialDesign:PackIcon Kind="ChartBellCurveCumulative"
                                              Width="70"
                                              Width="70"
                                              Height="70"
                                              Height="70"
-                                             Foreground="{Binding NavigationIndex,Converter={StaticResource _NavigationState1},ConverterParameter=6}" />
+                                             Foreground="{Binding NavigationIndex,Converter={StaticResource _NavigationState1},ConverterParameter=7}" />
                 </Button>
                 </Button>
-                <Button Grid.Column="7"
+                <Button Grid.Column="8"
                         Style="{StaticResource MaterialDesignIconButton}"
                         Style="{StaticResource MaterialDesignIconButton}"
                         ToolTip="{lex:Loc 用户}"
                         ToolTip="{lex:Loc 用户}"
                         Width="90"
                         Width="90"
                         Height="90"
                         Height="90"
-                        Background="{Binding NavigationIndex,Converter={StaticResource _NavigationState},ConverterParameter=7}"
+                        Background="{Binding NavigationIndex,Converter={StaticResource _NavigationState},ConverterParameter=8}"
                         Command="{Binding NavigationCommand}"
                         Command="{Binding NavigationCommand}"
                         CommandParameter="User">
                         CommandParameter="User">
                     <materialDesign:PackIcon Kind="AccountMultipleOutline"
                     <materialDesign:PackIcon Kind="AccountMultipleOutline"
                                              Width="70"
                                              Width="70"
                                              Height="70"
                                              Height="70"
-                                             Foreground="{Binding NavigationIndex,Converter={StaticResource _NavigationState1},ConverterParameter=7}" />
+                                             Foreground="{Binding NavigationIndex,Converter={StaticResource _NavigationState1},ConverterParameter=8}" />
                 </Button>
                 </Button>
             </Grid>
             </Grid>
 
 

+ 256 - 0
TeamAAS-VM/Views/Setting/AddScanner.xaml

@@ -0,0 +1,256 @@
+<UserControl x:Class="TeamAAS_VP.Views.Setting.AddScanner"
+             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.Setting"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             xmlns:enums="clr-namespace:TeamAAS_VP.Enums"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:valRules="clr-namespace:TeamAAS_VP.Identity"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             >
+    <prism:Dialog.WindowStyle>
+        <Style TargetType="Window">
+            <Setter Property="prism:Dialog.WindowStartupLocation"
+                Value="CenterScreen" />
+            <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>
+    <UserControl.Resources>
+        <ObjectDataProvider x:Key="eRobotBrand"
+                        MethodName="GetNames"
+                        ObjectType="{x:Type sys:Enum}">
+            <ObjectDataProvider.MethodParameters>
+                <x:Type TypeName="enums:RobotBrand" />
+            </ObjectDataProvider.MethodParameters>
+        </ObjectDataProvider>
+        <ObjectDataProvider x:Key="eTCPConnectType"
+                        MethodName="GetNames"
+                        ObjectType="{x:Type sys:Enum}">
+            <ObjectDataProvider.MethodParameters>
+                <x:Type TypeName="enums:TCPConnectType" />
+            </ObjectDataProvider.MethodParameters>
+        </ObjectDataProvider>
+        <ObjectDataProvider x:Key="eTerminator"
+                        MethodName="GetNames"
+                        ObjectType="{x:Type sys:Enum}">
+            <ObjectDataProvider.MethodParameters>
+                <x:Type TypeName="enums:Terminator" />
+            </ObjectDataProvider.MethodParameters>
+        </ObjectDataProvider>
+        <ObjectDataProvider x:Key="eDataEncoding"
+                        MethodName="GetNames"
+                        ObjectType="{x:Type sys:Enum}">
+            <ObjectDataProvider.MethodParameters>
+                <x:Type TypeName="enums:DataEncoding" />
+            </ObjectDataProvider.MethodParameters>
+        </ObjectDataProvider>
+    </UserControl.Resources>
+    <Grid HorizontalAlignment="Center">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="*" />
+            <RowDefinition Height="50" />
+        </Grid.RowDefinitions>
+
+        <!--参数详情-->
+        <Grid Margin="20,20">
+            <Grid.RowDefinitions>
+                <RowDefinition />
+                <RowDefinition />
+                <RowDefinition />
+                <RowDefinition />
+                <RowDefinition />
+                <RowDefinition />
+                <RowDefinition />
+                <RowDefinition />
+            </Grid.RowDefinitions>
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="50*" />
+                <ColumnDefinition Width="50*" />
+            </Grid.ColumnDefinitions>
+            <!--id-->
+            <TextBlock Text="Id:"
+                Grid.Row="0"
+                Grid.Column="0"
+                Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+                HorizontalAlignment="Right"
+                VerticalAlignment="Center" />
+            <TextBlock x:Name="txt_Id"
+               Text="{Binding Scanner.Id,Mode=TwoWay}"
+               Grid.Row="0"
+               Grid.Column="1"
+               Margin="10,0"
+               HorizontalAlignment="Left"
+               VerticalAlignment="Center" />
+            <!--名称-->
+            <TextBlock Text="{lex:Loc 名称}"
+               Grid.Row="1"
+               Grid.Column="0"
+               Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+               HorizontalAlignment="Right"
+               VerticalAlignment="Center" />
+            <TextBox x:Name="txt_Name"
+             Grid.Row="1"
+             Grid.Column="1"
+             Margin="10,0"
+             Width="{Binding ElementName=txt_Id,Path=ActualWidth}"
+             MinWidth="80"
+             TextAlignment="Center"
+             HorizontalAlignment="Left"
+             VerticalAlignment="Center">
+                <TextBox.Text>
+                    <Binding Path="Scanner.ScannerName"
+                     Mode="TwoWay">
+                        <Binding.ValidationRules>
+                            <valRules:NameValidationRule />
+                        </Binding.ValidationRules>
+                    </Binding>
+                </TextBox.Text>
+            </TextBox>
+            <!--通讯方式-->
+            <TextBlock Text="{lex:Loc 通讯方式}"
+               Grid.Row="3"
+               Grid.Column="0"
+               Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+               HorizontalAlignment="Right"
+               VerticalAlignment="Center" />
+            <ComboBox Text="{Binding Scanner.ConnectType,Mode=TwoWay}"
+              Grid.Row="3"
+              Grid.Column="1"
+              Margin="10,0"
+              Width="{Binding ElementName=txt_Id,Path=ActualWidth}"
+              MinWidth="80"
+              HorizontalContentAlignment="Center"
+              ItemsSource="{Binding Source={StaticResource  eTCPConnectType}}"
+              HorizontalAlignment="Left"
+              VerticalAlignment="Center" />
+            <!--IP地址-->
+            <TextBlock Text="IP:"
+               Grid.Row="4"
+               Grid.Column="0"
+               Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+               HorizontalAlignment="Right"
+               VerticalAlignment="Center" />
+            <TextBox x:Name="txt_IP"
+             Grid.Row="4"
+             Grid.Column="1"
+             Margin="10,0"
+             Width="{Binding ElementName=txt_Id,Path=ActualWidth}"
+             MinWidth="80"
+             TextAlignment="Center"
+             HorizontalAlignment="Left"
+             VerticalAlignment="Center">
+                <TextBox.Text>
+                    <Binding Path="Scanner.IP"
+                     Mode="TwoWay">
+                        <Binding.ValidationRules>
+                            <valRules:IPValidationRule />
+                        </Binding.ValidationRules>
+                    </Binding>
+                </TextBox.Text>
+            </TextBox>
+            <!--端口号-->
+            <TextBlock Text="Port:"
+               Grid.Row="5"
+               Grid.Column="0"
+               Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+               HorizontalAlignment="Right"
+               VerticalAlignment="Center" />
+            <TextBox x:Name="txt_Port"
+             Grid.Row="5"
+             Grid.Column="1"
+             Margin="10,0"
+             Width="{Binding ElementName=txt_Id,Path=ActualWidth}"
+             MinWidth="80"
+             TextAlignment="Center"
+             HorizontalAlignment="Left"
+             VerticalAlignment="Center">
+                <TextBox.Text>
+                    <Binding Path="Scanner.Port"
+                     Mode="TwoWay">
+                        <Binding.ValidationRules>
+                            <valRules:PortValidationRule />
+                        </Binding.ValidationRules>
+                    </Binding>
+                </TextBox.Text>
+            </TextBox>
+            <!--结束符-->
+            <TextBlock Text="{lex:Loc 结束符}"
+               Grid.Row="6"
+               Grid.Column="0"
+               Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+               HorizontalAlignment="Right"
+               VerticalAlignment="Center" />
+            <ComboBox Text="{Binding Scanner.Terminator,Mode=TwoWay}"
+              Grid.Row="6"
+              Grid.Column="1"
+              Margin="10,0"
+              Width="{Binding ElementName=txt_Id,Path=ActualWidth}"
+              MinWidth="80"
+              HorizontalContentAlignment="Center"
+              ItemsSource="{Binding Source={StaticResource  eTerminator}}"
+              HorizontalAlignment="Left"
+              VerticalAlignment="Center" />
+
+        </Grid>
+        <StackPanel Grid.Row="1"
+            Orientation="Horizontal"
+            HorizontalAlignment="Right">
+            <Button Height="30"
+            materialDesign:ButtonAssist.CornerRadius="10"
+            ToolTip="{lex:Loc 确定}"
+            Command="{Binding ConfirmCommand}">
+                <TextBlock Text="{lex:Loc 确定}" />
+                <Button.Style>
+                    <Style TargetType="Button"
+                   BasedOn="{StaticResource MaterialDesignRaisedButton}">
+                        <Style.Triggers>
+                            <MultiDataTrigger>
+                                <MultiDataTrigger.Conditions>
+                                    <!-- 当且仅当IP地址合规且其他条件满足时,启用按钮 -->
+                                    <Condition Binding="{Binding ElementName=txt_IP, Path=(Validation.HasError)}"
+                                       Value="False" />
+                                    <Condition Binding="{Binding ElementName=txt_Name, Path=(Validation.HasError)}"
+                                       Value="False" />
+                                    <Condition Binding="{Binding ElementName=txt_Port, Path=(Validation.HasError)}"
+                                       Value="False" />
+                                </MultiDataTrigger.Conditions>
+                                <Setter Property="IsEnabled"
+                                Value="True" />
+                            </MultiDataTrigger>
+                        </Style.Triggers>
+                    </Style>
+                </Button.Style>
+            </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>

+ 28 - 0
TeamAAS-VM/Views/Setting/AddScanner.xaml.cs

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

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

@@ -213,7 +213,282 @@
                 </Grid>
                 </Grid>
             </TabItem>
             </TabItem>
 
 
+            <TabItem>
+                <TabItem.Header>
+                    <StackPanel>
+                        <materialDesign:PackIcon Width="24"
+                             Height="24"
+                             HorizontalAlignment="Center"
+                             Kind="CodeArray" />
+                        <TextBlock HorizontalAlignment="Center"
+                                FontSize="{DynamicResource Font.Size.Body2}"
+                                Text="{lex:Loc 扫码枪}" />
+                    </StackPanel>
+                </TabItem.Header>
+                <Grid Margin="16">
+                    <Grid.RowDefinitions>
+                        <RowDefinition Height="50" />
+                        <RowDefinition Height="*" />
+                    </Grid.RowDefinitions>
+                    <Grid.ColumnDefinitions>
+                        <ColumnDefinition Width="auto" />
+                        <ColumnDefinition Width="*" />
+                    </Grid.ColumnDefinitions>
+                    <!--增删改查-->
+                    <StackPanel Grid.ColumnSpan="2"
+                        IsEnabled="{Binding IsAllowEdit}"
+                        Orientation="Horizontal">
+                        <Button Style="{StaticResource MaterialDesignFloatingActionMiniLightButton}"
+                                ToolTip="{lex:Loc 增加扫码枪}"
+                                Command="{Binding AddScannerCommand}">
+                            <materialDesign:PackIcon Kind="Plus" />
+                        </Button>
+                        <Button Style="{StaticResource MaterialDesignFloatingActionMiniDarkButton}"
+                                ToolTip="{lex:Loc 修改扫码枪}"
+                                Margin="20,0"
+                                Command="{Binding EditScannerCommand}">
+                            <materialDesign:PackIcon Kind="PuzzleEditOutline" />
+                        </Button>
+                        <Button Style="{StaticResource MaterialDesignFloatingActionMiniDarkButton}"
+                                ToolTip="{lex:Loc 移除扫码枪}"
+                                Command="{Binding RemoveScannerCommand}">
+                            <materialDesign:PackIcon Kind="DeleteForeverOutline" />
+                        </Button>
+                        <Button Style="{StaticResource MaterialDesignFloatingActionMiniSecondaryDarkButton}"
+                                ToolTip="{lex:Loc 保存扫码枪}"
+                                Margin="20,0"
+                                Command="{Binding SaveScannerCommand}">
+                            <materialDesign:PackIcon Kind="ContentSaveCheck" />
+                        </Button>
+
+                    </StackPanel>
 
 
+                    <!--扫码枪列表-->
+                    <TreeView Grid.Row="1"
+                        Grid.Column="0"
+                        SelectedItemChanged="TreeView_SelectedItemChanged">
+                        <TreeViewItem Header="{lex:Loc 扫码枪列表}"
+                            FontSize="{DynamicResource Font.Size.Title4}"
+                            FontWeight="Bold"
+                            IsExpanded="True"
+                            ItemsSource="{Binding ScannerList}">
+                            <TreeViewItem.ItemTemplate>
+                                <HierarchicalDataTemplate>
+                                    <StackPanel Orientation="Vertical">
+                                        <TextBlock Text="{Binding Name,Mode=TwoWay}"
+                                            FontSize="{DynamicResource Font.Size.Title4}" />
+                                        <StackPanel Orientation="Horizontal">
+                                            <TextBlock Text="{lex:Loc 名称}"
+                                                Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                                                FontSize="{DynamicResource Font.Size.Captions3}" />
+                                            <TextBlock Text="{Binding Name,Mode=TwoWay}"
+                                                Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                                                FontSize="{DynamicResource Font.Size.Captions3}" />
+                                            <TextBlock Text="{lex:Loc 连接方式}"
+                            Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                            FontSize="10"
+                            Margin="10,0,0,0" />
+                                            <TextBlock Text="{Binding ConnectType,Mode=TwoWay}"
+                            Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                            FontSize="{DynamicResource Font.Size.Captions3}" />
+                                        </StackPanel>
+                                        <StackPanel Orientation="Horizontal">
+                                            <TextBlock Text="{Binding IP,StringFormat=IP:{0},Mode=TwoWay}"
+                            Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                            FontSize="{DynamicResource Font.Size.Captions3}" />
+                                            <TextBlock Text="{Binding Port,StringFormat=Port:{0},Mode=TwoWay}"
+                            Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                            FontSize="{DynamicResource Font.Size.Captions3}"
+                            Margin="10,0" />
+                                            <TextBlock Text="{lex:Loc 结束符}"
+                            Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                            FontSize="{DynamicResource Font.Size.Captions3}" />
+                                            <TextBlock Text="{Binding Terminator,Mode=TwoWay}"
+                            Style="{StaticResource MaterialDesignCaptionTextBlock}"
+                            FontSize="{DynamicResource Font.Size.Captions3}" />
+                                        </StackPanel>
+                                        <Border Height="2"
+                        Margin="0"
+                        BorderThickness="2"
+                        BorderBrush="Green" />
+                                    </StackPanel>
+                                </HierarchicalDataTemplate>
+                            </TreeViewItem.ItemTemplate>
+                        </TreeViewItem>
+                    </TreeView>
+
+                    <!--参数详情-->
+                    <ScrollViewer Grid.Row="1"
+    Grid.Column="1"
+    IsEnabled="{Binding IsAllowEdit}"
+    Margin="20">
+                        <Grid MinHeight="300"
+        HorizontalAlignment="Left"
+        VerticalAlignment="Top">
+                            <Grid.RowDefinitions>
+                                <RowDefinition />
+                                <RowDefinition />
+                                <RowDefinition />
+                                <RowDefinition />
+                                <RowDefinition />
+                                <RowDefinition />
+                                <RowDefinition />
+                                <RowDefinition />
+                            </Grid.RowDefinitions>
+                            <Grid.ColumnDefinitions>
+                                <ColumnDefinition Width="auto" />
+                                <ColumnDefinition Width="*" />
+                            </Grid.ColumnDefinitions>
+                            <!--id-->
+                            <TextBlock Text="Id:"
+            Grid.Row="0"
+            Grid.Column="0"
+            Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+            HorizontalAlignment="Right"
+            VerticalAlignment="Center"
+            FontSize="{DynamicResource Font.Size.Body3}" />
+                            <TextBlock x:Name="txt_ScannerId"
+            Text="{Binding SelectScanner.Id,Mode=TwoWay}"
+            Grid.Row="0"
+            Grid.Column="1"
+            Margin="10,0"
+            HorizontalAlignment="Left"
+            VerticalAlignment="Center"
+            FontSize="{DynamicResource Font.Size.Body3}" />
+                            <!--名称-->
+                            <TextBlock Text="{lex:Loc 名称}"
+            Grid.Row="1"
+            Grid.Column="0"
+            Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+            HorizontalAlignment="Right"
+            VerticalAlignment="Center"
+            FontSize="{DynamicResource Font.Size.Body3}" />
+                            <TextBox Grid.Row="1"
+            Grid.Column="1"
+            Margin="10,0"
+            Width="{Binding ElementName=txt_ScannerId,Path=ActualWidth}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            MinWidth="80"
+            TextAlignment="Center"
+            HorizontalAlignment="Left"
+            VerticalAlignment="Center"
+            IsEnabled="False" 
+            Focusable="False"
+           >
+                                <TextBox.Text>
+                                    <Binding Path="SelectScanner.ScannerName"
+                    Mode="TwoWay">
+                                        <Binding.ValidationRules>
+                                            <valRules:NameValidationRule />
+                                        </Binding.ValidationRules>
+                                    </Binding>
+                                </TextBox.Text>
+                            </TextBox>
+                            <!--通讯方式-->
+                            <TextBlock Text="{lex:Loc 通讯方式}"
+            Grid.Row="2"
+            Grid.Column="0"
+            Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            HorizontalAlignment="Right"
+            VerticalAlignment="Center" />
+                            <ComboBox 
+            Grid.Row="2"
+            Grid.Column="1"
+            Margin="10,0"
+            Width="{Binding ElementName=txt_ScannerId,Path=ActualWidth}"
+            MinWidth="80"
+            ItemsSource="{ext:EnumBindingSource EnumType=enums:TCPConnectType}"
+            SelectedItem="{Binding SelectScanner.ConnectType, Mode=TwoWay}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            HorizontalContentAlignment="Center"
+            HorizontalAlignment="Left"
+            VerticalAlignment="Center" 
+            IsEnabled="False" 
+            Focusable="False"/>
+                            <!--IP地址-->
+                            <TextBlock Text="IP:"
+            Grid.Row="3"
+            Grid.Column="0"
+            Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            HorizontalAlignment="Right"
+            VerticalAlignment="Center" />
+                            <TextBox Grid.Row="3"
+            Grid.Column="1"
+            Margin="10,0"
+            Width="{Binding ElementName=txt_ScannerId,Path=ActualWidth}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            MinWidth="80"
+            TextAlignment="Center"
+            HorizontalAlignment="Left"
+            VerticalAlignment="Center"
+            IsEnabled="False" 
+            Focusable="False">
+                                <TextBox.Text>
+                                    <Binding Path="SelectScanner.IP"
+                    Mode="TwoWay">
+                                        <Binding.ValidationRules>
+                                            <valRules:IPValidationRule />
+                                        </Binding.ValidationRules>
+                                    </Binding>
+                                </TextBox.Text>
+                            </TextBox>
+                            <!--端口号-->
+                            <TextBlock Text="Port:"
+            Grid.Row="4"
+            Grid.Column="0"
+            Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            HorizontalAlignment="Right"
+            VerticalAlignment="Center" />
+                            <TextBox Grid.Row="4"
+            Grid.Column="1"
+            Margin="10,0"
+            Width="{Binding ElementName=txt_ScannerId,Path=ActualWidth}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            MinWidth="80"
+            TextAlignment="Center"
+            HorizontalAlignment="Left"
+            VerticalAlignment="Center"
+            IsEnabled="False" 
+            Focusable="False">
+                                <TextBox.Text>
+                                    <Binding Path="SelectScanner.Port"
+                    Mode="TwoWay">
+                                        <Binding.ValidationRules>
+                                            <valRules:PortValidationRule />
+                                        </Binding.ValidationRules>
+                                    </Binding>
+                                </TextBox.Text>
+                            </TextBox>
+                            <!--结束符-->
+                            <TextBlock Text="{lex:Loc 结束符}"
+            Grid.Row="5"
+            Grid.Column="0"
+            Style="{StaticResource MaterialDesignSubtitle1TextBlock}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            HorizontalAlignment="Right"
+            VerticalAlignment="Center" />
+                            <!-- 关键修改:用 SelectedItem 绑定枚举值,ItemsSource 直接绑定枚举类型(无需 ObjectDataProvider) -->
+                            <ComboBox 
+            Grid.Row="5"
+            Grid.Column="1"
+            Margin="10,0"
+            Width="{Binding ElementName=txt_ScannerId,Path=ActualWidth}"
+            MinWidth="80"
+            ItemsSource="{ext:EnumBindingSource EnumType=enums:Terminator}"
+            SelectedItem="{Binding SelectScanner.Terminator, Mode=TwoWay}"
+            FontSize="{DynamicResource Font.Size.Body3}"
+            HorizontalContentAlignment="Center"
+            HorizontalAlignment="Left"
+            VerticalAlignment="Center"                                     
+            IsEnabled="False" 
+            Focusable="False"/>
+                        </Grid>
+                    </ScrollViewer>
+                </Grid>
+            </TabItem>
             <!--设备信息-->
             <!--设备信息-->
             <TabItem>
             <TabItem>
                 <TabItem.Header>
                 <TabItem.Header>
@@ -463,9 +738,20 @@
                              Text="{Binding DeviceInfo.DataInfo.PROCESS_MACHINE_ID, Mode=TwoWay}"
                              Text="{Binding DeviceInfo.DataInfo.PROCESS_MACHINE_ID, Mode=TwoWay}"
                              Margin="6,2" />
                              Margin="6,2" />
 
 
+                    <TextBlock Grid.Row="22"
+                       Grid.Column="0"
+                       Text="虚拟SN:"
+                       HorizontalAlignment="Right"
+                       VerticalAlignment="Center" />
+                    <TextBox Grid.Row="22"
+                         Grid.Column="1"
+                         Text="{Binding DeviceInfo.XnSN, Mode=TwoWay}"
+                         Margin="6,2" />
+
+
                     <Button Content="保存"
                     <Button Content="保存"
                             Command="{Binding SaveDeviceInfoCommand}"
                             Command="{Binding SaveDeviceInfoCommand}"
-                            Grid.Row="22"
+                            Grid.Row="23"
                             HorizontalAlignment="Center"
                             HorizontalAlignment="Center"
                             Margin="0,10"
                             Margin="0,10"
                             Grid.Column="1" />
                             Grid.Column="1" />
@@ -2459,7 +2745,83 @@
                                 </Button>
                                 </Button>
                             </Grid>
                             </Grid>
                         </GroupBox>
                         </GroupBox>
-
+                        <GroupBox Grid.Row="5"
+          Header="{lex:Loc 扫码机配置}"
+          HorizontalAlignment="Left"
+          MinWidth="200"
+          Margin="0,0,20,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 ScanConfig.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 ScanConfig.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 ScanConfig.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 ScanConfig.StopBits,Mode=TwoWay}"
+                  ItemsSource="{Binding Source={StaticResource StopBits}}" />
+                                <TextBlock Text="DataBits:"
+                   Grid.Row="4"
+                   Grid.Column="0"
+                   HorizontalAlignment="Right" />
+                                <TextBox Text="{Binding ScanConfig.DataBits,Mode=TwoWay}"
+                 Grid.Row="4"
+                 Grid.Column="1"
+                 Margin="6,0" />
+
+                                <!--<Button Grid.Row="5"
+            Grid.Column="0"
+            Grid.ColumnSpan="2"
+            Margin="0,10,0,0"
+            Style="{StaticResource MaterialDesignRaisedButton}"
+            materialDesign:ButtonAssist.CornerRadius="10"
+            MinWidth="120"
+            Command="{Binding SaveScanConfigConfigCommand}">
+            <StackPanel Orientation="Horizontal"
+                HorizontalAlignment="Center">
+                <materialDesign:PackIcon Kind="ContentSaveCheck"
+                Margin="0,0,6,0" />
+                <TextBlock VerticalAlignment="Center"
+                Text="保存扫码机配置" />
+            </StackPanel>
+        </Button>-->
+                            </Grid>
+                        </GroupBox>
 
 
                     </StackPanel>
                     </StackPanel>
                 </StackPanel>
                 </StackPanel>

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

@@ -6,6 +6,7 @@ using System;
 using System.Windows.Controls;
 using System.Windows.Controls;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Models;
 using TeamAAS_VP.Models.Lights;
 using TeamAAS_VP.Models.Lights;
+using TeamAAS_VP.Models.Scanner;
 using TeamAAS_VP.ViewModels;
 using TeamAAS_VP.ViewModels;
 
 
 namespace TeamAAS_VP.Views
 namespace TeamAAS_VP.Views
@@ -30,6 +31,10 @@ namespace TeamAAS_VP.Views
                 {
                 {
                     viewModel.SelectRobot = e.NewValue as RobotInfo;
                     viewModel.SelectRobot = e.NewValue as RobotInfo;
                 }
                 }
+                if (e.NewValue is ScannerInfo)
+                {
+                    viewModel.SelectScanner = e.NewValue as ScannerInfo;
+                }
                 else if (e.NewValue is FeederInfo)
                 else if (e.NewValue is FeederInfo)
                 {
                 {
                     viewModel.SelectFeeder = e.NewValue as FeederInfo;
                     viewModel.SelectFeeder = e.NewValue as FeederInfo;