Sfoglia il codice sorgente

添加项目文件。

刘彬 2 mesi fa
commit
50445da8fe
100 ha cambiato i file con 29388 aggiunte e 0 eliminazioni
  1. 63 0
      .gitattributes
  2. 369 0
      .gitignore
  3. 0 0
      README.md
  4. 4 0
      ResXManager.config.xml
  5. 856 0
      Team.FFFeederService/AfagFeeder.cs
  6. 194 0
      Team.FFFeederService/AutoAdjustmentParameter.cs
  7. 16 0
      Team.FFFeederService/Enums/ActionType.cs
  8. 15 0
      Team.FFFeederService/Enums/DurationMode.cs
  9. 59 0
      Team.FFFeederService/Enums/FeederAction.cs
  10. 20 0
      Team.FFFeederService/Enums/FeederModel.cs
  11. 31 0
      Team.FFFeederService/Enums/WaveShape.cs
  12. 18 0
      Team.FFFeederService/FeederBrand.cs
  13. 316 0
      Team.FFFeederService/FeederIPManage.cs
  14. 161 0
      Team.FFFeederService/FeederService.cs
  15. 44 0
      Team.FFFeederService/Interfaces/IFeeder.cs
  16. 19 0
      Team.FFFeederService/Interfaces/IFeederService.cs
  17. 525 0
      Team.FFFeederService/Interfaces/IVoiceCoilMotor.cs
  18. 79 0
      Team.FFFeederService/Models/ActionParamcAutoFindParam.cs
  19. 60 0
      Team.FFFeederService/Models/ActionParamcs.cs
  20. 30 0
      Team.FFFeederService/Models/AutoFindParamModel.cs
  21. 26 0
      Team.FFFeederService/Models/FeederActionParam.cs
  22. 24 0
      Team.FFFeederService/Models/FeederNetworkInterface.cs
  23. 168 0
      Team.FFFeederService/Models/FeederNetworkInterfaceInfo.cs
  24. 169 0
      Team.FFFeederService/Models/HopperFeederParam.cs
  25. 29 0
      Team.FFFeederService/Models/NetworkInterfaceInfo.cs
  26. 131 0
      Team.FFFeederService/Models/SingleActionParam.cs
  27. 156 0
      Team.FFFeederService/Models/SingleSequenceAction.cs
  28. 109 0
      Team.FFFeederService/Models/SingleSequenceActionGroup.cs
  29. 134 0
      Team.FFFeederService/Models/VoiceMotorParam.cs
  30. 36 0
      Team.FFFeederService/Properties/AssemblyInfo.cs
  31. BIN
      Team.FFFeederService/Resources/AutoParaADJ.dll
  32. 168 0
      Team.FFFeederService/TCPCommunicationClass.cs
  33. 143 0
      Team.FFFeederService/Team.FFFeederService.csproj
  34. 1690 0
      Team.FFFeederService/TeamFeeder.cs
  35. 221 0
      Team.FFFeederService/VibrationFrequencyDetector .cs
  36. 445 0
      Team.FFFeederService/aflexCommunicationClass.cs
  37. 23 0
      Team.FFFeederService/app.config
  38. 15 0
      Team.FFFeederService/packages.config
  39. 31 0
      TeamAAS-VM.sln
  40. 300 0
      TeamAAS-VM/App.config
  41. 49 0
      TeamAAS-VM/App.xaml
  42. 246 0
      TeamAAS-VM/App.xaml.cs
  43. 15 0
      TeamAAS-VM/Attributes/LocalizationAttribute.cs
  44. 92 0
      TeamAAS-VM/Behaviors/ComboBoxSelectionBehavior.cs
  45. 125 0
      TeamAAS-VM/Controls/AddPalletView.xaml
  46. 314 0
      TeamAAS-VM/Controls/AddPalletView.xaml.cs
  47. 60 0
      TeamAAS-VM/Controls/AddProduct.xaml
  48. 130 0
      TeamAAS-VM/Controls/AddProduct.xaml.cs
  49. 170 0
      TeamAAS-VM/Controls/AflexControl.xaml
  50. 186 0
      TeamAAS-VM/Controls/AflexControl.xaml.cs
  51. 162 0
      TeamAAS-VM/Controls/FeederOutput.xaml
  52. 376 0
      TeamAAS-VM/Controls/FeederOutput.xaml.cs
  53. 1384 0
      TeamAAS-VM/Controls/FeederSequence.xaml
  54. 697 0
      TeamAAS-VM/Controls/FeederSequence.xaml.cs
  55. 148 0
      TeamAAS-VM/Controls/FeederSystemParam.xaml
  56. 318 0
      TeamAAS-VM/Controls/FeederSystemParam.xaml.cs
  57. 74 0
      TeamAAS-VM/Controls/ParameterEdit.xaml
  58. 147 0
      TeamAAS-VM/Controls/ParameterEdit.xaml.cs
  59. 36 0
      TeamAAS-VM/Controls/PictureDisplayControl.xaml
  60. 154 0
      TeamAAS-VM/Controls/PictureDisplayControl.xaml.cs
  61. 230 0
      TeamAAS-VM/Controls/RobotManual.xaml
  62. 472 0
      TeamAAS-VM/Controls/RobotManual.xaml.cs
  63. 224 0
      TeamAAS-VM/Controls/ScriptEditControl.xaml
  64. 619 0
      TeamAAS-VM/Controls/ScriptEditControl.xaml.cs
  65. 69 0
      TeamAAS-VM/Controls/ShowMessage.xaml
  66. 131 0
      TeamAAS-VM/Controls/ShowMessage.xaml.cs
  67. 63 0
      TeamAAS-VM/Controls/UProgressBar.xaml
  68. 239 0
      TeamAAS-VM/Controls/UProgressBar.xaml.cs
  69. 276 0
      TeamAAS-VM/Controls/VibrationControl.xaml
  70. 195 0
      TeamAAS-VM/Controls/VibrationControl.xaml.cs
  71. 806 0
      TeamAAS-VM/Controls/VibrationPara.xaml
  72. 896 0
      TeamAAS-VM/Controls/VibrationPara.xaml.cs
  73. 30 0
      TeamAAS-VM/Controls/WaitingPage.xaml
  74. 28 0
      TeamAAS-VM/Controls/WaitingPage.xaml.cs
  75. 67 0
      TeamAAS-VM/Controls/myNumericUpDowm.xaml
  76. 159 0
      TeamAAS-VM/Controls/myNumericUpDowm.xaml.cs
  77. 403 0
      TeamAAS-VM/Core/BgCommunicate.cs
  78. 329 0
      TeamAAS-VM/Core/BgModbusTcpCommunicate.cs
  79. 100 0
      TeamAAS-VM/Core/BraceFoldingStrategy.cs
  80. 894 0
      TeamAAS-VM/Core/Cameras/AHuaCamera.cs
  81. 958 0
      TeamAAS-VM/Core/Cameras/BaslerCamera.cs
  82. 145 0
      TeamAAS-VM/Core/Cameras/CameraService.cs
  83. 539 0
      TeamAAS-VM/Core/Cameras/CognexCamera.cs
  84. 931 0
      TeamAAS-VM/Core/Cameras/GalaxyCamera.cs
  85. 566 0
      TeamAAS-VM/Core/Cameras/MvCamera.cs
  86. 79 0
      TeamAAS-VM/Core/Common.cs
  87. 196 0
      TeamAAS-VM/Core/CoordinateTransformer.cs
  88. 108 0
      TeamAAS-VM/Core/DetectionResult.cs
  89. 168 0
      TeamAAS-VM/Core/FileHelper.cs
  90. 163 0
      TeamAAS-VM/Core/FilePath.cs
  91. 311 0
      TeamAAS-VM/Core/GalaxyMethod/CDecide.cs
  92. 82 0
      TeamAAS-VM/Core/GalaxyMethod/CWin32Bitmaps.cs
  93. 45 0
      TeamAAS-VM/Core/ImageHelper.cs
  94. 75 0
      TeamAAS-VM/Core/IniConfigHelper.cs
  95. 5204 0
      TeamAAS-VM/Core/Management.cs
  96. 518 0
      TeamAAS-VM/Core/ModbusTcpMasterCommunicate.cs
  97. 66 0
      TeamAAS-VM/Core/PLCs/MitsubishiMcPLC.cs
  98. 994 0
      TeamAAS-VM/Core/PLCs/MitsubishiPLC.cs
  99. 122 0
      TeamAAS-VM/Core/PLCs/OPCuaClientPLC.cs
  100. 108 0
      TeamAAS-VM/Core/PLCs/PlcService.cs

+ 63 - 0
.gitattributes

@@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs     diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following 
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln       merge=binary
+#*.csproj    merge=binary
+#*.vbproj    merge=binary
+#*.vcxproj   merge=binary
+#*.vcproj    merge=binary
+#*.dbproj    merge=binary
+#*.fsproj    merge=binary
+#*.lsproj    merge=binary
+#*.wixproj   merge=binary
+#*.modelproj merge=binary
+#*.sqlproj   merge=binary
+#*.wwaproj   merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg   binary
+#*.png   binary
+#*.gif   binary
+
+###############################################################################
+# diff behavior for common document formats
+# 
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the 
+# entries below.
+###############################################################################
+#*.doc   diff=astextplain
+#*.DOC   diff=astextplain
+#*.docx  diff=astextplain
+#*.DOCX  diff=astextplain
+#*.dot   diff=astextplain
+#*.DOT   diff=astextplain
+#*.pdf   diff=astextplain
+#*.PDF   diff=astextplain
+#*.rtf   diff=astextplain
+#*.RTF   diff=astextplain

+ 369 - 0
.gitignore

@@ -0,0 +1,369 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Oo]ut/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd
+
+#      TeamAAS-VM/TeamAAS-VP/exe/  ļ    µ      ļ 
+*.rar
+TeamAAS-VP/
+*.bak
+*.txt

+ 0 - 0
README.md


+ 4 - 0
ResXManager.config.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Values xmlns="urn:tom-englert.de/Configuration/1/0">
+  <Value Key="NeutralResourcesLanguage">zh-CN</Value>
+</Values>

+ 856 - 0
Team.FFFeederService/AfagFeeder.cs

@@ -0,0 +1,856 @@
+using aflex_CSharp_Integration_Sample;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+//using System.Net.Sockets;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Team.FFFeederService.Enums;
+using Team.FFFeederService.Interfaces;
+using Team.FFFeederService.Models;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace Team.FFFeederService
+{
+    public struct FeederParam
+    {
+        public double backLightIntensity;//光源强度
+        public byte configNum;//震动模式
+        public double degreeNum;//震动角度
+        public double vibrationIntensity;//震动强度
+        public double intervalNum;//间隔时间ms
+    }
+
+    public class AfagFeeder : IVoiceCoilMotorFeeder
+    {
+        public TcpClient TcpClient { get; }
+
+        public int FeederPort { get; private set; }
+
+        public string FeederIp { get; private set; }
+
+        public FeederBrand FeederBrand { get => FeederBrand.AFAG; }
+
+        public FeederModel FeederModel { get; private set; } = FeederModel.Unknown;
+
+        public Guid Id { get; set; }
+
+        public bool IsConnected => IsInit;
+
+        public bool IsInit { get; set; }
+
+        public event Action<Guid, ITcpClient, ConnectedEventArgs> FeederConnectedEvent;
+        public event Action<Guid, ITcpClient, ClosedEventArgs> FeederDisconnectedEvent;
+
+        private aflexCommunicationClass objaflex;
+
+        Timer feedStepTimer;
+        uint stepNum = 0;
+        TimeSpan durationNum = new TimeSpan();
+
+        /// <summary>
+        /// 配置编号
+        /// </summary>
+        public int ConfigIndex
+        {
+            get
+            {
+                if (objaflex == null) return 0;
+                else return objaflex.actual_ConfigNumber;
+            }
+        }
+
+        /// <summary>
+        /// 振动强度
+        /// </summary>
+        public double Intensity
+        {
+            get
+            {
+                if (objaflex == null) return 0;
+                else return objaflex.actual_intensity;
+            }
+        }
+
+        /// <summary>
+        /// 方向
+        /// </summary>
+        public double Direction
+        {
+            get
+            {
+                if (objaflex == null) return 0;
+                else return objaflex.actual_direction;
+            }
+        }
+
+
+        public AfagFeeder(Guid id, string ip, int port)
+        {
+            Id = id;
+            FeederIp = ip;
+            FeederPort = port;
+            objaflex = new aflexCommunicationClass();
+            objaflex.aflexValueChanged += Objaflex_aflexValueChanged;
+        }
+
+        private void Objaflex_aflexValueChanged(object sender, EventArgs e)
+        {
+
+        }
+
+        public void CloseLight()
+        {
+            try
+            {
+                if (!objaflex.actual_AutoMode) return;
+                objaflex.SetAuxPowerOut(0);
+            }
+            catch (Exception)
+            {
+
+            }
+
+        }
+
+        public Task CloseLightAsync()
+        {
+            try
+            {
+                if (!objaflex.actual_AutoMode) return Task.CompletedTask;
+                objaflex.SetAuxPowerOut(0);
+            }
+            catch (Exception)
+            {
+
+            }
+            return Task.CompletedTask;
+        }
+
+        public void Connect()
+        {
+
+            if (!IsInit)
+            { //Connect
+                //Check IP Textbox
+                IPAddress IPValue;
+                if (IPAddress.TryParse(FeederIp, out IPValue))
+                {
+                    if (/*IPValue.GetAddressBytes()[3] != 0 && */IPValue.GetAddressBytes()[3] != 255)
+                    {
+                        //Valid IP
+
+                        //Check Port
+                        int PortValue = FeederPort;
+
+                        if (PortValue > 0)
+                        {
+                            //Valid Port
+
+                            //Connect
+                            bool flog = objaflex.Connect(IPValue, PortValue);
+                            if (flog)
+                            {
+                                FeederConnectedEvent?.Invoke(Id, null, null);
+                                GeneralRelease();
+                            }
+                            else
+                            {
+                                FeederDisconnectedEvent?.Invoke(Id, null, null);
+                            }
+                            IsInit = true;
+                        }
+
+                    }
+                }
+            }
+            //else
+            //{ //Disconnect
+            //    objaflex.Disconnect();
+            //}
+        }
+
+        public async Task ConnectAsync()
+        {
+
+            await Task.Run(async () =>
+            {
+                //Connect
+                //Check IP Textbox
+                IPAddress IPValue;
+                bool resB = IPAddress.TryParse(FeederIp, out IPValue);
+                int PortValue = FeederPort;
+                try
+                {
+                    if (resB && IPValue.GetAddressBytes()[3] != 255)
+                    {
+                        if (PortValue > 0)
+                        {
+                            bool flog = objaflex.Connect(IPValue, PortValue);
+                            if (flog)
+                            {
+                                FeederConnectedEvent?.Invoke(Id, null, null);
+                                GeneralRelease();
+                            }
+                            else
+                            {
+                                FeederDisconnectedEvent?.Invoke(Id, null, null);
+                            }
+                            IsInit = true;
+                        }
+                    }
+                }
+                catch (Exception)
+                {
+                    IsInit = false;
+                    while (!IsInit)
+                    {
+                        try
+                        {
+                            bool flog = objaflex.Connect(IPValue, PortValue);
+                            if (flog)
+                            {
+                                FeederConnectedEvent?.Invoke(Id, null, null);
+                                GeneralRelease();
+                            }
+                            else
+                            {
+                                FeederDisconnectedEvent?.Invoke(Id, null, null);
+                            }
+                            IsInit = true;
+                        }
+                        catch (Exception)
+                        {
+                            await Task.Delay(1000);
+                        }
+                    }
+                }
+            });
+        }
+
+        /// <summary>
+        /// set release
+        /// </summary>
+        public void GeneralRelease()
+        {
+            if (!objaflex.actual_GeneralRelease)
+            {
+                objaflex.SetGeneralRelease(!objaflex.actual_GeneralRelease);
+            }
+        }
+
+        /// <summary>
+        /// 设置光源亮度
+        /// </summary>
+        /// <param name="brightnessNum">亮度范围0-100</param>
+        public void SetBackLight(double brightnessNum)
+        {
+            try
+            {
+                if (!objaflex.actual_AutoMode) return;
+                if (IsInit)
+                {
+                    GeneralRelease();
+                    if (brightnessNum >= 0 && brightnessNum <= 100)
+                    {
+                        objaflex.SetAuxPowerOut(brightnessNum);
+                    }
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 设置震动强度
+        /// </summary>
+        /// <param name="IntensValue">强度范围0-100</param>
+        public void SetIntensity(double IntensValue)
+        {
+            try
+            {
+                if (!objaflex.actual_AutoMode) return;
+                GeneralRelease();
+                if (IntensValue >= 0 && IntensValue <= 100.0)
+                {
+                    objaflex.SetIntensity(IntensValue);
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 加载配置参数
+        /// </summary>
+        /// <param name="modeNum">范围1-49</param>
+        public void LoadConfiguration(int modeNum)
+        {
+            try
+            {
+                if (!objaflex.actual_AutoMode) return;
+                Byte ConfigNumber;
+                if (Byte.TryParse(modeNum.ToString(), out ConfigNumber))
+                {
+                    if (ConfigNumber > 0 && ConfigNumber < 50)
+                    {
+                        GeneralRelease();
+                        objaflex.LoadConfiguration(ConfigNumber);
+                    }
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 设置震动方向
+        /// </summary>
+        /// <param name="DirectionValue">范围0-360°</param>
+        public void SetDirection(double DirectionValue)
+        {
+            try
+            {
+                if (!objaflex.actual_AutoMode) return;
+                if (DirectionValue >= 0 && DirectionValue <= 360.0)
+                {
+                    GeneralRelease();
+                    objaflex.SetDirection(DirectionValue);
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        public void StartShaking(double backLightIntensity, byte configNum, double degreeNum, double vibrationIntensity, double intervalNum)
+        {
+            FeederParam feed = new FeederParam();
+            feed.backLightIntensity = backLightIntensity;
+            feed.configNum = configNum;
+            feed.degreeNum = degreeNum;
+            feed.vibrationIntensity = vibrationIntensity;
+            feed.intervalNum = intervalNum;
+            stepNum = 1;
+            feedStepTimer = new Timer(StepSequenceHandler, feed, 3, 3);
+        }
+
+        public void StepSequenceHandler(object param)
+        {
+            FeederParam feedParam = (FeederParam)param;
+            switch (stepNum)
+            {
+                case 0:
+                    feedStepTimer.Dispose();
+                    break;
+                case 1: //set general release
+                    if (!objaflex.actual_GeneralRelease) objaflex.SetGeneralRelease(true);
+                    stepNum = 2; //next step
+                    break;
+                case 2: //设置光源                  
+                    objaflex.SetAuxPowerOut(feedParam.backLightIntensity);
+                    stepNum = 3;
+                    break;
+                case 3://确认设置
+                    if (Math.Abs(Math.Round(objaflex.actual_auxPowerOut, 2) - feedParam.backLightIntensity) < 0.1)
+                    {
+                        stepNum = 4; //next step
+                    }
+                    break;
+                case 4://加载震动模式
+                    objaflex.LoadConfiguration(feedParam.configNum); //move = ConfigNumber 2
+
+                    stepNum = 5; //next step
+                    break;
+                case 5: //确认加载成功 
+                    if (objaflex.actual_ConfigNumber == feedParam.configNum)
+                    {
+                        stepNum = 6; //next step
+                    }
+                    break;
+                case 6: //设置震动方向和强度
+                    objaflex.SetDirection(feedParam.degreeNum);
+                    objaflex.SetIntensity(feedParam.vibrationIntensity);
+                    durationNum = durationNum.Subtract(durationNum); //reset Timespan 
+                    stepNum = 7; //next step
+                    break;
+                case 7: //确认设置成功                    
+                    if ((Math.Abs(Math.Round(objaflex.actual_direction, 2) - feedParam.degreeNum) < 0.1) && (Math.Abs(Math.Round(objaflex.actual_intensity, 2) - feedParam.vibrationIntensity) < 0.1))
+                    {
+                        durationNum = durationNum.Add(new TimeSpan(0, 0, 0, 0, 3));
+                    }
+                    if (durationNum.Milliseconds > feedParam.intervalNum)
+                    { //500ms move duration
+                        stepNum = 8; //next step
+                    }
+                    break;
+                case 8: //设置震动强度 0%                    
+                    objaflex.SetIntensity(0);
+                    stepNum = 9; //next step
+                    break;
+                case 9: //确认
+                    if (objaflex.actual_intensity == 0)
+                    {
+                        stepNum = 0; //next step                       
+                    }
+                    break;
+            }
+        }
+
+        public void Dispose()
+        {
+            throw new NotImplementedException();
+        }
+
+        public Task<ushort> GetBackLightFlashTimeAsync()
+        {
+            return Task.FromResult((ushort)0);
+        }
+
+        public int GetDuration(int id)
+        {
+            return 0;
+        }
+
+        public Task<int> GetDurationAsync(int id)
+        {
+            return Task.FromResult((int)0);
+        }
+
+        public Task<int> GetInputTrigger(int i)
+        {
+            return Task.FromResult((int)0);
+        }
+
+        public Task<ushort> GetLightBrightnessAsync()
+        {
+            return Task.FromResult((ushort)objaflex.actual_auxPowerOut);
+        }
+
+        public ushort GetLightTimeout()
+        {
+            return 0;
+        }
+
+        public Task<ushort> GetLightTimeoutAsync()
+        {
+            return Task.FromResult((ushort)0);
+        }
+
+        public bool GetOutputStatus()
+        {
+            return false;
+        }
+
+        public Task<bool> GetOutputStatusAsync()
+        {
+            return Task.FromResult(false);
+        }
+
+        public Task<ushort> GetPlatShakeTimeoutAsync()
+        {
+            return Task.FromResult((ushort)0);
+        }
+
+        public int GetSelectedSequence()
+        {
+            return Convert.ToInt16(objaflex.actual_ConfigNumber);
+        }
+
+        public Task<int> GetSelectedSequenceAsync()
+        {
+            return Task.FromResult((int)Convert.ToInt16(objaflex.actual_ConfigNumber));
+        }
+
+        public int GetSelectedShakeParam()
+        {
+            return 0;
+        }
+
+        public Task<int> GetSelectedShakeParamAsync()
+        {
+            return Task.FromResult(0);
+        }
+
+        public Task<SingleSequenceActionGroup> GetSequenceGroupAsync(int id)
+        {
+            return Task.FromResult<SingleSequenceActionGroup>(null);
+        }
+
+        public SingleActionParam GetShakeGroupValue(int index)
+        {
+            return null;
+        }
+
+        public Task<SingleActionParam> GetShakeGroupValueAsync(int index)
+        {
+            return Task.FromResult<SingleActionParam>(null);
+        }
+
+        public SingleActionParam GetShakeParameters(int selectedShakeMotion)
+        {
+            return null;
+        }
+
+        public Task<SingleActionParam> GetShakeParametersAsync(int selectedShakeMotion)
+        {
+            return Task.FromResult<SingleActionParam>(null);
+        }
+
+        public string GetSingleParamValue(int id)
+        {
+            return "";
+        }
+
+        public Task<string> GetSingleParamValueAsync(int id)
+        {
+            return Task.FromResult("");
+        }
+
+        public Task<ushort> GetUpperFeederShakeTimeoutAsync()
+        {
+            return Task.FromResult((ushort)0);
+        }
+
+        public Task<HopperFeederParam> GetUpperParamAsync(int selectedSequence)
+        {
+            return Task.FromResult<HopperFeederParam>(null);
+        }
+
+        public bool LoadShakeSet(int v)
+        {
+            return false;
+        }
+
+        public Task<bool> LoadShakeSetAsync(int v)
+        {
+            return Task.FromResult(false);
+        }
+
+        public void OpenLight()
+        {
+            try
+            {
+                if (!objaflex.actual_AutoMode) return;
+                double DirectionValue = 100;
+                if (DirectionValue >= 0 && DirectionValue <= 360.0)
+                {
+                    GeneralRelease();
+                    objaflex.SetDirection(DirectionValue);
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        public Task OpenLightAsync()
+        {
+            try
+            {
+                if (!objaflex.actual_AutoMode) return Task.CompletedTask;
+                double DirectionValue = 100;
+                if (DirectionValue >= 0 && DirectionValue <= 360.0)
+                {
+                    GeneralRelease();
+                    objaflex.SetDirection(DirectionValue);
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+            return Task.CompletedTask;
+        }
+
+        public int Output(int id, int? timespan = null)
+        {
+            return 0;
+        }
+
+        public Task<int> OutputAsync(int id, int? timespan = null)
+        {
+            return Task.FromResult((int)0);
+        }
+
+        public bool QueryLightState()
+        {
+            if (objaflex.actual_auxPowerOut > 0)
+                return false;
+            else return true;
+        }
+
+        public Task<bool> QueryLightStateAsync()
+        {
+            if (objaflex.actual_auxPowerOut > 0)
+                return Task.FromResult(false);
+            else return Task.FromResult(true);
+        }
+
+        public void Reset()
+        {
+
+        }
+
+        public Task ResetAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task<int> RunFromCommand(string command, int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToBottomAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToBottomLeftAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToBottomRightAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToFlipAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToInnerHorizonAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToInnerVerticalAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToLeftAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToRightAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToTopAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToTopLeftAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task<int> RunToTopRightAsync(int? timespan = null)
+        {
+            return Task.FromResult<int>(0);
+        }
+
+        public Task SaveAllSetAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SaveGlobalSetAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SaveSequenceAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SaveShakeSetAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        public void SelectShakeParam(int id)
+        {
+
+        }
+
+        public Task SelectShakeParamAsync(int id)
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SetBackLightFlashTimeAsync(ushort backLightFlash)
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SetInputTrigger(int id, int value)
+        {
+            return Task.CompletedTask;
+        }
+
+        public void SetIpAddress(string ip, string subNetMask, int port)
+        {
+
+        }
+
+        public Task SetIpAddressAsync(string ip, string subNetMask, int port)
+        {
+            return Task.CompletedTask;
+        }
+
+        public void SetLightTimeOut(ushort timeout)
+        {
+
+        }
+
+        public Task SetLightTimeOutAsync(ushort timeout)
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SetLightValueAsync(ushort lightValue)
+        {
+            if (lightValue<0 || lightValue>100)
+            {
+                lightValue = 100;
+            }
+            try
+            {
+                objaflex.SetAuxPowerOut(lightValue);
+            }
+            catch (Exception)
+            {
+
+            }
+            
+            return Task.CompletedTask;
+        }
+
+        public Task SetLightValueToBufferAsync(ushort lightValue)
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SetPlatShakeTimeoutAsync(ushort upperFeederShakeTimeout)
+        {
+            return Task.CompletedTask;
+        }
+
+        public void SetSequence(int groupId, int actionId, SingleSequenceAction singleSequenceAction)
+        {
+
+        }
+
+        public Task SetSequenceAsync(int groupId, int actionId, SingleSequenceAction singleSequenceAction)
+        {
+            return Task.CompletedTask;
+        }
+
+        public void SetShakeParameters(int selectedShakeMotion, int id, string value)
+        {
+
+        }
+
+        public void SetShakeParameters(int selectedShakeMotion, string value)
+        {
+
+        }
+
+        public void SetShakeParameters(int selectedShakeMotion, SingleActionParam value)
+        {
+
+        }
+
+        public Task SetShakeParametersAsync(int selectedShakeMotion, int id, string value)
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SetShakeParametersAsync(int selectedShakeMotion, string value)
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SetShakeParametersAsync(int selectedShakeMotion, SingleActionParam value)
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task SetUpperFeederShakeTimeoutAsync(ushort upperFeederShakeTimeout)
+        {
+            return Task.CompletedTask;
+        }
+
+        public int ShakeUp()
+        {
+            return 0;
+        }
+
+        public Task<int> ShakeUpAsync()
+        {
+            return Task.FromResult(0);
+        }
+
+        public Task<int> StartAction(int index, int? timespan = null)
+        {
+            return Task.FromResult(0);
+        }
+
+        public Task<int> StartOneSequenceAsync(int id)
+        {
+            return Task.FromResult(0);
+        }
+
+        public void Stop()
+        {
+            SetIntensity(0);
+        }
+
+        public Task StopAsync()
+        {
+            SetIntensity(0);
+            return Task.CompletedTask;
+        }
+
+        public Task StopOneSequenceAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        public void StopOutput()
+        {
+
+        }
+
+        public Task StopOutputAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task WriteOutputParamAsync(int groupId, HopperFeederParam param)
+        {
+            return Task.CompletedTask;
+        }
+    }
+}

+ 194 - 0
Team.FFFeederService/AutoAdjustmentParameter.cs

@@ -0,0 +1,194 @@
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+using System.Runtime.Remoting.Messaging;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Controls.Primitives;
+using Team.FFFeederService.Enums;
+using Team.FFFeederService.Interfaces;
+using Team.FFFeederService.Models;
+
+namespace Team.FFFeederService
+{
+    /// <summary>
+    /// Feeder自动调整参数
+    /// </summary>
+    public class AutoAdjustmentParameter : IDisposable
+    {
+        /// <summary>
+        /// 动作的编号
+        /// </summary>
+        public int ActionIndex { get; set; }
+
+        // 声明一个委托字段,其签名与A中的GetDataFromA方法匹配
+        private readonly Func<Tuple<bool, float, float>> dataFetchDelegate;
+
+        public FeederModel FeederModel { get; set; }
+
+        private IVoiceCoilMotorFeeder Feeder;
+
+        public VibrationFrequencyDetector detector;
+
+        /// <summary>
+        /// 振动参数改变
+        /// </summary>
+        public event Action<SingleActionParam> OnVibrationParamChanged;
+
+        /// <summary>
+        /// 构造函数
+        /// </summary>
+        /// <param name="actionParam">动作参数</param>
+        /// <param name="rectangle">Feeder盘面的矩形</param>
+        /// <param name="_dataFetchDelegate">回调函数,获取相机拍照后的结果</param>
+        public AutoAdjustmentParameter(IVoiceCoilMotorFeeder feeder,int actionIndex,Func<Tuple<bool, float, float>> _dataFetchDelegate)
+        {
+            Feeder = feeder;
+            ActionIndex= actionIndex;
+            dataFetchDelegate = _dataFetchDelegate;
+            FeederModel = Feeder.FeederModel;
+            int feedermodel = 0;
+            switch (Feeder.FeederModel)
+            {
+                case FeederModel.FF120:
+                    feedermodel = 120;
+                    break;
+                case FeederModel.FF240:
+                    feedermodel = 240;
+                    break;
+                case FeederModel.FF380:
+                    feedermodel = 380;
+                    break;
+                case FeederModel.FF530:
+                    feedermodel = 530;
+                    break;
+                case FeederModel.Unknown:
+                    feedermodel = 380;
+                    break;
+                default:
+                    break;
+            }
+            detector=new VibrationFrequencyDetector();
+            detector.Initialize(feedermodel, ActionIndex);
+            // 订阅事件
+            detector.OnExecuteFeedervibration += data =>
+            {
+                //Feeder振动参数设置并执行动作
+                int action = data.inFedAct;
+                SingleActionParam actionp = new SingleActionParam
+                {
+                    Motor1 = new VoiceMotorParam
+                    {
+                        Amplitude = data.u16VoiMot0,
+                        Frequency = data.u16VoiMot1,
+                        Phase = data.u16VoiMot2,
+                        WaveShape = (WaveShape)data.u16VoiMot3,
+                    },
+                    Motor2 = new VoiceMotorParam
+                    {
+                        Amplitude = data.u16VoiMot4,
+                        Frequency = data.u16VoiMot5,
+                        Phase = data.u16VoiMot6,
+                        WaveShape = (WaveShape)data.u16VoiMot7,
+                    },
+                    Motor3 = new VoiceMotorParam
+                    {
+                        Amplitude = data.u16VoiMot8,
+                        Frequency = data.u16VoiMot9,
+                        Phase = data.u16VoiMotA,
+                        WaveShape = (WaveShape)data.u16VoiMotB,
+                    },
+                    Motor4 = new VoiceMotorParam
+                    {
+                        Amplitude = data.u16VoiMotC,
+                        Frequency = data.u16VoiMotD,
+                        Phase = data.u16VoiMotE,
+                        WaveShape = (WaveShape)data.u16VoiMotF,
+                    },
+                    DurationValue = data.u16DuartTim
+                };
+                OnVibrationParamChanged?.Invoke(actionp);
+                ExecuteFeederVibration(action, actionp);
+            };
+            detector.OnExecutePhoto += () =>
+            {
+                /// 相机拍照获取物料位置
+                return dataFetchDelegate?.Invoke();
+            };
+        }
+
+        public async Task<bool> Execute(int amplitudeMax, int amplitudeMin, int frequencyMax, int frequencyMin,int duration, CancellationToken token,Action<int> callback)
+        {
+            
+            float currentX = 0, currentY=0;
+            float oldX = 0, oldY=0;
+            int counter = 0;
+            int amplitude = amplitudeMin;
+            int frequency = frequencyMin;
+            await Feeder.OpenLightAsync();
+
+
+            detector.OnExecuteResult += status =>
+            {
+                callback?.Invoke(status);
+            };
+            while (!token.IsCancellationRequested)
+            {
+                detector.StartTask();
+                await Task.Delay(100);
+            }
+            detector.Dispose();
+            return false;
+        }
+
+        /// <summary>
+        /// 执行振动
+        /// </summary>
+        /// <param name="action">动作索引</param>
+        /// <returns></returns>
+        public async Task ExecuteAction(int action,int time)
+        {
+            await Feeder.StartAction(action, time);
+        }
+
+        /// <summary>
+        /// 写入震动参数
+        /// </summary>
+        /// <param name="action"></param>
+        /// <param name="actionp"></param>
+        /// <returns></returns>
+        public async Task WriteActionParm(int action, SingleActionParam actionp)
+        {
+            await Feeder.SetShakeParametersAsync(action, actionp);
+        }
+
+        public void ExecuteFeederVibration(int action, SingleActionParam actionp)
+        {
+            Task.Run(async () =>
+            {
+                await WriteActionParm(action, actionp);
+                await ExecuteAction(action, actionp.DurationValue);
+                await Task.Delay(actionp.DurationValue+1000);
+            }).GetAwaiter().GetResult();
+        }
+
+        /// <summary>
+        /// 设置寻频返回值0:停止 1 :启动 2:验证 3:结束
+        /// </summary>
+        /// <param name="state">0:停止 1 :启动 2:验证 3:结束</param>
+        public void SetState(int state)
+        {
+            detector.SetLogicState(state);
+        }
+
+        public void Dispose()
+        {
+            if (detector!=null)
+            {
+                detector.Dispose();
+            }
+        }
+    }
+}

+ 16 - 0
Team.FFFeederService/Enums/ActionType.cs

@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Enums
+{
+    public enum ActionType
+    {
+        None,
+        Shake,
+        Output,
+        DelayTime
+    }
+}

+ 15 - 0
Team.FFFeederService/Enums/DurationMode.cs

@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Enums
+{
+    public enum DurationMode
+    {
+        固定,
+        数量调整,
+        震动比
+    }
+}

+ 59 - 0
Team.FFFeederService/Enums/FeederAction.cs

@@ -0,0 +1,59 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Enums
+{
+    /// <summary>
+    /// Feeder振动动作
+    /// </summary>
+    public enum FeederAction
+    {
+        /// <summary>
+        /// 左下
+        /// </summary>
+        LeftAndBottom,
+        /// <summary>
+        /// 左
+        /// </summary>
+        Left,
+        /// <summary>
+        /// 左上
+        /// </summary>
+        LeftAndTop,
+        /// <summary>
+        /// 散开
+        /// </summary>
+        Flip,
+        /// <summary>
+        /// 上
+        /// </summary>
+        Top,
+        /// <summary>
+        /// 下
+        /// </summary>
+        Bottom,
+        /// <summary>
+        /// 右下
+        /// </summary>
+        RightAndBottom,
+        /// <summary>
+        /// 右
+        /// </summary>
+        Right,
+        /// <summary>
+        /// 右上
+        /// </summary>
+        RightAndTop,
+        /// <summary>
+        /// 垂直方向聚集
+        /// </summary>
+        VerticalAlignment,
+        /// <summary>
+        /// 水平方向聚集
+        /// </summary>
+        HorizontalAlignment
+    }
+}

+ 20 - 0
Team.FFFeederService/Enums/FeederModel.cs

@@ -0,0 +1,20 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Enums
+{
+    /// <summary>
+    /// Feeder型号
+    /// </summary>
+    public enum FeederModel
+    {
+        FF120=0,
+        FF240=1,
+        FF380=2,
+        FF530=3,
+        Unknown=99,
+    }
+}

+ 31 - 0
Team.FFFeederService/Enums/WaveShape.cs

@@ -0,0 +1,31 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Enums
+{
+    /// <summary>
+    /// 电机输出波形
+    /// </summary>
+    public enum WaveShape
+    {
+        /// <summary>
+        /// 不启用电机
+        /// </summary>
+        None,
+        /// <summary>
+        /// 正弦波
+        /// </summary>
+        SignWave,
+        /// <summary>
+        /// 上沿锯齿波
+        /// </summary>
+        SawToothWave,
+        /// <summary>
+        /// 下沿锯齿波
+        /// </summary>
+        TriangleWave
+    }
+}

+ 18 - 0
Team.FFFeederService/FeederBrand.cs

@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService
+{
+    /// <summary>
+    /// Feeder品牌
+    /// </summary>
+    public enum FeederBrand
+    {
+        TEAM = 0,
+        AFAG = 1,
+    }
+}

+ 316 - 0
Team.FFFeederService/FeederIPManage.cs

@@ -0,0 +1,316 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using System.Net;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using Team.FFFeederService.Models;
+using System.Net.Mail;
+using static System.Net.Mime.MediaTypeNames;
+using TouchSocket.Sockets;
+
+namespace Team.FFFeederService
+{
+    public class FeederIPManage
+    {
+        UdpClient udpClient;
+        public FeederIPManage()
+        {
+            udpClient = new UdpClient();
+        }
+
+        /// <summary>
+        /// 获取所有的Feeder
+        /// </summary>
+        /// <returns></returns>
+        public async Task<List<FeederNetworkInterfaceInfo>> Scan()
+        {
+            return await Task.Run(() => {
+                List<FeederNetworkInterfaceInfo> feeders1 = new List<FeederNetworkInterfaceInfo>();
+                try
+                {
+
+                    var netList = GetAllNetworkInterface();
+                    foreach (var item in netList)
+                    {
+                        Bind(item.IPv4Address.ToString());
+                        var feeders = GetFeederList(item);
+                        foreach (var item1 in feeders)
+                        {
+                            feeders1.Add(item1);
+                        }
+                    }
+                }
+                catch (Exception)
+                {
+
+                }
+                return feeders1;
+            });
+        }
+
+        public void Bind(string ip)
+        {
+            // 指定要绑定的本地地址和端口
+            IPAddress localIpAddress = IPAddress.Parse(ip); // 你想要使用的网口的IP地址
+            int localPort = 8000; // 你想要绑定的端口号
+            udpClient.Client.Close();
+            udpClient.Client.Dispose();
+            udpClient = new UdpClient();
+            udpClient.Client.Bind(new IPEndPoint(localIpAddress, localPort));
+        }
+
+        /// <summary>
+        /// 获取所有已连接网口的IP地址
+        /// </summary>
+        /// <returns></returns>
+        public NetworkInterfaceInfo[] GetAllNetworkInterface()
+        {
+            List<NetworkInterfaceInfo> networks = new List<NetworkInterfaceInfo>();
+            // 获取计算机上所有的网络接口
+            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
+
+            // 遍历每个网络接口,并获取其IP地址信息
+            foreach (NetworkInterface networkInterface in networkInterfaces)
+            {
+                // 排除回环接口和虚拟接口等
+                if (networkInterface.OperationalStatus == OperationalStatus.Up &&
+                    networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
+                    networkInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel &&
+                    networkInterface.NetworkInterfaceType != NetworkInterfaceType.Unknown)
+                {
+                    // 获取该网络接口的IP属性集合
+                    IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
+
+                    // 遍历该网络接口的IP地址信息
+                    foreach (UnicastIPAddressInformation ip1 in ipProperties.UnicastAddresses)
+                    {
+                        // 仅输出IPv4地址
+                        if (ip1.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
+                        {
+                            // 输出IPv4地址信息
+                            Console.WriteLine($"网口名称: {networkInterface.Name}");
+                            Console.WriteLine($"IPv4地址: {ip1.Address.ToString()}");
+                            Console.WriteLine($"子网掩码: {ip1.IPv4Mask}");
+                            networks.Add(new NetworkInterfaceInfo { Name = networkInterface.Name, IPv4Address = ip1.Address, IPv4Mask = ip1.IPv4Mask });
+                        }
+                    }
+                }
+            }
+            return networks.ToArray();
+        }
+
+        /// <summary>
+        /// 搜寻Feeder
+        /// </summary>
+        /// <param name="udpClient"></param>
+        /// <returns></returns>
+        public FeederNetworkInterfaceInfo[] GetFeederList(NetworkInterfaceInfo network)
+        {
+            List<FeederNetworkInterfaceInfo> feeders = new List<FeederNetworkInterfaceInfo>();
+            // 设置服务IP(这个IP地址是服务器的IP),设置端口号
+            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1234);
+            //发送信息
+            byte[] data = new byte[1024];
+            string cmd = "{udpscan}";
+            data = Encoding.UTF8.GetBytes(cmd);
+            udpClient.Send(data, data.Length, ip);
+            udpClient.Client.ReceiveTimeout = 500;
+            for (int i = 0; i < 10; i++)
+            {
+                try
+                {
+                    var da = udpClient.Receive(ref ip);
+                    string config = Encoding.UTF8.GetString(da, 0, da.Length).TrimEnd('\n').TrimEnd('\r');
+                    Console.WriteLine(config);
+                    //{ FF0Ver2.6.5 / ip:192.168.31.200:5000 / sub:255.255.255.0 / gw:192.168.31.1 / mac:80:34:28:66:49:6a}
+                    var info1 = AnalysisIP(config);
+                    if (info1 != null)
+                    {
+                        info1.IsAccessible = AreFirstThreeOctetsEqual(IPAddress.Parse(info1.IP), network.IPv4Address);
+                        info1.Network = network;
+                        feeders.Add((FeederNetworkInterfaceInfo)info1);
+                    }
+                    ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1234);
+                }
+                catch (Exception)
+                {
+                    break;
+                }
+            }
+            return feeders.ToArray();
+        }
+
+        /// <summary>
+        /// 解析Feeder的IP等信息
+        /// </summary>
+        /// <param name="input"></param>
+        /// <returns></returns>
+        public FeederNetworkInterfaceInfo AnalysisIP(string input)
+        {
+            // 定义正则表达式模式
+            string pattern = @"{(?<Name>[^V]+)Ver(?<Version>[^\/]+)\/ip:(?<IP>[^:]+):(?<Port>\d+)\/sub:(?<Subnet>[^\/]+)\/gw:(?<Gateway>[^\/]+)\/mac:(?<MAC>[^}]+)}";
+
+            // 进行正则匹配
+            Match match = Regex.Match(input, pattern);
+
+            // 提取匹配的值
+            if (match.Success)
+            {
+                string FF380 = match.Groups["Name"].Value.Trim();
+                string version = match.Groups["Version"].Value.Trim(); ; // 提取版本号
+                string IP = match.Groups["IP"].Value.Trim();
+                string port = match.Groups["Port"].Value.Trim();
+                string subnet = match.Groups["Subnet"].Value.Trim();
+                string gateway = match.Groups["Gateway"].Value.Trim();
+                string MAC = match.Groups["MAC"].Value.Trim();
+                // 输出提取的值
+                Console.WriteLine($"Name: {FF380}");
+                Console.WriteLine($"Version: {version}");
+                Console.WriteLine($"IP: {IP}");
+                Console.WriteLine($"Port: {port}");
+                Console.WriteLine($"子网掩码: {subnet}");
+                Console.WriteLine($"网关: {gateway}");
+                Console.WriteLine($"MAC: {MAC}");
+
+                return new FeederNetworkInterfaceInfo
+                {
+                    FeederType = FF380,
+                    Version = version,
+                    IP = IP,
+                    Port = int.Parse(port),
+                    Subnet = subnet,
+                    Gateway = gateway,
+                    MAC = MAC
+                };
+
+            }
+            else
+            {
+                Console.WriteLine("No match found.");
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// 重置Feeder
+        /// </summary>
+        /// <param name="udpClient"></param>
+        /// <param name="FeederMAC"></param>
+        /// <returns></returns>
+        public bool ResetFeeder(string FeederMAC, NetworkInterfaceInfo network = null)
+        {
+            try
+            {
+                if (network != null)
+                {
+                    Bind(network.IPv4Address.ToString());
+                }
+                // 设置服务IP(这个IP地址是服务器的IP),设置端口号
+                IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1234);
+                //发送信息
+                byte[] data = new byte[1024];
+                string cmd = "{ParReset/mac:" + FeederMAC + "}";
+                data = Encoding.UTF8.GetBytes(cmd);
+                udpClient.Send(data, data.Length, ip);
+                udpClient.Client.ReceiveTimeout = 5000;
+                var da = udpClient.Receive(ref ip);
+                string rev = Encoding.UTF8.GetString(da, 0, da.Length).TrimEnd('\n').TrimEnd('\r');
+                if (string.Equals(rev, cmd))
+                {
+                    return true;
+                }
+                else
+                {
+                    return false;
+                }
+            }
+            catch (Exception)
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// 设置FeederIP
+        /// </summary>
+        /// <param name="FeederMAC"></param>
+        /// <param name="TargetIp"></param>
+        /// <param name="TargetPort"></param>
+        /// <param name="TargetSub"></param>
+        /// <param name="network"></param>
+        /// <returns></returns>
+        public async Task<bool> SetFeederIP(string FeederMAC, string TargetIp, int TargetPort, string TargetSub, NetworkInterfaceInfo network=null)
+        {
+            try
+            {
+                if (network != null)
+                {
+                    Bind(network.IPv4Address.ToString());
+                }
+                
+                // 设置服务IP(这个IP地址是服务器的IP),设置端口号
+                IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1234);
+                //发送信息
+                byte[] data = new byte[1024];
+                string cmd = "{ipset/mac:" + $"{FeederMAC}/ip:{TargetIp}:{TargetPort}/sub:{TargetSub}" + "}";
+                data = Encoding.UTF8.GetBytes(cmd);
+                await udpClient.SendAsync(data, data.Length, ip);
+                udpClient.Client.ReceiveTimeout = 5000;
+                var dataas=await udpClient.ReceiveAsync();
+                var da = dataas.Buffer;
+                
+                //var da = udpClient.Receive(ref ip);
+                string rev = Encoding.UTF8.GetString(da, 0, da.Length).TrimEnd('\n').TrimEnd('\r');
+                if (string.Equals(rev, cmd))
+                {
+                    return true;
+                }
+                else
+                {
+                    return false;
+                }
+            }
+            catch (Exception)
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// 对比两个IP地址是否在同网段
+        /// </summary>
+        /// <param name="ip1"></param>
+        /// <param name="ip2"></param>
+        /// <returns></returns>
+        public bool AreFirstThreeOctetsEqual(IPAddress ip1, IPAddress ip2)
+        {
+            byte[] bytes1 = ip1.GetAddressBytes();
+            byte[] bytes2 = ip2.GetAddressBytes();
+
+            // 比较前三个字节
+            for (int i = 0; i < 3; i++)
+            {
+                if (bytes1[i] != bytes2[i])
+                {
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        public void Disposed()
+        {
+            udpClient.Client.Close();
+            udpClient.Client.Dispose();
+        }
+
+        ~FeederIPManage()
+        {
+            Disposed();
+        }
+    }
+}

+ 161 - 0
Team.FFFeederService/FeederService.cs

@@ -0,0 +1,161 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading.Tasks;
+using Team.FFFeederService.Interfaces;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace Team.FFFeederService
+{
+    public class FeederService : IFeederService
+    {
+        private readonly Dictionary<Guid, IVoiceCoilMotorFeeder> _feederCollection;
+        public FeederService()
+        {
+            _feederCollection = new Dictionary<Guid, IVoiceCoilMotorFeeder>();
+        }
+
+        public bool CreateFeeder(Guid id, string ip, int port,FeederBrand feederBrand)
+        {
+            if (feederBrand== FeederBrand.TEAM)
+            {
+                var tcpClient = new TouchSocket.Sockets.TcpClient();
+                var config = new TouchSocketConfig();
+                config.SetRemoteIPHost(new IPHost(IPAddress.Parse(ip), port));
+                config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r\n"); });       //设置结束符
+                config.ConfigurePlugins(a => { a.UseTcpReconnection(); });       ////如需永远尝试连接,tryCount设置为-1即可。
+                                                                                            //载入配置
+                tcpClient.Setup(config);
+                IVoiceCoilMotorFeeder feeder = new TeamFeeder(tcpClient);
+
+                if (_feederCollection.ContainsKey(id))
+                {
+                    var currentFeeder = _feederCollection[id];
+                    currentFeeder.Dispose();
+                }
+                else
+                {
+                    _feederCollection.Add(id,feeder);
+                }
+                feeder.Id = id;
+                _feederCollection[id].FeederConnectedEvent += FeederService_FeederConnectedEvent;
+                _feederCollection[id].FeederDisconnectedEvent += FeederService_FeederDisconnectedEvent;
+            }
+            else
+            {
+                IVoiceCoilMotorFeeder feeder = new AfagFeeder(id,ip,port);
+                if (_feederCollection.ContainsKey(id))
+                {
+                    var currentFeeder = _feederCollection[id];
+                    currentFeeder.Dispose();
+                }
+                else
+                {
+                    _feederCollection.Add(id, feeder);
+                }
+                _feederCollection[id].FeederConnectedEvent += FeederService_FeederConnectedEvent;
+                _feederCollection[id].FeederDisconnectedEvent += FeederService_FeederDisconnectedEvent;
+            }
+            return true;
+        }
+
+        public Task<bool> CreateFeederAsync(Guid id, string ip, int port, FeederBrand feederBrand)
+        {
+            if(feederBrand == FeederBrand.TEAM)
+            {
+                var tcpClient = new TouchSocket.Sockets.TcpClient();
+                var config = new TouchSocketConfig();
+                config.SetRemoteIPHost(new IPHost(IPAddress.Parse(ip), port));
+                config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r\n"); });       //设置结束符
+                config.ConfigurePlugins(a => { a.UseTcpReconnection(); });       ////如需永远尝试连接,tryCount设置为-1即可。
+                                                                                            //载入配置
+                tcpClient.Setup(config);
+                IVoiceCoilMotorFeeder feeder = new TeamFeeder(tcpClient);
+                if (_feederCollection.ContainsKey(id))
+                {
+                    var currentFeeder = _feederCollection[id];
+                    currentFeeder.Dispose();
+                }
+                else
+                {
+                    _feederCollection.Add(id, feeder);
+                }
+                feeder.Id = id;
+                _feederCollection[id].FeederConnectedEvent += FeederService_FeederConnectedEvent;
+                _feederCollection[id].FeederDisconnectedEvent += FeederService_FeederDisconnectedEvent;
+            }
+            else
+            {
+                IVoiceCoilMotorFeeder feeder = new AfagFeeder(id, ip, port);
+                if (_feederCollection.ContainsKey(id))
+                {
+                    var currentFeeder = _feederCollection[id];
+                    currentFeeder.Dispose();
+                }
+                else
+                {
+                    _feederCollection.Add(id, feeder);
+                }
+                _feederCollection[id].FeederConnectedEvent += FeederService_FeederConnectedEvent;
+                _feederCollection[id].FeederDisconnectedEvent += FeederService_FeederDisconnectedEvent;
+            }
+            return Task.FromResult(true);
+        }
+
+        /// <summary>
+        /// Feeder断开连接时
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void FeederService_FeederDisconnectedEvent(Guid feederId, ITcpClient client, ClosedEventArgs e)
+        {
+            
+        }
+
+        /// <summary>
+        /// Feeder连接上时
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void FeederService_FeederConnectedEvent(Guid feederId, ITcpClient client, ConnectedEventArgs e)
+        {
+            
+        }
+
+        public IVoiceCoilMotorFeeder GetFeeder(Guid id)
+        {
+            return _feederCollection[id];
+        }
+
+        public Task<IVoiceCoilMotorFeeder> GetFeederAsync(Guid id)
+        {
+            return Task.FromResult(_feederCollection[id]);
+        }
+
+        public Task UnRegisterFeederAsync(Guid id)
+        {
+            if (_feederCollection.ContainsKey(id))
+            {
+                var feeder = _feederCollection[id];
+                feeder.Dispose();
+            }
+            return Task.CompletedTask;
+        }
+        public void UnRegisterFeeder(Guid id)
+        {
+            if (_feederCollection.ContainsKey(id))
+            {
+                var feeder = _feederCollection[id];
+                feeder.Dispose();
+            }
+        }
+    }
+}

+ 44 - 0
Team.FFFeederService/Interfaces/IFeeder.cs

@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Team.FFFeederService.Enums;
+using TouchSocket.Sockets;
+
+namespace Team.FFFeederService.Interfaces
+{
+    public interface IFeeder : IDisposable
+    {
+        TcpClient TcpClient { get; }
+        FeederBrand FeederBrand { get; }
+        int FeederPort { get; }
+        string FeederIp { get; }
+        Guid Id { get; set; }
+        FeederModel FeederModel { get; }
+        void Reset();
+        Task ResetAsync();
+        void OpenLight();
+        Task OpenLightAsync();
+        void CloseLight();
+        Task CloseLightAsync();
+        /// <summary>
+        /// 停止
+        /// </summary>
+        /// <returns></returns>
+        Task StopAsync();
+        void Stop();
+        void Connect();
+        Task ConnectAsync();
+        bool IsConnected { get; }
+        bool IsInit { get; }
+        /// <summary>
+        /// Feeder连接上时
+        /// </summary>
+       event Action<Guid, ITcpClient, ConnectedEventArgs> FeederConnectedEvent;
+        /// <summary>
+        /// Feeder断开连接上时
+        /// </summary>
+        event Action<Guid, ITcpClient, ClosedEventArgs> FeederDisconnectedEvent;
+    }
+}

+ 19 - 0
Team.FFFeederService/Interfaces/IFeederService.cs

@@ -0,0 +1,19 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Interfaces
+{
+    public interface IFeederService
+    {
+        Task<bool> CreateFeederAsync(Guid id, string ip, int port, FeederBrand feederBrand);
+        bool CreateFeeder(Guid id, string ip, int port, FeederBrand feederBrand);
+
+        IVoiceCoilMotorFeeder GetFeeder(Guid id);
+        Task<IVoiceCoilMotorFeeder> GetFeederAsync(Guid id);
+        Task UnRegisterFeederAsync(Guid id);
+        void UnRegisterFeeder(Guid id);
+    }
+}

+ 525 - 0
Team.FFFeederService/Interfaces/IVoiceCoilMotor.cs

@@ -0,0 +1,525 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Team.FFFeederService.Models;
+
+namespace Team.FFFeederService.Interfaces
+{
+    public interface IVoiceCoilMotorFeeder : IFeeder
+    {
+        /// <summary>
+        /// 选择使用振动集
+        /// </summary>
+        /// <param name="id"></param>
+        /// <exception cref="FeederResponseException"></exception>
+        void SelectShakeParam(int id);
+
+        /// <summary>
+        /// 选择使用振动集
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        /// <exception cref="FeederResponseException"></exception>
+        Task SelectShakeParamAsync(int id);
+
+        /// <summary>
+        /// 将振动集参数存储至非易失内存中
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        Task SaveShakeSetAsync();
+
+        /// <summary>
+        /// 查询当前选择的振动集
+        /// </summary>
+        /// <returns></returns>
+        int GetSelectedShakeParam();
+
+        /// <summary>
+        /// 查询当前选择的振动集
+        /// </summary>
+        /// <returns></returns>
+        Task<int> GetSelectedShakeParamAsync();
+
+        /// <summary>
+        /// 选择要使用的振动集(1~26)
+        /// </summary>
+        /// <param name="v"></param>
+        /// <returns></returns>
+        bool LoadShakeSet(int v);
+
+        /// <summary>
+        /// 选择要使用的振动集(1~26)
+        /// </summary>
+        /// <param name="v"></param>
+        /// <returns></returns>
+        Task<bool> LoadShakeSetAsync(int v);
+
+        /// <summary>
+        /// 执行平台振动
+        /// </summary>
+        /// <param name="index"></param>
+        /// <param name="timespan"></param>
+        Task<int> StartAction(int index, int? timespan = null);
+
+        /// <summary>
+        /// 向前
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToLeftAsync(int? timespan = null);
+
+        /// <summary>
+        /// 左前
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToBottomLeftAsync(int? timespan = null);
+
+        /// <summary>
+        /// 右前
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToTopLeftAsync(int? timespan = null);
+
+        /// <summary>
+        /// 向左
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToBottomAsync(int? timespan = null);
+
+        /// <summary>
+        /// 向右
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToTopAsync(int? timespan = null);
+
+        /// <summary>
+        /// 向后
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToRightAsync(int? timespan = null);
+
+        /// <summary>
+        /// 左后
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToBottomRightAsync(int? timespan = null);
+
+        /// <summary>
+        /// 右后
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToTopRightAsync(int? timespan = null);
+
+        /// <summary>
+        /// 散开
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToFlipAsync(int? timespan = null);
+
+        /// <summary>
+        /// 横向聚中
+        /// </summary>
+        /// <param name="timespan">持续时间</param>
+        /// <returns></returns>
+        Task<int> RunToInnerVerticalAsync(int? timespan = null);
+
+        /// <summary>
+        /// 纵向聚中
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunToInnerHorizonAsync(int? timespan = null);
+
+        /// <summary>
+        /// 读一个振动动作值
+        /// </summary>
+        /// <param name="v"></param>
+        /// <returns></returns>
+        SingleActionParam GetShakeGroupValue(int index);
+
+        /// <summary>
+        /// 读一个振动动作值
+        /// </summary>
+        /// <param name="index"></param>
+        /// <returns></returns>
+        Task<SingleActionParam> GetShakeGroupValueAsync(int index);
+
+        /// <summary>
+        /// 获取单个动作持续时间
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        int GetDuration(int id);
+
+        /// <summary>
+        /// 获取单个动作持续时间
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        Task<int> GetDurationAsync(int id);
+
+        /// <summary>
+        /// 写入振动单个参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="id"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        Task SetShakeParametersAsync(int selectedShakeMotion, int id, string value);
+
+        /// <summary>
+        /// 写入振动单个参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="id"></param>
+        /// <param name="value"></param>
+        void SetShakeParameters(int selectedShakeMotion, int id, string value);
+
+
+        /// <summary>
+        /// 写入平台振动完成参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        Task SetShakeParametersAsync(int selectedShakeMotion, string value);
+
+        /// <summary>
+        /// 写入平台振动完成参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="value"></param>
+        void SetShakeParameters(int selectedShakeMotion, string value);
+
+        /// <summary>
+        /// 写入完成的平台振动参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="value"></param>
+        void SetShakeParameters(int selectedShakeMotion, SingleActionParam value);
+
+        /// <summary>
+        /// 写入完成的平台振动参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        Task SetShakeParametersAsync(int selectedShakeMotion, SingleActionParam value);
+
+        /// <summary>
+        /// 获取完整的平台振动参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <returns></returns>
+        SingleActionParam GetShakeParameters(int selectedShakeMotion);
+
+        /// <summary>
+        /// 获取完整的平台振动参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <returns></returns>
+        Task<SingleActionParam> GetShakeParametersAsync(int selectedShakeMotion);
+
+        /// <summary>
+        /// 获取平台震动超时时间
+        /// </summary>
+        /// <returns></returns>
+        Task<ushort> GetPlatShakeTimeoutAsync();
+
+        /// <summary>
+        /// 设置平台震动超时时间
+        /// </summary>
+        /// <param name="upperFeederShakeTimeout"></param>
+        /// <returns></returns>
+        Task SetPlatShakeTimeoutAsync(ushort upperFeederShakeTimeout);
+
+        /// <summary>
+        /// 执行料斗供料
+        /// </summary>
+        /// <returns></returns>
+        Task<int> ShakeUpAsync();
+
+        /// <summary>
+        /// 执行供料
+        /// </summary>
+        /// <returns></returns>
+        int ShakeUp();
+
+        /// <summary>
+        /// 停止料斗振动
+        /// </summary>
+        /// <returns></returns>
+        Task StopOutputAsync();
+
+        /// <summary>
+        /// 停止料斗振动
+        /// </summary>
+        void StopOutput();
+
+        /// <summary>
+        /// 获取料斗参数
+        /// </summary>
+        /// <param name="selectedSequence"></param>
+        /// <returns></returns>
+        Task<HopperFeederParam> GetUpperParamAsync(int selectedSequence);
+
+        /// <summary>
+        /// 写入输出参数
+        /// </summary>
+        /// <param name="groupId"></param>
+        /// <param name="param"></param>
+        /// <returns></returns>
+        Task WriteOutputParamAsync(int groupId, HopperFeederParam param);
+
+        /// <summary>
+        /// 获取料斗震动超时时间
+        /// </summary>
+        /// <returns></returns>
+        Task<ushort> GetUpperFeederShakeTimeoutAsync();
+
+        /// <summary>
+        /// 设置料斗震动超时时间
+        /// </summary>
+        /// <param name="upperFeederShakeTimeout"></param>
+        /// <returns></returns>
+        Task SetUpperFeederShakeTimeoutAsync(ushort upperFeederShakeTimeout);
+
+        /// <summary>
+        /// 执行料斗动作
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        Task<int> OutputAsync(int id, int? timespan = null);
+
+        /// <summary>
+        /// 执行料斗动作
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        int Output(int id, int? timespan = null);
+
+        /// <summary>
+        /// /获取取料斗动作状态
+        /// </summary>
+        /// <returns></returns>
+        bool GetOutputStatus();
+
+        /// <summary>
+        /// /获取取料斗动作状态
+        /// </summary>
+        /// <returns></returns>
+        Task<bool> GetOutputStatusAsync();
+
+        /// <summary>
+        /// 停止序列
+        /// </summary>
+        /// <returns></returns>
+        Task StopOneSequenceAsync();
+
+        /// <summary>
+        /// 执行一个序列
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        Task<int> StartOneSequenceAsync(int id);
+
+        /// <summary>
+        /// 获取单个序列集
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        Task<SingleSequenceActionGroup> GetSequenceGroupAsync(int id);
+
+        /// <summary>
+        /// 写入序列参数
+        /// </summary>
+        /// <param name="groupId"></param>
+        /// <param name="singleSequenceAction"></param>
+        void SetSequence(int groupId, int actionId, SingleSequenceAction singleSequenceAction);
+
+        /// <summary>
+        /// 写入序列参数
+        /// </summary>
+        /// <param name="groupId"></param>
+        /// <param name="actionId"></param>
+        /// <param name="singleSequenceAction"></param>
+        /// <returns></returns>
+        Task SetSequenceAsync(int groupId, int actionId, SingleSequenceAction singleSequenceAction);
+
+        /// <summary>
+        /// 将序列参数存储至非易失内存中
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        Task SaveSequenceAsync();
+
+        /// <summary>
+        /// 查询当前选择的序列
+        /// </summary>
+        /// <returns></returns>
+        int GetSelectedSequence();
+
+        /// <summary>
+        /// 查询当前选择的序列
+        /// </summary>
+        /// <returns></returns>
+        Task<int> GetSelectedSequenceAsync();
+
+        /// <summary>
+        /// 设置背光打开超时时间
+        /// </summary>
+        /// <param name="timeout"></param>
+        void SetLightTimeOut(ushort timeout);
+
+        /// <summary>
+        /// 设置背光打开超时时间
+        /// </summary>
+        /// <param name="timeout"></param>
+        /// <returns></returns>
+        Task SetLightTimeOutAsync(ushort timeout);
+
+        /// <summary>
+        /// 获取背光打开超时时间
+        /// </summary>
+        /// <returns></returns>
+        ushort GetLightTimeout();
+
+        /// <summary>
+        /// 获取背光打开超时时间
+        /// </summary>
+        /// <returns></returns>
+        Task<ushort> GetLightTimeoutAsync();
+
+        /// <summary>
+        /// 设置背光亮度
+        /// </summary>
+        /// <param name="lightValue"></param>
+        /// <returns></returns>
+        Task SetLightValueAsync(ushort lightValue);
+
+        /// <summary>
+        /// 设置背光亮度
+        /// </summary>
+        /// <param name="lightValue"></param>
+        /// <returns></returns>
+        Task SetLightValueToBufferAsync(ushort lightValue);
+
+        /// <summary>
+        /// 设置背光闪烁时间
+        /// </summary>
+        /// <param name="backLightFlash"></param>
+        /// <returns></returns>
+        Task SetBackLightFlashTimeAsync(ushort backLightFlash);
+
+        /// <summary>
+        /// 获取背光状态
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        bool QueryLightState();
+
+        /// <summary>
+        /// 获取背光状态
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        Task<bool> QueryLightStateAsync();
+
+        /// <summary>
+        /// 获取背光亮度
+        /// </summary>
+        /// <returns></returns>
+        Task<ushort> GetLightBrightnessAsync();
+
+        /// <summary>
+        /// 获取背光闪烁时间
+        /// </summary>
+        /// <returns></returns>
+        Task<ushort> GetBackLightFlashTimeAsync();
+
+
+        /// <summary>
+        /// 执行命令
+        /// </summary>
+        /// <param name="command"></param>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        Task<int> RunFromCommand(string command, int? timespan = null);
+
+        /// <summary>
+        /// 读单个参数值
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        string GetSingleParamValue(int id);
+
+        /// <summary>
+        /// 读单个参数值
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        Task<string> GetSingleParamValueAsync(int id);
+
+        /// <summary>
+        /// 设置IP地址
+        /// </summary>
+        /// <param name="ip"></param>
+        /// <param name="subNetMask"></param>
+        /// <param name="port"></param>
+        /// <returns></returns>
+        Task SetIpAddressAsync(string ip, string subNetMask, int port);
+
+        /// <summary>
+        /// 设置IP地址
+        /// </summary>
+        /// <param name="ip"></param>
+        /// <param name="subNetMask"></param>
+        /// <param name="port"></param>
+        void SetIpAddress(string ip, string subNetMask, int port);
+
+        /// <summary>
+        /// 获取输入触发参数
+        /// </summary>
+        /// <param name="i"></param>
+        /// <returns></returns>
+        /// <exception cref="IndexOutOfRangeException"></exception>
+        Task<int> GetInputTrigger(int i);
+
+        /// <summary>
+        /// 设置输入触发参数
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        /// <exception cref="IndexOutOfRangeException"></exception>
+        Task SetInputTrigger(int id, int value);
+
+        /// <summary>
+        /// 将所有参数存储至非易失内存中
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        Task SaveAllSetAsync();
+
+        /// <summary>
+        /// 将全局参数存储至非易失内存中
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        Task SaveGlobalSetAsync();
+    }
+}

+ 79 - 0
Team.FFFeederService/Models/ActionParamcAutoFindParam.cs

@@ -0,0 +1,79 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TouchSocket.Core;
+
+namespace Team.FFFeederService.Models
+{
+    public class ActionParamcAutoFindParam
+    {
+        public int ActionIndex {  get; set; }
+
+        public string ActionName { get;private set; }
+
+        /// <summary>
+        /// X轴参数值
+        /// </summary>
+        public ActionAxisParamcs X_Axis {  get; set; }
+
+        /// <summary>
+        /// Y轴参数值
+        /// </summary>
+        public ActionAxisParamcs Y_Axis { get; set; }
+
+        /// <summary>
+        /// 调整成功结束时的阈值
+        /// </summary>
+        public int SuccedEndThreshold { get; set; }
+
+        /// <summary>
+        /// 调整递增的最大阈值
+        /// </summary>
+        public int StepMaxValue { get;set; }
+
+        /// <summary>
+        /// 重新调整的开始阈值
+        /// </summary>
+        public int RestartValue {  get; set; }
+
+        /// <summary>
+        /// 失败递减阈值
+        /// </summary>
+        public int FailStepValue {  get; set; }
+
+        /// <summary>
+        /// 成功递增阈值
+        /// </summary>
+        public int SuccedStepValue {  get; set; }
+
+        /// <summary>
+        /// 振幅递增单位值
+        /// </summary>
+        public int AmpStepValue {  get; set; }
+
+        /// <summary>
+        /// 频率递增单位值
+        /// </summary>
+        public int FreStepValue {  get; set; }
+
+        /// <summary>
+        /// 振幅加速递增单位值
+        /// </summary>
+        public int AmpStepValue2 {  get; set; }
+
+        /// <summary>
+        /// 频率加速递增单位值
+        /// </summary>
+        public int FreStepValue2 { get; set; }
+
+        public ActionParamcAutoFindParam(int actionIndex)
+        {
+            ActionIndex = actionIndex;
+            ActionName = ((char)('A' + ActionIndex)).ToString();
+            X_Axis = new ActionAxisParamcs("X Axis");
+            Y_Axis = new ActionAxisParamcs("Y Axis");
+        }
+    }
+}

+ 60 - 0
Team.FFFeederService/Models/ActionParamcs.cs

@@ -0,0 +1,60 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// 自动寻频时,单个轴方向的判别参数
+    /// </summary>
+    public class ActionAxisParamcs
+    {
+        /// <summary>
+        /// 轴名称
+        /// </summary>
+        public string Name {  get; set; }
+
+        /// <summary>
+        /// 正方向A极参数
+        /// </summary>
+        public float PositClassAThr {  get; set; }
+
+        /// <summary>
+        /// 正方向B极参数
+        /// </summary>
+        public float PositClassBThr {  get; set; }
+
+        /// <summary>
+        /// 负方向A极参数
+        /// </summary>
+        public float NegatClassAThr { get; set; }
+
+        /// <summary>
+        /// 负方向B极参数
+        /// </summary>
+        public float NegatClassBThr { get; set; }
+
+        /// <summary>
+        /// 越线参数
+        /// </summary>
+        public float ExceLimitThr {  get; set; }
+
+        /// <summary>
+        /// Feeder盘面A区域界限
+        /// </summary>
+        public float AreaBound_A { get; set; }
+
+
+        /// <summary>
+        /// Feeder盘面B区域界限
+        /// </summary>
+        public float AreaBound_B { get; set; }
+
+        public ActionAxisParamcs(string name)
+        {
+            Name = name;
+        }
+    }
+}

+ 30 - 0
Team.FFFeederService/Models/AutoFindParamModel.cs

@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Team.FFFeederService.Enums;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// 自动寻频参数模型
+    /// </summary>
+    public class AutoFindParamModel
+    {
+        /// <summary>
+        /// Feeder型号
+        /// </summary>
+        public FeederModel FeederModel { get; set; }
+
+        /// <summary>
+        /// 所有动作的自动寻频参数
+        /// </summary>
+        public List<AutoAdjustmentParameter> AllActions { get; set; }=new List<AutoAdjustmentParameter>();
+
+        public AutoFindParamModel() 
+        { 
+            
+        }
+    }
+}

+ 26 - 0
Team.FFFeederService/Models/FeederActionParam.cs

@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Team.FFFeederService.Enums;
+
+namespace Team.FFFeederService.Models
+{
+    public class FeederActionParam
+    {
+        public Guid Id { get; set; }
+        /// <summary>
+        /// 频率
+        /// </summary>
+        public ushort Frequency { get; set; }
+        /// <summary>
+        /// 振幅
+        /// </summary>
+        public ushort Amplitude { get; set; }
+        /// <summary>
+        /// 动作
+        /// </summary>
+        public FeederAction Name { get; set; }
+    }
+}

+ 24 - 0
Team.FFFeederService/Models/FeederNetworkInterface.cs

@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// Feeder扫描结果集合
+    /// </summary>
+    public class FeederNetworkInterface
+    {
+        /// <summary>
+        /// 网卡接口信息
+        /// </summary>
+        public NetworkInterfaceInfo Network {  get; set; }
+
+        /// <summary>
+        /// 单个网卡对应的Feeder集合
+        /// </summary>
+        public List<FeederNetworkInterfaceInfo> Feeders {  get; set; }
+    }
+}

+ 168 - 0
Team.FFFeederService/Models/FeederNetworkInterfaceInfo.cs

@@ -0,0 +1,168 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// Feeder地址信息
+    /// </summary>
+    public class FeederNetworkInterfaceInfo : INotifyPropertyChanged
+    {
+        /// <summary>
+        /// 名称
+        /// </summary>
+        public string FeederType { get; set; }
+        /// <summary>
+        /// 固件版本
+        /// </summary>
+        public string Version { get; set; }
+        /// <summary>
+        /// IP
+        /// </summary>
+        public string IP { get; set; }
+        /// <summary>
+        /// 端口
+        /// </summary>
+        public int Port { get; set; }
+        /// <summary>
+        /// 掩码
+        /// </summary>
+        public string Subnet { get; set; }
+        /// <summary>
+        /// 网关
+        /// </summary>
+        public string Gateway { get; set; }
+        /// <summary>
+        /// MAC
+        /// </summary>
+        public string MAC { get; set; }
+
+        private bool _IsAccessible;
+
+        /// <summary>
+        /// 可到达的
+        /// </summary>
+        public bool IsAccessible
+        {
+            get { return _IsAccessible; }
+            set { SetProperty(ref _IsAccessible,value); }
+        }
+
+        /// <summary>
+        /// 网卡信息
+        /// </summary>
+        public NetworkInterfaceInfo Network { get; set; }
+
+        //
+        // 摘要:
+        //     Occurs when a property value changes.
+        public event PropertyChangedEventHandler PropertyChanged;
+
+        //
+        // 摘要:
+        //     Checks if a property already matches a desired value. Sets the property and notifies
+        //     listeners only when necessary.
+        //
+        // 参数:
+        //   storage:
+        //     Reference to a property with both getter and setter.
+        //
+        //   value:
+        //     Desired value for the property.
+        //
+        //   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.
+        //
+        //
+        // 类型参数:
+        //   T:
+        //     Type of the property.
+        //
+        // 返回结果:
+        //     True if the value was changed, false if the existing value matched the desired
+        //     value.
+        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;
+        }
+
+        //
+        // 摘要:
+        //     Checks if a property already matches a desired value. Sets the property and notifies
+        //     listeners only when necessary.
+        //
+        // 参数:
+        //   storage:
+        //     Reference to a property with both getter and setter.
+        //
+        //   value:
+        //     Desired value for the property.
+        //
+        //   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.
+        //
+        //
+        //   onChanged:
+        //     Action that is called after the property value has been changed.
+        //
+        // 类型参数:
+        //   T:
+        //     Type of the property.
+        //
+        // 返回结果:
+        //     True if the value was changed, false if the existing value matched the desired
+        //     value.
+        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;
+        }
+
+        //
+        // 摘要:
+        //     Raises this object's PropertyChanged event.
+        //
+        // 参数:
+        //   propertyName:
+        //     Name of the property used to notify listeners. This value is optional and can
+        //     be provided automatically when invoked from compilers that support System.Runtime.CompilerServices.CallerMemberNameAttribute.
+        protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
+        {
+            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
+        }
+
+        //
+        // 摘要:
+        //     Raises this object's PropertyChanged event.
+        //
+        // 参数:
+        //   args:
+        //     The PropertyChangedEventArgs
+        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
+        {
+            this.PropertyChanged?.Invoke(this, args);
+        }
+    }
+}

+ 169 - 0
Team.FFFeederService/Models/HopperFeederParam.cs

@@ -0,0 +1,169 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// 料斗参数
+    /// </summary>
+    public class HopperFeederParam: INotifyPropertyChanged
+    {
+        private bool _HopperDigitalOutput1;
+        /// <summary>
+        /// 数字量输出1
+        /// </summary>
+        public bool HopperDigitalOutput1
+        {
+            get { return _HopperDigitalOutput1; }
+            set { SetProperty(ref _HopperDigitalOutput1,value); }
+        }
+
+        private int _HopperAnalogOutput1;
+        /// <summary>
+        /// 模拟量输出11
+        /// </summary>
+        public int HopperAnalogOutput1
+        {
+            get { return _HopperAnalogOutput1; }
+            set { SetProperty(ref _HopperAnalogOutput1, value); }
+        }
+
+        private bool _HopperDigitalOutput2;
+        /// <summary>
+        /// 数字量输出2
+        /// </summary>
+        public bool HopperDigitalOutput2
+        {
+            get { return _HopperDigitalOutput2; }
+            set { SetProperty(ref _HopperDigitalOutput2, value); }
+        }
+
+        private int _HopperAnalogOutput2;
+        /// <summary>
+        /// 模拟量输出2
+        /// </summary>
+        public int HopperAnalogOutput2
+        {
+            get { return _HopperAnalogOutput2; }
+            set { SetProperty(ref _HopperAnalogOutput2, value); }
+        }
+
+        private int _HopperVibrationAmpl;
+        /// <summary>
+        /// 料斗振动振幅
+        /// </summary>
+        public int HopperVibrationAmpl
+        {
+            get { return _HopperVibrationAmpl; }
+            set { SetProperty(ref _HopperVibrationAmpl, value); }
+        }
+
+        private int _HopperVibrationFreq;
+        /// <summary>
+        /// 料斗振动频率
+        /// </summary>
+        public int HopperVibrationFreq
+        {
+            get { return _HopperVibrationFreq; }
+            set { SetProperty(ref _HopperVibrationFreq, value); }
+        }
+
+        private int _HopperVibrationWaveform;
+        /// <summary>
+        /// 料斗振动波形
+        /// </summary>
+        public int HopperVibrationWaveform
+        {
+            get { return _HopperVibrationWaveform; }
+            set { SetProperty(ref _HopperVibrationWaveform, value); }
+        }
+
+        private int _HopperDuration;
+        /// <summary>
+        /// 振动持续时间
+        /// </summary>
+        public int HopperDuration
+        {
+            get { return _HopperDuration; }
+            set { SetProperty(ref _HopperDuration, value); }
+        }
+
+    #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);
+    }
+    #endregion
+}
+}

+ 29 - 0
Team.FFFeederService/Models/NetworkInterfaceInfo.cs

@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// 网卡接口信息
+    /// </summary>
+    public class NetworkInterfaceInfo 
+    {
+        /// <summary>
+        /// 网口的名称
+        /// </summary>
+        public string Name { get; set; }
+        /// <summary>
+        /// IP地址
+        /// </summary>
+        public IPAddress IPv4Address { get; set; }
+        /// <summary>
+        /// 子网掩码
+        /// </summary>
+        public IPAddress IPv4Mask { get; set; }
+
+    }
+}

+ 131 - 0
Team.FFFeederService/Models/SingleActionParam.cs

@@ -0,0 +1,131 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// 单个平台振动动作参数
+    /// </summary>
+    public class SingleActionParam : INotifyPropertyChanged
+    {
+        private VoiceMotorParam _Motor1;
+
+        public VoiceMotorParam Motor1
+        {
+            get { return _Motor1; }
+            set { SetProperty(ref _Motor1, value); }
+        }
+
+        private VoiceMotorParam _Motor2;
+
+        public VoiceMotorParam Motor2
+        {
+            get { return _Motor2; }
+            set { SetProperty(ref _Motor2, value); }
+        }
+
+        private VoiceMotorParam _Motor3;
+
+        public VoiceMotorParam Motor3
+        {
+            get { return _Motor3; }
+            set { SetProperty(ref _Motor3, value); }
+        }
+
+        private VoiceMotorParam _Motor4;
+
+        public VoiceMotorParam Motor4
+        {
+            get { return _Motor4; }
+            set { SetProperty(ref _Motor4, value); }
+        }
+
+        private int _DurationValue;
+        /// <summary>
+        /// 持续时长
+        /// </summary>
+        public int DurationValue
+        {
+            get { return _DurationValue; }
+            set { SetProperty(ref _DurationValue, value); }
+        }
+
+        #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);
+        }
+        #endregion
+    }
+}

+ 156 - 0
Team.FFFeederService/Models/SingleSequenceAction.cs

@@ -0,0 +1,156 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+using Team.FFFeederService.Enums;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// 单个序列动作
+    /// </summary>
+    public class SingleSequenceAction : INotifyPropertyChanged
+    {
+        private ActionType _Type;
+        /// <summary>
+        /// 动作
+        /// </summary>
+        public ActionType Type
+        {
+            get { return _Type; }
+            set { SetProperty(ref _Type,value); }
+        }
+
+        private int _ShakeId;
+        /// <summary>
+        /// 程序
+        /// </summary>
+        public int ShakeId
+        {
+            get { return _ShakeId; }
+            set { SetProperty(ref _ShakeId, value); }
+        }
+        private DurationMode _DurationMode;
+        /// <summary>
+        /// 持续模式
+        /// </summary>
+        public DurationMode DurationMode
+        {
+            get { return _DurationMode; }
+            set {
+                if (value == DurationMode.震动比)
+                {
+                    DurationValue = DurationValue > 100 ? 100 : DurationValue;
+                    Format = "{}{0:N0} ms";
+                    Max = 30000;
+                }
+                else
+                {
+                    Format = "{}{0:N0} %";
+                    Max = 100;
+                }
+                SetProperty(ref _DurationMode, value);
+            }
+        }
+        private int _DurationValue;
+        /// <summary>
+        /// 持续时长
+        /// </summary>
+        public int DurationValue
+        {
+            get { return _DurationValue; }
+            set { SetProperty(ref _DurationValue, value); }
+        }
+
+        private string _Format;
+
+        public string Format
+        {
+            get { return _Format; }
+            set { SetProperty(ref _Format, value); }
+        }
+
+        private int _Max;
+
+        public int Max
+        {
+            get { return _Max; }
+            set { SetProperty(ref _Max, value); }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 109 - 0
Team.FFFeederService/Models/SingleSequenceActionGroup.cs

@@ -0,0 +1,109 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// 一个序列集
+    /// </summary>
+    public class SingleSequenceActionGroup : INotifyPropertyChanged
+    {
+        private ObservableCollection<SingleSequenceAction> _SingleSequenceActions;
+
+        public ObservableCollection<SingleSequenceAction> SingleSequenceActions
+        {
+            get { return _SingleSequenceActions; }
+            set { SetProperty(ref _SingleSequenceActions,value); }
+        }
+
+        private int _PartCntMax;
+
+        /// <summary>
+        /// 震动平台零件极限值
+        /// </summary>
+        public int PartCntMax
+        {
+            get { return _PartCntMax; }
+            set { SetProperty(ref _PartCntMax, value); }
+        }
+
+        #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);
+        }
+        #endregion
+    }
+}

+ 134 - 0
Team.FFFeederService/Models/VoiceMotorParam.cs

@@ -0,0 +1,134 @@
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+using Team.FFFeederService.Enums;
+
+namespace Team.FFFeederService.Models
+{
+    /// <summary>
+    /// 单个电机参数
+    /// </summary>
+    public class VoiceMotorParam:INotifyPropertyChanged
+    {
+        private ushort _Amplitude;
+        /// <summary>
+        /// 振幅(0-100%)
+        /// </summary>
+        public ushort Amplitude
+        {
+            get { return _Amplitude; }
+            set { SetProperty(ref _Amplitude,value); }
+        }
+
+        private ushort _Frequency;
+        /// <summary>
+        /// 频率(0-250HZ)
+        /// </summary>
+        public ushort Frequency
+        {
+            get { return _Frequency; }
+            set { SetProperty(ref _Frequency, value); }
+        }
+        private ushort _Phase;
+        /// <summary>
+        /// 相位(0-359deg)
+        /// </summary>
+        public ushort Phase
+        {
+            get { return _Phase; }
+            set { SetProperty(ref _Phase, value); }
+        }
+        private WaveShape _WaveShape;
+        /// <summary>
+        /// 波形
+        /// </summary>
+        public WaveShape WaveShape
+        {
+            get { return _WaveShape; }
+            set { SetProperty(ref _WaveShape, value); }
+        }
+
+        #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);
+        }
+        #endregion
+
+        public VoiceMotorParam Clone()
+        {
+            return JsonConvert.DeserializeObject<VoiceMotorParam>(JsonConvert.SerializeObject(this));
+        }
+    }
+}

+ 36 - 0
Team.FFFeederService/Properties/AssemblyInfo.cs

@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 有关程序集的一般信息由以下
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+[assembly: AssemblyTitle("Team.FFFeederService")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("Team.FFFeederService")]
+[assembly: AssemblyCopyright("Copyright ©  2024")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 会使此程序集中的类型
+//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
+//请将此类型的 ComVisible 特性设置为 true。
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+[assembly: Guid("26da3704-77d7-46a7-8651-684878dac898")]
+
+// 程序集的版本信息由下列四个值组成: 
+//
+//      主版本
+//      次版本
+//      生成号
+//      修订号
+//
+//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
+//通过使用 "*",如下所示:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

BIN
Team.FFFeederService/Resources/AutoParaADJ.dll


+ 168 - 0
Team.FFFeederService/TCPCommunicationClass.cs

@@ -0,0 +1,168 @@
+/*********************************************************************
+ *
+ *	Afag Telnet C# Integration Sample Header
+ *
+ *********************************************************************
+ * FileName:        TCPCommunicationClass.cs
+ * Dependencies:    aflex_CSharp_Integration_Sample
+ * Company:         ima-tec GmbH
+ *
+ * Software License Agreement
+ *
+ *
+ * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
+ * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
+ * LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
+ * AFAG BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
+ * PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
+ * BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
+ * THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
+ * SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
+ * (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
+ *
+ *
+ ********************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading.Tasks;
+//using TouchSocket.Core;
+//using TouchSocket.Sockets;
+
+namespace aflex_CSharp_Integration_Sample 
+{
+    class TCPCommunicationClass 
+    {
+        public TcpClient objTCPClient = null;
+        private byte[] byteReceiveBuffer = new byte[256];
+        private bool boolTXEnable = false;
+
+
+        public delegate void ReadResultDelegate(string Result);
+        //Events
+        public event ReadResultDelegate ResultReceived; //event of valid recieve package
+        public event EventHandler ConnectionAbort; 
+
+
+        public TCPCommunicationClass() 
+        {
+        }
+
+
+        public bool Connect(IPAddress IPAddress, int Port) { //connect to the Telnet server
+            bool Successful = false;
+            if (this.objTCPClient != null) {
+                this.objTCPClient.Close(); //if there is already a connection, close it
+            }
+            this.objTCPClient = new TcpClient();
+
+            try { 
+                this.objTCPClient.Connect(IPAddress, Port);
+                this.objTCPClient.Client.BeginReceive(byteReceiveBuffer, 0, 256, SocketFlags.None, new AsyncCallback(asyncResultRead), null);
+                Successful = true;
+                this.boolTXEnable = true;
+            } catch {
+            }
+            return Successful;
+        }
+
+        public void Disconnect() { //disconnect from server
+            this.objTCPClient.Close();
+        }
+
+        private void asyncResultRead(IAsyncResult Result) { // here we read out an asynchronously received package
+            try {
+                if (Result.IsCompleted) {
+                    this.objTCPClient.Client.EndReceive(Result);
+                    string returnString = "";
+                    int y = 0;
+                    for (int i = 0; i < byteReceiveBuffer.Length - 2; i++) {
+                        if (i < 250 && Convert.ToChar(byteReceiveBuffer[i]) == 'H' && Convert.ToChar(byteReceiveBuffer[i + 1]) == 'B' && Convert.ToChar(byteReceiveBuffer[i + 2]) == 'T') {
+                            returnString = String.Empty;
+                            for (int x = i; x < i + 5; x++) {
+                                if (byteReceiveBuffer[x] != 0) {
+                                    returnString += (Convert.ToChar(byteReceiveBuffer[x]).ToString());
+                                    y = x;
+                                    byteReceiveBuffer[x] = 0;
+                                }
+                            }
+                            if (this.ResultReceived != null) {
+                                this.ResultReceived(returnString);
+                            }
+                        }
+                        if (byteReceiveBuffer[i] == 13 && byteReceiveBuffer[i + 1] == 10) {
+                            returnString = String.Empty;
+                            for (int x = y; x < i; x++) {
+                                if (byteReceiveBuffer[x] != 0) {
+                                    returnString += (Convert.ToChar(byteReceiveBuffer[x]).ToString());
+                                    y = x;
+                                    byteReceiveBuffer[x] = 0;
+                                }
+                            }
+                            if (this.ResultReceived != null) {
+                                this.ResultReceived(returnString);
+                            }
+                        }
+                    }
+
+                    //reset buffer
+                    byteReceiveBuffer = new byte[256];
+                    this.objTCPClient.Client.BeginReceive(byteReceiveBuffer, 0, 256, SocketFlags.None, new AsyncCallback(asyncResultRead), null);
+                }
+            } catch {
+                this.objTCPClient.Close();
+            }
+        }
+
+        /// <summary>
+        /// Send a command to the Host
+        /// </summary>
+        /// <param name="Command">the command to transmit</param>
+        /// <returns>transmit sucessfull = true</returns>
+        public bool SendCommand(string Packet) {
+            bool Successfull = false;
+            if (this.boolTXEnable && this.Connected) {
+                byte[] byteTXBuffer; 
+                byteTXBuffer = Encoding.ASCII.GetBytes(Packet + "\r\n");
+         
+                try {
+                    this.objTCPClient.Client.Send(byteTXBuffer);
+                } catch {
+                    if (this.ConnectionAbort != null) {
+                        this.ConnectionAbort(this, new EventArgs());
+                    }
+                }
+                Successfull = true;
+            }
+            if (this.Connected == false) {
+                if (this.ConnectionAbort != null) {
+                    this.ConnectionAbort(this, new EventArgs());
+                }
+            }
+            return Successfull;
+        }
+
+
+        #region SET / GET
+        /// <summary>
+        /// shows the connection state 
+        /// </summary>
+        public bool Connected {
+            get {
+                bool Connected = false;
+                if (this.objTCPClient != null && this.objTCPClient.Client != null) {
+                    Connected = this.objTCPClient.Connected;
+                }
+                return Connected;
+            }
+        }
+
+        #endregion
+    }
+}

+ 143 - 0
Team.FFFeederService/Team.FFFeederService.csproj

@@ -0,0 +1,143 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{26DA3704-77D7-46A7-8651-684878DAC898}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>Team.FFFeederService</RootNamespace>
+    <AssemblyName>Team.FFFeederService</AssemblyName>
+    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <Deterministic>true</Deterministic>
+    <NuGetPackageImportStamp>
+    </NuGetPackageImportStamp>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup>
+    <StartupObject />
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
+      <HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
+    </Reference>
+    <Reference Include="PresentationCore" />
+    <Reference Include="PresentationFramework" />
+    <Reference Include="System" />
+    <Reference Include="System.Buffers, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Buffers.4.6.1\lib\net462\System.Buffers.dll</HintPath>
+    </Reference>
+    <Reference Include="System.ComponentModel.DataAnnotations" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.Drawing.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Drawing.Common.9.0.9\lib\net462\System.Drawing.Common.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Memory, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Memory.4.6.3\lib\net462\System.Memory.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Numerics" />
+    <Reference Include="System.Numerics.Vectors, Version=4.1.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Numerics.Vectors.4.6.1\lib\net462\System.Numerics.Vectors.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Xaml" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Net.Http" />
+    <Reference Include="System.Xml" />
+    <Reference Include="TouchSocket, Version=3.1.17.0, Culture=neutral, PublicKeyToken=5f39d7da98dac6a9, processorArchitecture=MSIL">
+      <HintPath>..\packages\TouchSocket.3.1.17\lib\net472\TouchSocket.dll</HintPath>
+    </Reference>
+    <Reference Include="TouchSocket.Core, Version=3.1.17.0, Culture=neutral, PublicKeyToken=d6c415a2f58eda72, processorArchitecture=MSIL">
+      <HintPath>..\packages\TouchSocket.Core.3.1.17\lib\net472\TouchSocket.Core.dll</HintPath>
+    </Reference>
+    <Reference Include="ValueConverters, Version=3.1.22.0, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\packages\ValueConverters.3.1.22\lib\net48\ValueConverters.dll</HintPath>
+    </Reference>
+    <Reference Include="ValueConverters.Annotations, Version=3.1.22.0, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\packages\ValueConverters.Annotations.3.1.22\lib\net48\ValueConverters.Annotations.dll</HintPath>
+    </Reference>
+    <Reference Include="WindowsBase" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="AfagFeeder.cs" />
+    <Compile Include="aflexCommunicationClass.cs" />
+    <Compile Include="AutoAdjustmentParameter.cs" />
+    <Compile Include="Enums\FeederModel.cs" />
+    <Compile Include="FeederBrand.cs" />
+    <Compile Include="FeederService.cs" />
+    <Compile Include="Enums\ActionType.cs" />
+    <Compile Include="Enums\DurationMode.cs" />
+    <Compile Include="Enums\FeederAction.cs" />
+    <Compile Include="Enums\WaveShape.cs" />
+    <Compile Include="FeederIPManage.cs" />
+    <Compile Include="Interfaces\IFeeder.cs" />
+    <Compile Include="Interfaces\IFeederService.cs" />
+    <Compile Include="Interfaces\IVoiceCoilMotor.cs" />
+    <Compile Include="Models\ActionParamcAutoFindParam.cs" />
+    <Compile Include="Models\ActionParamcs.cs" />
+    <Compile Include="Models\AutoFindParamModel.cs" />
+    <Compile Include="Models\FeederActionParam.cs" />
+    <Compile Include="Models\FeederNetworkInterface.cs" />
+    <Compile Include="Models\FeederNetworkInterfaceInfo.cs" />
+    <Compile Include="Models\NetworkInterfaceInfo.cs" />
+    <Compile Include="Models\SingleActionParam.cs" />
+    <Compile Include="Models\SingleSequenceAction.cs" />
+    <Compile Include="Models\SingleSequenceActionGroup.cs" />
+    <Compile Include="Models\HopperFeederParam.cs" />
+    <Compile Include="Models\VoiceMotorParam.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="TCPCommunicationClass.cs" />
+    <Compile Include="TeamFeeder.cs" />
+    <Compile Include="VibrationFrequencyDetector .cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <Folder Include="Events\" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="app.config" />
+    <None Include="packages.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <Analyzer Include="..\packages\TouchSocket.Core.3.1.17\analyzers\dotnet\cs\TouchSocket.Core.SourceGenerator.dll" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="Resources\AutoParaADJ.dll" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <Import Project="..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets" Condition="Exists('..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets')" />
+  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
+    <PropertyGroup>
+      <ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
+    </PropertyGroup>
+    <Error Condition="!Exists('..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets'))" />
+  </Target>
+</Project>

+ 1690 - 0
Team.FFFeederService/TeamFeeder.cs

@@ -0,0 +1,1690 @@
+using Newtonsoft.Json.Linq;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.Design;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Input;
+using Team.FFFeederService.Enums;
+using Team.FFFeederService.Interfaces;
+using Team.FFFeederService.Models;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace Team.FFFeederService
+{
+    /// <summary>
+    /// Feeder 参数读写控制
+    /// </summary>
+    public class TeamFeeder : IVoiceCoilMotorFeeder
+    {
+        #region 字段
+        /// <summary>
+        /// 背光打开命令
+        /// </summary>
+        private const string LightOpenCommand = "{K1}";
+        /// <summary>
+        /// 背光关闭命令
+        /// </summary>
+        private const string LightCloseCommand = "{K0}";
+        /// <summary>
+        /// 查询背光状态命令
+        /// </summary>
+        private const string QueryLightStateCommand = "{K?}";
+        /// <summary>
+        /// 平台振动参数起始地址
+        /// </summary>
+        private const int ShakeParamStartAddress = 300;
+        /// <summary>
+        /// 料斗振动参数起始地址
+        /// </summary>
+        private const int HopperParamStartAddress = 742;
+        /// <summary>
+        /// 序列参数起始地址
+        /// </summary>
+        private const int SequenceParamStartAddress = 950;
+
+        private IWaitingClient<ITcpClient, IReceiverResult> WaitClient;
+
+        private bool isFirstConnect = true;
+        private Task bgConnectTask;
+        #endregion
+
+        #region 属性
+        public FeederBrand FeederBrand { get => FeederBrand.TEAM; }
+
+        public FeederModel FeederModel { get; private set; } = FeederModel.Unknown;
+
+        public Guid Id { get; set; }
+        /// <summary>
+        /// Feeder连接状态
+        /// </summary>
+        public bool IsConnected => TcpClient.Online;
+
+        /// <summary>
+        /// Feeder是否首次连接成功
+        /// </summary>
+        public bool IsInit { get; private set; }
+        /// <summary>
+        /// Feeder IP地址
+        /// </summary>
+        public string FeederIp => TcpClient.IP;
+        /// <summary>
+        /// Feeder 端口
+        /// </summary>
+        public int FeederPort => TcpClient.Port;
+
+        /// <summary>
+        /// 接收数据的超时时间
+        /// </summary>
+        public int MillisecondsTimeout = 5000;  //接收数据超时时间
+
+        /// <summary>
+        /// TCP客户端通讯
+        /// </summary>
+        public TcpClient TcpClient { get; }
+        #endregion
+        // private const string SelectOneShakeCommand = "{UV1}\r\n";
+
+        #region 事件
+        /// <summary>
+        /// Feeder连接上时
+        /// </summary>
+        public event Action<Guid, ITcpClient, ConnectedEventArgs> FeederConnectedEvent;
+        /// <summary>
+        /// Feeder断开连接上时
+        /// </summary>
+        public event Action<Guid, ITcpClient, ClosedEventArgs> FeederDisconnectedEvent;
+        #endregion
+
+        public TeamFeeder(TcpClient tcpClient)
+        {
+            TcpClient = tcpClient;
+            //调用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;
+        }
+
+        #region 方法
+
+        #region Feeder 连接
+        /// <summary>
+        /// 连接Feeder
+        /// </summary>
+        public void Connect()
+        {
+            try
+            {
+                TcpClient.Connect();
+                IsInit = true;
+                isFirstConnect = false;
+            }
+            catch (Exception)
+            {
+                IsInit = false;
+                if (bgConnectTask == null)
+                {
+                    bgConnectTask = Task.Run(async () =>
+                    {
+                        while (true)
+                        {
+                            try
+                            {
+                                TcpClient.Connect();
+                                isFirstConnect = false;
+                                return;
+                            }
+                            catch (Exception)
+                            {
+                                await Task.Delay(1000);
+                            }
+                        }
+                    });
+                }
+                throw;
+            }
+        }
+
+        /// <summary>
+        /// 连接Feeder
+        /// </summary>
+        /// <returns></returns>
+        public async Task ConnectAsync()
+        {
+            try
+            {
+                await TcpClient.ConnectAsync();
+                IsInit = true;
+                isFirstConnect = false;
+            }
+            catch (Exception)
+            {
+                IsInit = false;
+                if (bgConnectTask == null)
+                {
+                    bgConnectTask = Task.Run(async () =>
+                    {
+                        while (true)
+                        {
+                            try
+                            {
+                                TcpClient.Connect();
+                                isFirstConnect = false;
+                                return;
+                            }
+                            catch (Exception)
+                            {
+                                await Task.Delay(1000);
+                            }
+                        }
+                    });
+                }
+                throw;
+            }
+        }
+        #endregion
+
+        public void Reset()
+        {
+
+        }
+        public Task ResetAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        #region 振动集
+        /// <summary>
+        /// 选择使用振动集
+        /// </summary>
+        /// <param name="id"></param>
+        /// <exception cref="FeederResponseException"></exception>
+        public void SelectShakeParam(int id)
+        {
+            var sendCommand = "{UV" + id + "}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            if (result.TrimEnd() != sendCommand.TrimEnd())
+            {
+                throw new Exception("FFFeeder响应不正确");
+            }
+        }
+
+        /// <summary>
+        /// 选择使用振动集
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        /// <exception cref="FeederResponseException"></exception>
+        public async Task SelectShakeParamAsync(int id)
+        {
+            var sendCommand = "{UV" + id + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            if (result.TrimEnd() != sendCommand.TrimEnd())
+            {
+                throw new Exception("FFFeeder响应不正确");
+            }
+        }
+
+        /// <summary>
+        /// 将振动集参数存储至非易失内存中
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public async Task SaveShakeSetAsync()
+        {
+            string sendCommand = "{DV}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            if (result.TrimEnd() != sendCommand.TrimEnd())
+            {
+                throw new Exception("FFFeeder响应不正确");
+            }
+        }
+
+        /// <summary>
+        /// 查询当前选择的振动集
+        /// </summary>
+        /// <returns></returns>
+        public int GetSelectedShakeParam()
+        {
+            const string sendCommand = "{UV?}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return int.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+
+        /// <summary>
+        /// 查询当前选择的振动集
+        /// </summary>
+        /// <returns></returns>
+        public async Task<int> GetSelectedShakeParamAsync()
+        {
+            const string sendCommand = "{UV?}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return int.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+        #endregion
+
+        #region 平台振动参数
+        //300~741
+        //300   A   平台振动 A 振幅 1
+        //301   A   平台振动 A 频率 1
+        //302   A   平台振动 A 相位 1
+        //303   A   平台振动 A 波形 1
+        //304   A   平台振动 A 振幅 2
+        //305   A   平台振动 A 频率 2
+        //306   A   平台振动 A 相位 2
+        //307   A   平台振动 A 波形 2
+        //308   A   平台振动 A 振幅 3
+        //309   A   平台振动 A 频率 3
+        //310   A   平台振动 A 相位 3
+        //311   A   平台振动 A 波形 3
+        //312   A   平台振动 A 振幅 4
+        //313   A   平台振动 A 频率 4
+        //314   A   平台振动 A 相位 4
+        //315   A   平台振动 A 波形 4
+        //316   A   平台振动 A 持续时间
+        //300+17*n
+
+        /// <summary>
+        /// 选择要使用的振动集(1~26)
+        /// </summary>
+        /// <param name="v"></param>
+        /// <returns></returns>
+        public bool LoadShakeSet(int v)
+        {
+            var command = "{UV" + v + "}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            return result == command;
+        }
+
+        /// <summary>
+        /// 选择要使用的振动集(1~26)
+        /// </summary>
+        /// <param name="v"></param>
+        /// <returns></returns>
+        public async Task<bool> LoadShakeSetAsync(int v)
+        {
+            var command = "{UV" + v + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+
+            return result == command;
+        }
+
+        /// <summary>
+        /// 执行平台振动
+        /// </summary>
+        /// <param name="index"></param>
+        /// <param name="timespan"></param>
+        public async Task<int> StartAction(int index, int? timespan = null)
+        {
+            if (index < 0 || index > 25)
+            {
+                index = 0;
+            }
+            char chn = (char)('A' + index);
+            string actionCommand = $"C{chn}";
+            return await RunFromCommand(actionCommand, timespan);
+        }
+
+        /// <summary>
+        /// 停止平台振动
+        /// </summary>
+        public void Stop()
+        {
+            WaitClient.SendThenReturn(Encoding.ASCII.GetBytes("{HC}"), MillisecondsTimeout);
+        }
+
+        /// <summary>
+        /// 停止平台振动
+        /// </summary>
+        /// <returns></returns>
+        public Task StopAsync()
+        {
+            return WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes("{HC}"), MillisecondsTimeout);
+        }
+
+        /// <summary>
+        /// 向前
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToLeftAsync(int? timespan = null)
+        {
+            var command = "{CA" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CA", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 左前
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToBottomLeftAsync(int? timespan = null)
+        {
+
+            var command = "{CB" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CB", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 右前
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToTopLeftAsync(int? timespan = null)
+        {
+            var command = "{CC" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CC", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 向左
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToBottomAsync(int? timespan = null)
+        {
+            var command = "{CD" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CD", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 向右
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToTopAsync(int? timespan = null)
+        {
+            var command = "{CE" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CE", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 向后
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToRightAsync(int? timespan = null)
+        {
+            var command = "{CF" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CF", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 左后
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToBottomRightAsync(int? timespan = null)
+        {
+            var command = "{CG" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CG", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 右后
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToTopRightAsync(int? timespan = null)
+        {
+            var command = "{CH" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CH", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 散开
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToFlipAsync(int? timespan = null)
+        {
+
+            var command = "{CI" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CI", "");
+            return string.IsNullOrEmpty(timeSpan) ? 0 : int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 横向聚中
+        /// </summary>
+        /// <param name="timespan">持续时间</param>
+        /// <returns></returns>
+        public async Task<int> RunToInnerVerticalAsync(int? timespan = null)
+        {
+            var command = "{CJ" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CJ", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 纵向聚中
+        /// </summary>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunToInnerHorizonAsync(int? timespan = null)
+        {
+            var command = "{CK" + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("CK", "");
+            if (string.IsNullOrEmpty(timeSpan))
+            {
+                return 0;
+            }
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 读一个振动动作值
+        /// </summary>
+        /// <param name="v"></param>
+        /// <returns></returns>
+        public SingleActionParam GetShakeGroupValue(int index)
+        {
+            if (index < 0 || index > 25)
+            {
+                index = 0;
+            }
+            return GetShakeGroupValueAsync(index).GetAwaiter().GetResult();
+        }
+
+        /// <summary>
+        /// 读一个振动动作值
+        /// </summary>
+        /// <param name="index"></param>
+        /// <returns></returns>
+        public async Task<SingleActionParam> GetShakeGroupValueAsync(int index)
+        {
+            var results = new string[17];
+            for (var j = 0; j < 17; j++)
+            {
+                var id = index * 17 + ShakeParamStartAddress + j;
+                var command = "{RP" + id + "}";
+                var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+                string result = Encoding.ASCII.GetString(returnData);
+                results[j] = result.TrimEnd().Replace("{RP", "").Replace("}", "").Split(":")[1];
+            }
+            int i = 0;
+            SingleActionParam actionParam=new SingleActionParam();
+            actionParam.Motor1 = new VoiceMotorParam() { Amplitude = ushort.Parse(results[i]), Frequency= ushort.Parse(results[i+1]), Phase = ushort.Parse(results[i + 2]), WaveShape= (WaveShape)ushort.Parse(results[i + 3]) };
+            i = 4;
+            actionParam.Motor2 = new VoiceMotorParam() { Amplitude = ushort.Parse(results[i]), Frequency = ushort.Parse(results[i + 1]), Phase = ushort.Parse(results[i + 2]), WaveShape = (WaveShape)ushort.Parse(results[i + 3]) };
+            i = 8;
+            actionParam.Motor3 = new VoiceMotorParam() { Amplitude = ushort.Parse(results[i]), Frequency = ushort.Parse(results[i + 1]), Phase = ushort.Parse(results[i + 2]), WaveShape = (WaveShape)ushort.Parse(results[i + 3]) };
+            i = 12;
+            actionParam.Motor4 = new VoiceMotorParam() { Amplitude = ushort.Parse(results[i]), Frequency = ushort.Parse(results[i + 1]), Phase = ushort.Parse(results[i + 2]), WaveShape = (WaveShape)ushort.Parse(results[i + 3]) };
+            actionParam.DurationValue = int.Parse(results[16]);
+            return actionParam;
+        }
+
+        /// <summary>
+        /// 获取单个动作持续时间
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        public int GetDuration(int id)
+        {
+            var idInServer = id * 17 + 316;
+            var command = "{RP" + idInServer + "}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            var value = result.TrimEnd().Replace("{RP", "").Replace("}", "").Split(':')[1];
+            return int.Parse(value);
+        }
+
+        /// <summary>
+        /// 获取单个动作持续时间
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        public async Task<int> GetDurationAsync(int id)
+        {
+            var idInServer = id * 17 + 316;
+            var command = "{RP" + idInServer + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            var value = result.TrimEnd().Replace("{RP", "").Replace("}", "").Split(':')[1];
+            return int.Parse(value);
+        }
+
+        /// <summary>
+        /// 写入振动单个参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="id"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        public async Task SetShakeParametersAsync(int selectedShakeMotion, int id, string value)
+        {
+            var commandId = 300 + selectedShakeMotion * 17 + id;
+            var command = "{WP" + $"{commandId}={value}" + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            //string result = Encoding.ASCII.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 写入振动单个参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="id"></param>
+        /// <param name="value"></param>
+        public void SetShakeParameters(int selectedShakeMotion, int id, string value)
+        {
+            var commandId = 300 + selectedShakeMotion * 17 + id;
+            var command = "{WP" + $"{commandId}={value}" + "}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command));
+        }
+
+        /// <summary>
+        /// 写入平台振动完成参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        public async Task SetShakeParametersAsync(int selectedShakeMotion, string value)
+        {
+            if (selectedShakeMotion < 0 || selectedShakeMotion > 15)
+                selectedShakeMotion = 0;
+            char chn = (char)('A' + selectedShakeMotion);
+            var command = "{SC" + $"{chn}=" + $"({value})" + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+        }
+
+        /// <summary>
+        /// 写入平台振动完成参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="value"></param>
+        public void SetShakeParameters(int selectedShakeMotion, string value)
+        {
+            if (selectedShakeMotion < 0 || selectedShakeMotion > 15)
+                selectedShakeMotion = 0;
+            char chn = (char)('A' + selectedShakeMotion);
+            var command = "{SC" + $"{chn}=" + $"({value})" + "}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command));
+        }
+
+        /// <summary>
+        /// 写入完整的平台振动参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="value"></param>
+        public void SetShakeParameters(int selectedShakeMotion, SingleActionParam value)
+        {
+            StringBuilder sb = new StringBuilder();
+            sb.Append($"{value.Motor1.Amplitude};{value.Motor1.Frequency};{value.Motor1.Phase};{(int)value.Motor1.WaveShape};");
+            sb.Append($"{value.Motor2.Amplitude};{value.Motor2.Frequency};{value.Motor2.Phase};{(int)value.Motor2.WaveShape};");
+            sb.Append($"{value.Motor3.Amplitude};{value.Motor3.Frequency};{value.Motor3.Phase};{(int)value.Motor3.WaveShape};");
+            sb.Append($"{value.Motor4.Amplitude};{value.Motor4.Frequency};{value.Motor4.Phase};{(int)value.Motor4.WaveShape};");
+            sb.Append($"{value.DurationValue}");
+            SetShakeParameters(selectedShakeMotion, sb.ToString());
+        }
+
+        /// <summary>
+        /// 写入完整的平台振动参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        public async Task SetShakeParametersAsync(int selectedShakeMotion, SingleActionParam value)
+        {
+            StringBuilder sb = new StringBuilder();
+            sb.Append($"{value.Motor1.Amplitude};{value.Motor1.Frequency};{value.Motor1.Phase};{(int)value.Motor1.WaveShape};");
+            sb.Append($"{value.Motor2.Amplitude};{value.Motor2.Frequency};{value.Motor2.Phase};{(int)value.Motor2.WaveShape};");
+            sb.Append($"{value.Motor3.Amplitude};{value.Motor3.Frequency};{value.Motor3.Phase};{(int)value.Motor3.WaveShape};");
+            sb.Append($"{value.Motor4.Amplitude};{value.Motor4.Frequency};{value.Motor4.Phase};{(int)value.Motor4.WaveShape};");
+            sb.Append($"{value.DurationValue}");
+            await SetShakeParametersAsync(selectedShakeMotion, sb.ToString());
+        }
+
+        /// <summary>
+        /// 获取完整的平台振动参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <returns></returns>
+        public SingleActionParam GetShakeParameters(int selectedShakeMotion)
+        {
+            if (selectedShakeMotion < 0 || selectedShakeMotion > 15)
+                selectedShakeMotion = 0;
+            char chn = (char)('A' + selectedShakeMotion);
+            var command = "{LC" + $"{chn}" + "}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace($"LC{chn}", "").Replace("(", "").Replace(")", "").Replace(":", "").Split(";");
+            int i = 0;
+            SingleActionParam actionParam = new SingleActionParam();
+            actionParam.Motor1 = new VoiceMotorParam() { Amplitude = ushort.Parse(timeSpan[i]), Frequency = ushort.Parse(timeSpan[i + 1]), Phase = ushort.Parse(timeSpan[i + 2]), WaveShape = (WaveShape)ushort.Parse(timeSpan[i + 3]) };
+            i = 4;
+            actionParam.Motor2 = new VoiceMotorParam() { Amplitude = ushort.Parse(timeSpan[i]), Frequency = ushort.Parse(timeSpan[i + 1]), Phase = ushort.Parse(timeSpan[i + 2]), WaveShape = (WaveShape)ushort.Parse(timeSpan[i + 3]) };
+            i = 8;
+            actionParam.Motor2 = new VoiceMotorParam() { Amplitude = ushort.Parse(timeSpan[i]), Frequency = ushort.Parse(timeSpan[i + 1]), Phase = ushort.Parse(timeSpan[i + 2]), WaveShape = (WaveShape)ushort.Parse(timeSpan[i + 3]) };
+            i = 12;
+            actionParam.Motor2 = new VoiceMotorParam() { Amplitude = ushort.Parse(timeSpan[i]), Frequency = ushort.Parse(timeSpan[i + 1]), Phase = ushort.Parse(timeSpan[i + 2]), WaveShape = (WaveShape)ushort.Parse(timeSpan[i + 3]) };
+            actionParam.DurationValue = int.Parse(timeSpan[16]);
+            return actionParam;
+        }
+
+        /// <summary>
+        /// 获取完整的平台振动参数
+        /// </summary>
+        /// <param name="selectedShakeMotion"></param>
+        /// <returns></returns>
+        public async Task<SingleActionParam> GetShakeParametersAsync(int selectedShakeMotion)
+        {
+            if (selectedShakeMotion < 0 || selectedShakeMotion > 15)
+                selectedShakeMotion = 0;
+            char chn = (char)('A' + selectedShakeMotion);
+            var command = "{LC" + $"{chn}" + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace($"LC{chn}", "").Replace("(", "").Replace(")", "").Replace(":", "").Split(";");
+            int i = 0;
+            SingleActionParam actionParam = new SingleActionParam();
+            actionParam.Motor1 = new VoiceMotorParam() { Amplitude = ushort.Parse(timeSpan[i]), Frequency = ushort.Parse(timeSpan[i + 1]), Phase = ushort.Parse(timeSpan[i + 2]), WaveShape = (WaveShape)ushort.Parse(timeSpan[i + 3]) };
+            i = 4;
+            actionParam.Motor2 = new VoiceMotorParam() { Amplitude = ushort.Parse(timeSpan[i]), Frequency = ushort.Parse(timeSpan[i + 1]), Phase = ushort.Parse(timeSpan[i + 2]), WaveShape = (WaveShape)ushort.Parse(timeSpan[i + 3]) };
+            i = 8;
+            actionParam.Motor2 = new VoiceMotorParam() { Amplitude = ushort.Parse(timeSpan[i]), Frequency = ushort.Parse(timeSpan[i + 1]), Phase = ushort.Parse(timeSpan[i + 2]), WaveShape = (WaveShape)ushort.Parse(timeSpan[i + 3]) };
+            i = 12;
+            actionParam.Motor2 = new VoiceMotorParam() { Amplitude = ushort.Parse(timeSpan[i]), Frequency = ushort.Parse(timeSpan[i + 1]), Phase = ushort.Parse(timeSpan[i + 2]), WaveShape = (WaveShape)ushort.Parse(timeSpan[i + 3]) };
+            actionParam.DurationValue = int.Parse(timeSpan[16]);
+            return actionParam;
+        }
+
+        /// <summary>
+        /// 获取平台震动超时时间
+        /// </summary>
+        /// <returns></returns>
+        public async Task<ushort> GetPlatShakeTimeoutAsync()
+        {
+            const string sendCommand = "{RP65?}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return ushort.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+
+        /// <summary>
+        /// 设置平台震动超时时间
+        /// </summary>
+        /// <param name="upperFeederShakeTimeout"></param>
+        /// <returns></returns>
+        public async Task SetPlatShakeTimeoutAsync(ushort upperFeederShakeTimeout)
+        {
+            const int commandId = 65;
+            var command = "{WP" + $"{commandId}={upperFeederShakeTimeout}" + "}";
+            var result = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            //const string saveCommand = "{DG}";
+            //var result1 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(saveCommand));
+        }
+        #endregion
+
+        #region 料斗振动输出参数
+        //742~949
+        //742+8*n   n   料斗动作 n 数字量输出 1
+        //743+8*n   n   料斗动作 n 模拟量输出 1
+        //744+8*n   n   料斗动作 n 数字量输出 2
+        //745+8*n   n   料斗动作 n 模拟量输出 2
+        //746+8*n   n   备用
+        //747+8*n   n   备用
+        //748+8*n   n   备用
+        //749+8*n   n   料斗振动 n 持续时间
+
+        /// <summary>
+        /// 执行料斗供料
+        /// </summary>
+        /// <returns></returns>
+        public async Task<int> ShakeUpAsync()
+        {
+            const string sendCommand = "{EF:(A;55;110)}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return ushort.Parse(result.TrimEnd().Split(';')[1].Replace("}", "").Replace(")", ""));
+        }
+
+        /// <summary>
+        /// 执行供料
+        /// </summary>
+        /// <returns></returns>
+        public int ShakeUp()
+        {
+            const string sendCommand = "{EF:(A;55;110)}";
+            var result = Encoding.ASCII.GetString(WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(sendCommand)));
+            return ushort.Parse(result.TrimEnd().Split(';')[1].Replace("}", "").Replace(")", ""));
+        }
+
+        /// <summary>
+        /// 停止料斗振动
+        /// </summary>
+        /// <returns></returns>
+        public Task StopOutputAsync()
+        {
+            const string command = "{HB}";
+            return WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+        }
+
+        /// <summary>
+        /// 停止料斗振动
+        /// </summary>
+        public void StopOutput()
+        {
+            const string command = "{HB}";
+            WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command));
+        }
+
+        /// <summary>
+        /// 获取料斗参数
+        /// </summary>
+        /// <param name="selectedSequence"></param>
+        /// <returns></returns>
+        public async Task<HopperFeederParam> GetUpperParamAsync(int selectedSequence)
+        {
+            var param = new HopperFeederParam();
+            var startIndex = 742 + selectedSequence * 8;
+            var collections = new string[8];
+            for (var i = 0; i < 8; i++)
+            {
+                var id = startIndex + i;
+                var result = await GetSingleParamValueAsync(id);
+                collections[i] = result.Replace("{", "").Replace("}", "").Split(':')[1];
+            }
+
+            param.HopperDigitalOutput1 = int.Parse(collections[0]) == 1;
+            param.HopperAnalogOutput1 = int.Parse(collections[1]);
+            param.HopperDigitalOutput2 = int.Parse(collections[2]) == 1;
+            param.HopperAnalogOutput2 = int.Parse(collections[3]);
+            param.HopperVibrationAmpl = int.Parse(collections[4]);
+            param.HopperVibrationFreq = int.Parse(collections[5]);
+            param.HopperVibrationWaveform = int.Parse(collections[6]);
+            param.HopperDuration = int.Parse(collections[7]);
+            return param;
+            //return ushort.Parse(result.Split(':')[1].Replace("}", ""));
+        }
+
+        /// <summary>
+        /// 写入输出参数
+        /// </summary>
+        /// <param name="groupId"></param>
+        /// <param name="param"></param>
+        /// <returns></returns>
+        public async Task WriteOutputParamAsync(int groupId, HopperFeederParam param)
+        {
+            const int startId = 742;
+            var id1 = startId + groupId * 8;
+            var id2 = startId + groupId * 8 + 1;
+            var id3 = startId + groupId * 8 + 2;
+            var id4 = startId + groupId * 8 + 3;
+            var id5 = startId + groupId * 8 + 7;
+            var command1 = "{WP" + $"{id1}={Convert.ToInt32(param.HopperDigitalOutput1)}" + "}";
+            var command2 = "{WP" + $"{id2}={Convert.ToInt32(param.HopperAnalogOutput1)}" + "}";
+            var command3 = "{WP" + $"{id3}={Convert.ToInt32(param.HopperDigitalOutput2)}" + "}";
+            var command4 = "{WP" + $"{id4}={Convert.ToInt32(param.HopperAnalogOutput2)}" + "}";
+            var command5 = "{WP" + $"{id5}={Convert.ToInt32(param.HopperDuration)}" + "}";
+            var result1 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command1));
+            var result2 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command2));
+            var result3 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command3));
+            var result4 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command4));
+            var result5 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command5));
+            await SaveShakeSetAsync();
+        }
+
+        /// <summary>
+        /// 获取料斗震动超时时间
+        /// </summary>
+        /// <returns></returns>
+        public async Task<ushort> GetUpperFeederShakeTimeoutAsync()
+        {
+            const string sendCommand = "{RP66?}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return ushort.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+
+        /// <summary>
+        /// 设置料斗震动超时时间
+        /// </summary>
+        /// <param name="upperFeederShakeTimeout"></param>
+        /// <returns></returns>
+        public async Task SetUpperFeederShakeTimeoutAsync(ushort upperFeederShakeTimeout)
+        {
+            const int commandId = 66;
+            var command = "{WP" + $"{commandId}={upperFeederShakeTimeout}" + "}";
+            var result = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            //const string saveCommand = "{DG}";
+            //var result1 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(saveCommand));
+        }
+
+        /// <summary>
+        /// 执行料斗动作
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public async Task<int> OutputAsync(int id, int? timespan = null)
+        {
+            if (id < 1 || id > 26)
+            {
+                throw new Exception("输入参数不正确");
+            }
+
+            var enumerable = Enumerable.Range('A', 26).ToArray();
+            //var split = new[] { "A", "B" };
+            var outPut = "B" + (char)enumerable[id - 1];
+            var command = "{" + outPut + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace(outPut, "");
+            return string.IsNullOrWhiteSpace(timeSpan) ? 0 : int.Parse(timeSpan);
+
+        }
+
+        /// <summary>
+        /// 执行料斗动作
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public int Output(int id, int? timespan = null)
+        {
+            var enumerable = Enumerable.Range('A', 26).ToArray();
+            //var split = new[] { "A", "B" };
+            var outPut = "B" + (char)enumerable[id - 1];
+            var command = "{" + outPut + timespan + "}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace(outPut, "");
+            return int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 获取取料斗动作状态
+        /// </summary>
+        /// <returns></returns>
+        public bool GetOutputStatus()
+        {
+            const string sendCommand = "{RP97?}";
+            var result = Encoding.ASCII.GetString(WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(sendCommand)));
+            return result.Split(':')[1].Replace("}", "") == "0" ? false : true;
+        }
+
+        /// <summary>
+        ///获取取料斗动作状态
+        /// </summary>
+        /// <returns></returns>
+        public async Task<bool> GetOutputStatusAsync()
+        {
+            const string sendCommand = "{RP97?}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return result.Split(':')[1].Replace("}", "") == "0" ? false : true;
+        }
+        #endregion
+
+        #region 序列动作参数
+        //950~1703
+        //950+29*n  n   动作 1 类型
+        //951+29*n  n   动作 1 震动
+        //952+29*n  n   动作 1 持续模式
+        //953+29*n  n   动作 1 持续时间值
+        //954+29*n  n   动作 2 类型
+        //955+29*n  n   动作 2 震动
+        //956+29*n  n   动作 2 持续模式
+        //957+29*n  n   动作 2 持续时间值
+        //958+29*n  n   动作 3 类型
+        //959+29*n  n   动作 3 震动
+        //960+29*n  n   动作 3 持续模式
+        //961+29*n  n   动作 3 持续时间值
+        //962+29*n  n   动作 4 类型
+        //963+29*n  n   动作 4 震动
+        //964+29*n  n   动作 4 持续模式
+        //965+29*n  n   动作 4 持续时间值
+        //966+29*n  n   动作 5 类型
+        //967+29*n  n   动作 5 震动
+        //968+29*n  n   动作 5 持续模式
+        //969+29*n  n   动作 5 持续时间值
+        //970+29*n  n   动作 6 类型
+        //971+29*n  n   动作 6 震动
+        //972+29*n  n   动作 6 持续模式
+        //973+29*n  n   动作 6 持续时间值
+        //974+29*n  n   动作 7 类型
+        //975+29*n  n   动作 7 震动
+        //976+29*n  n   动作 7 持续模式
+        //977+29*n  n   动作 7 持续时间值
+        //978+29*n  n   震动平台零件极限值
+
+        /// <summary>
+        /// 停止序列
+        /// </summary>
+        /// <returns></returns>
+        public async Task StopOneSequenceAsync()
+        {
+            var sendCommand = "{HS}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            //string result = Encoding.ASCII.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 执行一个序列
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        public async Task<int> StartOneSequenceAsync(int id)
+        {
+            var sendCommand = "{ES:(0;0;0;0;" + id + ")}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            var replaced = result.TrimEnd().Replace("{", "").Replace("}", "").Replace("(", "").Replace(")", "");
+            var splits = replaced.Split(';');
+            return int.Parse(splits[5]);
+            //#if NETCOREAPP
+            //            var time = int.Parse(splits[^1]);
+            //            return time;
+            //#elif NET472||NETSTANDARD
+            //  var time = int.Parse(splits[splits.Length - 1]);
+            //            return time;
+            //#endif
+        }
+
+        /// <summary>
+        /// 获取单个序列集
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        public async Task<SingleSequenceActionGroup> GetSequenceGroupAsync(int id)
+        {
+            const int startId = SequenceParamStartAddress;
+            var singleSequenceActionGroup = new SingleSequenceActionGroup();
+            singleSequenceActionGroup.SingleSequenceActions = new System.Collections.ObjectModel.ObservableCollection<SingleSequenceAction>();
+            for (var i = 0; i < 7; i++)
+            {
+                var singleSequenceAction = new SingleSequenceAction();
+                var value1 = await GetSingleParamValueAsync(startId + id * 29 + i * 4);
+                var value2 = await GetSingleParamValueAsync(startId + id * 29 + i * 4 + 1);
+                var value3 = await GetSingleParamValueAsync(startId + id * 29 + i * 4 + 2);
+                var value4 = await GetSingleParamValueAsync(startId + id * 29 + i * 4 + 3);
+                value1 = value1.Replace("{", "");
+                value1 = value1.Replace("}", "").Split(':')[1];
+                value2 = value2.Replace("{", "");
+                value2 = value2.Replace("}", "").Split(':')[1];
+                value3 = value3.Replace("{", "");
+                value3 = value3.Replace("}", "").Split(':')[1];
+                value4 = value4.Replace("{", "");
+                value4 = value4.Replace("}", "").Split(':')[1];
+                singleSequenceAction.Type = (ActionType)int.Parse(value1);
+                singleSequenceAction.ShakeId = int.Parse(value2) > 0 ? int.Parse(value2) : 0;
+                singleSequenceAction.DurationMode = (DurationMode)int.Parse(value3);
+                singleSequenceAction.DurationValue = int.Parse(value4);
+
+                singleSequenceActionGroup.SingleSequenceActions.Add(singleSequenceAction);
+            }
+
+            var value5 = await GetSingleParamValueAsync(startId + id * 29 + 28);
+            value5 = value5.Replace("{", "");
+            value5 = value5.Replace("}", "").Split(':')[1];
+            singleSequenceActionGroup.PartCntMax = int.Parse(value5);
+            return singleSequenceActionGroup;
+        }
+
+        /// <summary>
+        /// 写入序列参数
+        /// </summary>
+        /// <param name="groupId"></param>
+        /// <param name="singleSequenceAction"></param>
+        public void SetSequence(int groupId, int actionId, SingleSequenceAction singleSequenceAction)
+        {
+            const int startId = SequenceParamStartAddress;
+            var id1 = startId + groupId * 29 + actionId * 4;
+            var id2 = startId + groupId * 29 + actionId * 4 + 1;
+            var id3 = startId + groupId * 29 + actionId * 4 + 2;
+            var id4 = startId + groupId * 29 + actionId * 4 + 3;
+            var command1 = "{WP" + $"{id1}={(int)singleSequenceAction.Type}" + "}";
+            var command2 = "{WP" + $"{id1}={singleSequenceAction.ShakeId}" + "}";
+            var command3 = "{WP" + $"{id1}={(int)singleSequenceAction.DurationMode}" + "}";
+            var command4 = "{WP" + $"{id1}={(int)singleSequenceAction.DurationValue}" + "}";
+
+            var result = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command1));
+            result = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command2));
+            result = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command3));
+            result = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command4));
+        }
+
+        /// <summary>
+        /// 写入序列参数
+        /// </summary>
+        /// <param name="groupId"></param>
+        /// <param name="actionId"></param>
+        /// <param name="singleSequenceAction"></param>
+        /// <returns></returns>
+        public async Task SetSequenceAsync(int groupId, int actionId, SingleSequenceAction singleSequenceAction)
+        {
+            const int startId = 950;
+            var id1 = startId + groupId * 29 + actionId * 4;
+            var id2 = startId + groupId * 29 + actionId * 4 + 1;
+            var id3 = startId + groupId * 29 + actionId * 4 + 2;
+            var id4 = startId + groupId * 29 + actionId * 4 + 3;
+            var command1 = "{WP" + $"{id1}={(int)singleSequenceAction.Type}" + "}";
+            var command2 = "{WP" + $"{id2}={singleSequenceAction.ShakeId}" + "}";
+            var command3 = "{WP" + $"{id3}={(int)singleSequenceAction.DurationMode}" + "}";
+            var command4 = "{WP" + $"{id4}={singleSequenceAction.DurationValue}" + "}";
+
+            var result = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command1));
+            result = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command2));
+            result = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command3));
+            result = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command4));
+        }
+
+        /// <summary>
+        /// 将序列参数存储至非易失内存中
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public async Task SaveSequenceAsync()
+        {
+            const string sendCommand = "{DS}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            if (result.TrimEnd() != sendCommand.TrimEnd())
+            {
+                throw new Exception("FFFeeder响应不正确");
+            }
+        }
+
+        /// <summary>
+        /// 查询当前选择的序列
+        /// </summary>
+        /// <returns></returns>
+        public int GetSelectedSequence()
+        {
+            const string sendCommand = "{US?}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+
+            return int.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+
+        /// <summary>
+        /// 查询当前选择的序列
+        /// </summary>
+        /// <returns></returns>
+        public async Task<int> GetSelectedSequenceAsync()
+        {
+            const string sendCommand = "{US?}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+
+            return int.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+        #endregion
+
+        #region 背光灯操作
+        /// <summary>
+        /// 背光灯打开
+        /// </summary>
+        public void OpenLight()
+        {
+            WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(LightOpenCommand), MillisecondsTimeout);
+        }
+
+        /// <summary>
+        /// 背光灯打开
+        /// </summary>
+        /// <returns></returns>
+        public Task OpenLightAsync()
+        {
+            return WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(LightOpenCommand), MillisecondsTimeout);
+        }
+
+        /// <summary>
+        /// 背光关闭
+        /// </summary>
+        public void CloseLight()
+        {
+            WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(LightCloseCommand), MillisecondsTimeout);
+        }
+
+        /// <summary>
+        /// 背光关闭
+        /// </summary>
+        /// <returns></returns>
+        public Task CloseLightAsync()
+        {
+            return WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(LightCloseCommand), MillisecondsTimeout);
+        }
+
+        /// <summary>
+        /// 设置背光打开超时时间
+        /// </summary>
+        /// <param name="timeout"></param>
+        public void SetLightTimeOut(ushort timeout)
+        {
+            var commandId = 44;
+            var command = "{WP" + $"{commandId}={timeout}" + "}";
+            var result = Encoding.ASCII.GetString(WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command)));
+            //var saveCommand = "{DG}";
+            //var result1 = Encoding.ASCII.GetString(WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(saveCommand)));
+        }
+
+        /// <summary>
+        /// 设置背光打开超时时间
+        /// </summary>
+        /// <param name="timeout"></param>
+        /// <returns></returns>
+        public async Task SetLightTimeOutAsync(ushort timeout)
+        {
+            var commandId = 44;
+            var command = "{WP" + $"{commandId}={timeout}" + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            //var saveCommand = "{DG}";
+            //returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(saveCommand));
+        }
+
+        /// <summary>
+        /// 获取背光打开超时时间
+        /// </summary>
+        /// <returns></returns>
+        public ushort GetLightTimeout()
+        {
+            const string sendCommand = "{RP44?}";
+            var result = Encoding.ASCII.GetString(WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(sendCommand)));
+            return ushort.Parse(result.Split(':')[1].Replace("}", ""));
+        }
+
+        /// <summary>
+        /// 获取背光打开超时时间
+        /// </summary>
+        /// <returns></returns>
+        public async Task<ushort> GetLightTimeoutAsync()
+        {
+            const string sendCommand = "{RP44?}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return ushort.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+
+        /// <summary>
+        /// 设置背光亮度
+        /// </summary>
+        /// <param name="lightValue"></param>
+        /// <returns></returns>
+        public async Task SetLightValueAsync(ushort lightValue)
+        {
+            const int commandId = 34;
+            var command = "{WP" + $"{commandId}={lightValue}" + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            string result = Encoding.ASCII.GetString(returnData);
+            //const string saveCommand = "{DG}";
+            //returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(saveCommand));
+            //result = Encoding.ASCII.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 设置背光亮度
+        /// </summary>
+        /// <param name="lightValue"></param>
+        /// <returns></returns>
+        public async Task SetLightValueToBufferAsync(ushort lightValue)
+        {
+            const int commandId = 34;
+            var command = "{WP" + $"{commandId}={lightValue}" + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            //string result = Encoding.ASCII.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 设置背光闪烁时间
+        /// </summary>
+        /// <param name="backLightFlash"></param>
+        /// <returns></returns>
+        public async Task SetBackLightFlashTimeAsync(ushort backLightFlash)
+        {
+            const int commandId = 33;
+            var command = "{WP" + $"{commandId}={backLightFlash}" + "}";
+            var result = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            //const string saveCommand = "{DG}";
+            //var result1 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(saveCommand));
+        }
+
+        /// <summary>
+        /// 获取背光状态
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public bool QueryLightState()
+        {
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(QueryLightStateCommand));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            result = result.Trim().Replace("{", "").Replace("}", "");
+            var splitsStrings = result.Split(':');
+            if (splitsStrings.Length <= 1)
+            {
+                throw new Exception("RECEIVED DATA NOT CORRECT");
+            }
+
+            return splitsStrings[1] == "1";
+        }
+
+        /// <summary>
+        /// 获取背光状态
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public async Task<bool> QueryLightStateAsync()
+        {
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(QueryLightStateCommand));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            result = result.Trim().Replace("{", "").Replace("}", "");
+            var splitsStrings = result.Split(':');
+            if (splitsStrings.Length <= 1)
+            {
+                throw new Exception("RECEIVED DATA NOT CORRECT");
+            }
+
+            return splitsStrings[1] == "1";
+        }
+
+        /// <summary>
+        /// 获取背光亮度
+        /// </summary>
+        /// <returns></returns>
+        public async Task<ushort> GetLightBrightnessAsync()
+        {
+            const string sendCommand = "{RP34?}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return ushort.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+
+        /// <summary>
+        /// 获取背光闪烁时间
+        /// </summary>
+        /// <returns></returns>
+        public async Task<ushort> GetBackLightFlashTimeAsync()
+        {
+            const string sendCommand = "{RP33?}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            return ushort.Parse(result.TrimEnd().Split(':')[1].Replace("}", ""));
+        }
+        #endregion
+
+
+        /// <summary>
+        /// 执行命令
+        /// </summary>
+        /// <param name="command"></param>
+        /// <param name="timespan"></param>
+        /// <returns></returns>
+        public async Task<int> RunFromCommand(string command, int? timespan = null)
+        {
+            var exeCommand = "{" + command + timespan + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(exeCommand));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            var timeSpan = result.TrimEnd().Replace("{", "").Replace("}", "").Replace(command, "");
+            return string.IsNullOrEmpty(timeSpan) ? 0 : int.Parse(timeSpan);
+        }
+
+        /// <summary>
+        /// 读单个参数值
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        public string GetSingleParamValue(int id)
+        {
+            var command = "{RP" + id + "}";
+            var returnData = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            return result;
+        }
+
+        /// <summary>
+        /// 读单个参数值
+        /// </summary>
+        /// <param name="id"></param>
+        /// <returns></returns>
+        public async Task<string> GetSingleParamValueAsync(int id)
+        {
+            var command = "{RP" + id + "}";
+            var returnData =await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+
+            string result = Encoding.ASCII.GetString(returnData);
+            return result.TrimEnd();
+        }
+
+        /// <summary>
+        /// 设置IP地址
+        /// </summary>
+        /// <param name="ip"></param>
+        /// <param name="subNetMask"></param>
+        /// <param name="port"></param>
+        /// <returns></returns>
+        public async Task SetIpAddressAsync(string ip, string subNetMask, int port)
+        {
+            var ipSplits = ip.Split('.');
+            var subNetMaskSplits = subNetMask.Split('.');
+            var list = ipSplits.ToList();
+            list.AddRange(subNetMaskSplits);
+            list.Add(port.ToString());
+
+            var commandId = 13;
+            foreach (var command in list.Select(item => "{WP" + $"{commandId}={item}" + "}"))
+            {
+                var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+                string result = Encoding.ASCII.GetString(returnData);
+                commandId++;
+            }
+
+            string saveCommand = "{DF}";
+            var returnData1 = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(saveCommand));
+            string result1 = Encoding.ASCII.GetString(returnData1);
+            saveCommand = "{DG}";
+            returnData1 = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(saveCommand));
+            result1 = Encoding.ASCII.GetString(returnData1);
+        }
+
+        /// <summary>
+        /// 设置IP地址
+        /// </summary>
+        /// <param name="ip"></param>
+        /// <param name="subNetMask"></param>
+        /// <param name="port"></param>
+        public void SetIpAddress(string ip, string subNetMask, int port)
+        {
+            var ipSplits = ip.Split('.');
+            var subNetMaskSplits = subNetMask.Split('.');
+            var list = ipSplits.ToList();
+            list.AddRange(subNetMaskSplits);
+            list.Add(port.ToString());
+            var commandId = 13;
+            foreach (var result in list.Select(item => "{WP" + $"{commandId}={item}" + "}")
+                .Select(command => Encoding.ASCII.GetString(WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(command)))))
+            {
+                commandId++;
+            }
+
+            const string saveCommand = "{DG}";
+            var result1 = WaitClient.SendThenReturn(Encoding.ASCII.GetBytes(saveCommand));
+        }
+
+        /// <summary>
+        /// 获取输入触发参数
+        /// </summary>
+        /// <param name="i"></param>
+        /// <returns></returns>
+        /// <exception cref="IndexOutOfRangeException"></exception>
+        public async Task<int> GetInputTrigger(int i)
+        {
+            if (i > 2 || i < 0)
+            {
+                throw new IndexOutOfRangeException("输入的参数id{i}超出了索引");
+            }
+            var param = await GetSingleParamValueAsync(40 + i - 1);
+            var value1 = param.Replace("{", "");
+            value1 = value1.Replace("}", "").Split(':')[1];
+            return int.Parse(value1);
+
+        }
+
+        /// <summary>
+        /// 设置输入触发参数
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        /// <exception cref="IndexOutOfRangeException"></exception>
+        public async Task SetInputTrigger(int id, int value)
+        {
+            if (id > 2 || id < 0)
+            {
+                throw new IndexOutOfRangeException("输入的参数id{i}超出了索引");
+            }
+            var commandId = 39 + id;
+            var command = "{WP" + $"{commandId}={value}" + "}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(command));
+            //const string saveCommand = "{DG}";
+            //returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(saveCommand));
+        }
+
+        /// <summary>
+        /// 将所有参数存储至非易失内存中
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public async Task SaveAllSetAsync()
+        {
+            string sendCommand = "{DF}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            if (result.TrimEnd() != sendCommand.TrimEnd())
+            {
+                throw new Exception("FFFeeder响应不正确");
+            }
+        }
+
+        /// <summary>
+        /// 将全局参数存储至非易失内存中
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public async Task SaveGlobalSetAsync()
+        {
+            string sendCommand = "{DG}";
+            var returnData = await WaitClient.SendThenReturnAsync(Encoding.ASCII.GetBytes(sendCommand));
+            string result = Encoding.ASCII.GetString(returnData);
+            if (result.TrimEnd() != sendCommand.TrimEnd())
+            {
+                throw new Exception("FFFeeder响应不正确");
+            }
+        }
+        #endregion
+
+        /// <summary>
+        /// 断开连接,释放资源
+        /// </summary>
+        public void Dispose()
+        {
+            TcpClient.Close();
+            TcpClient.Dispose();
+        }
+
+        /// <summary>
+        /// 成功连接到服务器
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ConnectedVoid(ITcpClient client, ConnectedEventArgs e)
+        {
+            FeederConnectedEvent?.Invoke(this.Id, client,e);
+            FeederModel = GetFeederModel();
+            //Console.WriteLine($"{client.RemoteIPHost.EndPoint.ToString()}已连接!");
+            return EasyTask.CompletedTask;
+        }
+
+        /// <summary>
+        /// 从服务器断开连接,当连接不成功时不会触发。
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task DisconnectedVoid(ITcpClient client, ClosedEventArgs e)
+        {
+            FeederDisconnectedEvent?.Invoke(this.Id, client,e);
+            //Console.WriteLine($"{client.IP}断开连接!");
+            return EasyTask.CompletedTask;
+        }
+
+        /// <summary>
+        /// 获取Feeder型号
+        /// </summary>
+        /// <returns></returns>
+        public FeederModel GetFeederModel()
+        {
+            try
+            {
+                string res = GetSingleParamValue(30);
+                if (int.TryParse(res,out int model))
+                {
+                    switch (model)
+                    {
+                        case 120:
+                            return FeederModel.FF120;
+                        case 240:
+                            return FeederModel.FF240;
+                        case 380:
+                            return FeederModel.FF380;
+                        case 530:
+                            return FeederModel.FF530;
+                        default:
+                            return FeederModel.Unknown;
+                    }
+                }
+                else
+                {
+                    return FeederModel.Unknown;
+                }
+            }
+            catch (Exception)
+            {
+                return FeederModel.Unknown;
+            }
+        }
+
+        /// <summary>
+        /// 获取Feeder型号
+        /// </summary>
+        /// <returns></returns>
+        public async Task<FeederModel> GetFeederModelAsync()
+        {
+            try
+            {
+                string res =await GetSingleParamValueAsync(30);
+                if (int.TryParse(res, out int model))
+                {
+                    switch (model)
+                    {
+                        case 120:
+                            return FeederModel.FF120;
+                        case 240:
+                            return FeederModel.FF240;
+                        case 380:
+                            return FeederModel.FF380;
+                        case 530:
+                            return FeederModel.FF530;
+                        default:
+                            return FeederModel.Unknown;
+                    }
+                }
+                else
+                {
+                    return FeederModel.Unknown;
+                }
+            }
+            catch (Exception)
+            {
+                return FeederModel.Unknown;
+            }
+        }
+    }
+}

+ 221 - 0
Team.FFFeederService/VibrationFrequencyDetector .cs

@@ -0,0 +1,221 @@
+using Newtonsoft.Json.Linq;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService
+{
+    public class VibrationFrequencyDetector : IDisposable
+    {
+        /// <summary>
+        /// C++ DLL结构体对应C#版本
+        /// </summary>
+        [StructLayout(LayoutKind.Sequential)]
+        public struct ST_APAFedColC
+        {
+            public int inFedAct;
+
+            public UInt16 u16VoiMot0;
+            public UInt16 u16VoiMot1;
+            public UInt16 u16VoiMot2;
+            public UInt16 u16VoiMot3;
+            public UInt16 u16VoiMot4;
+            public UInt16 u16VoiMot5;
+            public UInt16 u16VoiMot6;
+            public UInt16 u16VoiMot7;
+            public UInt16 u16VoiMot8;
+            public UInt16 u16VoiMot9;
+            public UInt16 u16VoiMotA;
+            public UInt16 u16VoiMotB;
+            public UInt16 u16VoiMotC;
+            public UInt16 u16VoiMotD;
+            public UInt16 u16VoiMotE;
+            public UInt16 u16VoiMotF;
+
+            public UInt16 u16DuartTim;
+        }
+
+        [StructLayout(LayoutKind.Sequential)]
+        public struct ST_APAMateInf
+        {
+            public float fMatePosX;
+            public float fMatePosY;
+            public int Sta;
+        }
+
+        [StructLayout(LayoutKind.Sequential)]
+        public struct ST_APAParamRe
+        {
+            public int Sta;
+            public UInt16 u16MinAmp;
+            public UInt16 u16MaxAmp;
+            public UInt16 u16MinFre;
+            public UInt16 u16MaxFre;
+            public UInt16 u16Tim;
+        }
+
+        // 委托定义 - 对应C++回调函数
+        public delegate int APAFedColCallback(ST_APAFedColC stFecColC);
+        public delegate ST_APAMateInf APACoordReCallback();
+        public delegate int APALogicAdjEndCallback(int enAdjSta);
+
+        // 存储回调引用以防止垃圾回收
+        /// <summary>
+        /// Feeder动作执行结果回调
+        /// </summary>
+        private APAFedColCallback _fedColCallback;
+        private APACoordReCallback _coordReCallback;
+        private APALogicAdjEndCallback _logicAdjEndCallback;
+
+        // DLL导入
+        private const string DllName = "AutoParaADJ.dll";
+
+        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+        private static extern int APATask();
+
+        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+        private static extern int APAInit(
+            APACoordReCallback VisCoor_cb,
+            APAFedColCallback FedCol_cb,
+            APALogicAdjEndCallback LogEnd_cb,
+            int FedType,
+            int enAct);
+
+        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+        private static extern int APALogicStaCol(int Sta);
+
+        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+        private static extern int APALogicParamSet(
+            ushort u16MinAmp,
+            ushort u16MaxAmp,
+            ushort u16MinFre,
+            ushort u16MaxFre,
+            ushort u16Tim);
+
+        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+        private static extern ST_APAParamRe APALogicParamRe();
+
+        // 事件 - 用于向C#代码传递回调数据
+        /// <summary>
+        /// 设置振动参数并执行动作后的回调事件
+        /// </summary>
+        public event Action<ST_APAFedColC> OnExecuteFeedervibration;
+        /// <summary>
+        /// 相机拍照获取物料位置回调事件
+        /// </summary>
+        /// <returns></returns>
+        public delegate Tuple<bool, float, float> ExecutePhotoDelegate();
+        public event ExecutePhotoDelegate OnExecutePhoto;
+
+        /// <summary>
+        /// 逻辑调整结束回调事件,0 :失败 1:运行中 3:完成调频 6:验证结束
+        /// </summary>
+        public event Action<int> OnExecuteResult;
+
+        /// <summary>
+        /// 初始化振动检测器
+        /// </summary>
+        /// <param name="fedType">Feeder类型</param>
+        /// <param name="enAct">动作编号</param>
+        /// <returns>初始化结果</returns>
+        public bool Initialize(int fedType, int enAct)
+        {
+            // 创建并保存回调委托实例
+            _coordReCallback = onExecutePhoto;
+
+            _fedColCallback = (ST_APAFedColC stFecColC) =>
+            {
+                OnExecuteFeedervibration?.Invoke(stFecColC);
+                return 1; // 返回成功
+            };
+
+            _logicAdjEndCallback = (int enAdjSta) =>
+            {
+                OnExecuteResult?.Invoke(enAdjSta);
+                return 1; // 返回成功
+            };
+
+            // 调用DLL初始化函数
+            int result = APAInit(_coordReCallback, _fedColCallback, _logicAdjEndCallback, 1, enAct);
+            return result == 1; // 假设0表示成功
+        }
+
+        /// <summary>
+        /// 启动振动检测任务
+        /// </summary>
+        /// <returns>任务启动结果</returns>
+        public bool StartTask()
+        {
+            int result = APATask();
+            return result == 0; // 假设0表示成功
+        }
+
+        /// <summary>
+        /// 设置逻辑参数
+        /// </summary>
+        /// <param name="minAmplitude">最小振幅</param>
+        /// <param name="maxAmplitude">最大振幅</param>
+        /// <param name="minFrequency">最小频率</param>
+        /// <param name="maxFrequency">最大频率</param>
+        /// <returns>设置结果</returns>
+        public bool SetLogicParameters(ushort minAmplitude, ushort maxAmplitude,
+                                      ushort minFrequency, ushort maxFrequency, ushort durationValue)
+        {
+            int result = APALogicParamSet(minAmplitude, maxAmplitude, minFrequency, maxFrequency, durationValue);
+            return result == 0; // 假设0表示成功
+        }
+
+        /// <summary>
+        /// 获取逻辑参数
+        /// </summary>
+        /// <param name="minAmplitude">最小振幅</param>
+        /// <param name="maxAmplitude">最大振幅</param>
+        /// <param name="minFrequency">最小频率</param>
+        /// <param name="maxFrequency">最大频率</param>
+        /// <returns>获取结果</returns>
+        public ST_APAParamRe GetLogicParameters()
+        {
+            ST_APAParamRe result = APALogicParamRe();
+            return result;
+        }
+
+        /// <summary>
+        /// 设置逻辑状态,0:停止 1 :启动 2:验证 3:结束
+        /// </summary>
+        /// <param name="state">状态值</param>
+        /// <returns>设置结果</returns>
+        public bool SetLogicState(int state)
+        {
+            int result = APALogicStaCol(state);
+            return result == 0; // 假设0表示成功
+        }
+
+        /// <summary>
+        /// 释放资源
+        /// </summary>
+        public void Dispose()
+        {
+            // 清理回调引用
+            _fedColCallback = null;
+            _coordReCallback = null;
+            _logicAdjEndCallback = null;
+
+            // 其他清理工作...
+        }
+
+        private ST_APAMateInf onExecutePhoto()
+        {
+            var res = OnExecutePhoto?.Invoke();
+
+            return new ST_APAMateInf
+            {
+                fMatePosX = res.Item2,
+                fMatePosY = res.Item3,
+                Sta = res.Item1 ? 1 : 0
+            };
+        }
+    }
+}

+ 445 - 0
Team.FFFeederService/aflexCommunicationClass.cs

@@ -0,0 +1,445 @@
+/*********************************************************************
+ *
+ *	Afag Telnet C# Integration Sample Header
+ *
+ *********************************************************************
+ * FileName:        aflexCommunicationClass.cs
+ * Dependencies:    aflex_CSharp_Integration_Sample
+ * Company:         ima-tec GmbH
+ *
+ * Software License Agreement
+ *
+ *
+ * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
+ * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
+ * LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
+ * AFAG BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
+ * CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
+ * PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
+ * BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
+ * THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
+ * SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
+ * (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
+ *
+ *
+ ********************************************************************/
+
+
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+
+namespace aflex_CSharp_Integration_Sample {
+    class aflexCommunicationClass {
+
+        //the target Values are the aflex Input values
+        private UInt16 pr_target_direction;
+        private UInt16 pr_target_intensity;
+        private UInt16 pr_target_auxPowerOut;
+        private Byte pr_target_ConfigNumber;
+        private Byte pr_target_GeneralRelease;
+        private Byte pr_target_ControllerRestart;
+
+
+        //The actual device Values are the aflex Output values
+        private UInt16 pr_actual_direction;
+        private UInt16 pr_actual_intensity;
+        private UInt16 pr_actual_auxPowerOut;
+        private Byte pr_actual_ConfigNumber;
+        private Byte pr_actual_AutoMode;
+        private Byte pr_actual_GeneralRelease;
+        private Byte pr_actual_ControllerRestart;
+
+        //Bitoffset of the Values
+        private const Byte pr_BitOff_direction = 48;
+        private const Byte pr_BitOff_intensity = 64;
+        private const Byte pr_BitOff_auxPowerOut = 8;
+        private const Byte pr_BitOff_ConfigNumber = 0;
+        private const Byte pr_BitOff_AutoMode = 32;
+        private const Byte pr_BitOff_GeneralRelease = 40;
+        private const Byte pr_BitOff_ControllerRestart = 24;
+
+
+        //The aflex ControlUnit TelnetServer doesn't transmit a new package each time a value changed.
+        //So the Client has to poll the aflex Outputs to detect the changes. For this the following TimeSpan are used.
+        private TimeSpan pr_sync_direction= new TimeSpan();
+        private TimeSpan pr_sync_intensity = new TimeSpan();
+        private TimeSpan pr_sync_auxPowerOut = new TimeSpan();
+        private TimeSpan pr_sync_ConfigNumber= new TimeSpan();
+        private TimeSpan pr_sync_AutoMode = new TimeSpan();
+        private TimeSpan pr_sync_GeneralRelease = new TimeSpan();
+        private TimeSpan pr_sync_ControllerRestart = new TimeSpan();
+
+        private const int TimerPeriod = 10; //fixed timer period in Milliseconds. Adjust that value due the Application requirements
+        private TimeSpan tick = new TimeSpan(0, 0, 0, 0, TimerPeriod); //Timespan to Add each Timer tick
+        private TimeSpan pr_MaxSync = new TimeSpan(0,0,0,0,100);  //Timespan for polling the aflex Outputs. Adjust that value due the Application requirements, max value "ticks" * 7!
+        private Timer objSyncTimer; //Timer for polling 
+        
+        public TCPCommunicationClass objTelnetConnection; //connection interface
+        private bool pr_b_LoggedIn; //Telnet Client logged in
+        private bool pr_b_HBT; //Heartbeat state of the Telnet Server
+
+        /// <summary>
+        /// Occurs when a aflex value is recieved. Transmit the PropertyName as string. 
+        /// </summary>
+        public event EventHandler aflexValueChanged; 
+
+
+        /// <summary>
+        /// This Timer is used for cyclic polling the aflex outputs. TimerPeriod should be adjust due the Application requirements. 
+        /// </summary>
+        /// <param name="state"></param>
+        private void  objSyncTimer_Tick(object state) {
+            if (pr_b_LoggedIn) {
+                pr_sync_direction = pr_sync_direction.Add(tick); 
+                pr_sync_intensity= pr_sync_intensity.Add(tick);
+                pr_sync_auxPowerOut = pr_sync_auxPowerOut.Add(tick);
+                pr_sync_ConfigNumber = pr_sync_ConfigNumber.Add(tick);
+                pr_sync_AutoMode = pr_sync_AutoMode.Add(tick);
+                pr_sync_GeneralRelease = pr_sync_GeneralRelease.Add(tick);
+                pr_sync_ControllerRestart =pr_sync_ControllerRestart.Add(tick);
+
+                //only send one "GO" command each tick --> return. The pr_sync_XXXX Timespan is reset when reading the "RO" input command from the Server. 
+                //So take care that the pr_MaxSync greater than "tick" * 7.
+                if (pr_sync_AutoMode > pr_MaxSync) {
+                    objTelnetConnection.SendCommand("GO " + pr_BitOff_AutoMode);              
+                    return; //only send one Command each Tick
+                }
+                if (pr_sync_GeneralRelease > pr_MaxSync) {
+                    objTelnetConnection.SendCommand("GO " + pr_BitOff_GeneralRelease);
+                    return; //only send one Command each Tick
+                }
+                if(pr_sync_intensity > pr_MaxSync) {
+                    objTelnetConnection.SendCommand("GO " + pr_BitOff_intensity);
+                    return; //only send one Command each Tick
+                }
+                if (pr_sync_auxPowerOut > pr_MaxSync) {
+                    objTelnetConnection.SendCommand("GO " + pr_BitOff_auxPowerOut);
+                    return; //only send one Command each Tick
+                }
+                if (pr_sync_ConfigNumber > pr_MaxSync) {
+                    objTelnetConnection.SendCommand("GO " + pr_BitOff_ConfigNumber);
+                    return; //only send one Command each Tick
+                }
+                if (pr_sync_ControllerRestart > pr_MaxSync) {
+                    objTelnetConnection.SendCommand("GO " + pr_BitOff_ControllerRestart);
+                    return; //only send one Command each Tick
+                }
+                if (pr_sync_direction > pr_MaxSync) {
+                    objTelnetConnection.SendCommand("GO " + pr_BitOff_direction);
+                    return; //only send one Command each Tick
+                }
+            }
+        }
+
+
+        public aflexCommunicationClass() {
+            objSyncTimer = new Timer(objSyncTimer_Tick, null, TimerPeriod, TimerPeriod); 
+            objTelnetConnection = new TCPCommunicationClass();
+            objTelnetConnection.ResultReceived += ObjTelnetConnection_ResultReceived;
+            objTelnetConnection.ConnectionAbort += ObjTelnetConnection_ConnectionAbort;
+        }
+
+        private void ObjTelnetConnection_ConnectionAbort(object sender, EventArgs e) {
+            this.pr_b_LoggedIn = false;
+            if (aflexValueChanged != null) aflexValueChanged("LoggedIn", new EventArgs());
+        }
+
+        /// <summary>
+        /// check the RX string for valid commands
+        /// </summary>
+        /// <param name="Result">input string</param>
+        private void ObjTelnetConnection_ResultReceived(string Result) {
+            if (Result != null) {
+                string[] array_result = Result.Split(' '); //split with separator "space"
+                string str_PropertyName = String.Empty;
+                if (Result.Contains("\r\nTU")) { //Welcome String of Telnet server
+                    objTelnetConnection.SendCommand("admin");
+                } else {
+                    if (array_result.Length == 1) { //TU & TP are the only commands with Lengt == 1
+                        switch (array_result[0]) { //after the TCP/IP connection is established the client has to log in on the Server. This is request by the server with the commands "TU" and "TP". 
+                            case "TU": //Type User to login to TelnetServer
+                                objTelnetConnection.SendCommand("admin");
+                                break;
+                            case "TP": //Type Password of TelnetServer
+                                objTelnetConnection.SendCommand("TelnetServer");
+                                break;
+                        }
+                    } else if (array_result.Length > 1) { //all other Commands Length > 1
+                        switch (array_result[0]) {
+                            case "RO": //Read Output 
+                                str_PropertyName = readRxValue(array_result);
+                                break;
+                            case "AK": //ACK from Set Input Command
+                                str_PropertyName = readRxValue(array_result);
+                                break;
+                            case "ER": //Errorcode
+                                str_PropertyName = "ER:" + array_result[1];
+                                break;
+                            case "LI": //Login/Logout response  
+                                if (Convert.ToByte(array_result[1]) == 1) {
+                                    pr_b_LoggedIn = true; //Now we can transfer aflex commands to the server
+                                } else {
+                                    pr_b_LoggedIn = false; 
+                                }
+                                str_PropertyName = "LoggedIn";
+                                break;
+
+                            case "HBT": //Heartbeat only for visualisation
+                                pr_b_HBT = array_result[1] == "1" ? true : false;
+                                str_PropertyName = "HBT";
+                                break;
+                        }                 
+                    }
+                }
+                if (aflexValueChanged != null) aflexValueChanged(str_PropertyName, new EventArgs());
+            }
+        }
+
+
+        /// <summary>
+        /// detect the RX commands and get the values
+        /// </summary>
+        /// <param name="Input">Rx input string array</param>
+        /// <returns>PropertyName as string</returns>
+        private string readRxValue(string[] Input) {
+            if (Input.Length >= 2) { 
+                switch (Convert.ToByte(Input[1])) { 
+                    case pr_BitOff_AutoMode:
+                        pr_actual_AutoMode = Convert.ToByte(Input[2]);
+                        pr_sync_AutoMode = pr_sync_AutoMode.Subtract(pr_sync_AutoMode); //Reset Sync Timespan
+                        return "AutoMode";
+                    case pr_BitOff_auxPowerOut:
+                        pr_actual_auxPowerOut = Convert.ToUInt16(Input[2]);
+                        pr_sync_auxPowerOut = pr_sync_auxPowerOut.Subtract(pr_sync_auxPowerOut); //Reset Sync Timespan
+                        return "AuxPowerOut";
+                    case pr_BitOff_ConfigNumber:
+                        pr_actual_ConfigNumber = Convert.ToByte(Input[2]);
+                        pr_sync_ConfigNumber = pr_sync_ConfigNumber.Subtract(pr_sync_ConfigNumber); //Reset Sync Timespan
+                        return "ConfigNumber";
+                    case pr_BitOff_ControllerRestart:
+                        pr_actual_ControllerRestart = Convert.ToByte(Input[2]);
+                        pr_sync_ControllerRestart = pr_sync_ControllerRestart.Subtract(pr_sync_ControllerRestart); //Reset Sync Timespan
+                        if (pr_actual_ControllerRestart != 0 && pr_target_ControllerRestart != 0) {
+                            pr_target_ControllerRestart = 0;
+                            objTelnetConnection.SendCommand("SI " + pr_BitOff_ControllerRestart + " " + pr_target_ControllerRestart); //After setting ControllerRestart, reset the Command to start the Restart. 
+                        }
+                        return "ControllerRestart";
+                    case pr_BitOff_direction:
+                        pr_actual_direction = Convert.ToUInt16(Input[2]);
+                        pr_sync_direction = pr_sync_direction.Subtract(pr_sync_direction); //Reset Sync Timespan
+                        return "Direction";
+                    case pr_BitOff_GeneralRelease:
+                        pr_actual_GeneralRelease = Convert.ToByte(Input[2]);
+                        pr_sync_GeneralRelease = pr_sync_GeneralRelease.Subtract(pr_sync_GeneralRelease); //Reset Sync Timespan
+                        return "GeneralRelease";
+                    case pr_BitOff_intensity:
+                        pr_actual_intensity = Convert.ToUInt16(Input[2]);
+                        pr_sync_intensity = pr_sync_intensity.Subtract(pr_sync_intensity); //Reset Sync Timespan
+                        return "Intensity";
+                }
+            }
+            return String.Empty; 
+        }
+
+
+        #region Commands
+        /// <summary>
+        /// Establish the connetion to the Telnet Server
+        /// </summary>
+        /// <param name="IPAdress">IP Adress of the ControlUnit</param>
+        /// <param name="Port">Port that is configured in the ControlUnit (default Port 23) </param>
+        public bool Connect(IPAddress IPAdress,int Port) {
+            return this.objTelnetConnection.Connect(IPAdress, Port); 
+        }
+
+        /// <summary>
+        /// disconnects from Telnet Server
+        /// </summary>
+        public void Disconnect() {
+            this.pr_b_LoggedIn = false;
+            this.objTelnetConnection.Disconnect();
+        }
+
+
+        /// <summary>
+        /// Calculates the target direction and transmits the value to the aflex
+        /// </summary>
+        /// <param name="Degree">Direction [°]: 0-360 allowed</param>
+        public void SetDirection (double Degree) {
+            //Direction Value = (MaxValue / 360) * target dircetion (user manual 6.6.1) 
+            //MaxValue (16Bit) = 65535 
+            if (pr_b_LoggedIn) {
+                //Calculate UINT16 Value 7
+                if (Degree <= 360.0 && Degree >= 0.0) {
+                    pr_target_direction = (UInt16)((UInt16.MaxValue / 360.0) * Degree);
+                    objTelnetConnection.SendCommand("SI " + pr_BitOff_direction + " " + pr_target_direction);
+                }
+            }
+        }
+
+        /// <summary>
+        /// Calculates the target intensity and transmit value to the aflex 
+        /// </summary>
+        /// <param name="Intensity">Intensity [%]:  0-100 allowed</param>
+        public void SetIntensity(double Intensity) {
+            //Intensity Value = (MaxValue / 100%) * target direction[%] (user manual 6.6.1) 
+            //MaxValue (16Bit) = 65535 
+            if (pr_b_LoggedIn) {
+                if (Intensity <= 100.0 && Intensity >= 0.0) {
+                    pr_target_intensity = (UInt16)((UInt16.MaxValue / 100.0) * Intensity);
+                    objTelnetConnection.SendCommand("SI " + pr_BitOff_intensity + " " + pr_target_intensity);
+                }      
+            }
+        }
+
+        /// <summary>
+        /// Set the general release of the ControlUnit 
+        /// </summary>
+        /// <param name="Value">true = release | false = inhibit</param>
+        public void SetGeneralRelease (bool Value) {
+            if (pr_b_LoggedIn) {
+                if (Value) pr_target_GeneralRelease = Byte.MaxValue;
+                else pr_target_GeneralRelease = 0;
+                objTelnetConnection.SendCommand("SI " + pr_BitOff_GeneralRelease + " " + pr_target_GeneralRelease); 
+            }
+        }
+
+        /// <summary>
+        /// Calculates the target AuxPowerOutput of the ControlUnit and transmitt it. (AuxPowerOut --> Backlight) 
+        /// </summary>
+        /// <param name="Intensity">Intensity [%]:  0-100 allowed</param>
+        public void SetAuxPowerOut(double Intensity) {
+            //Intensity Value = (MaxValue / 100%) * target direction[%] (user manual 6.6.1) 
+            //MaxValue (16Bit) = 65535 
+            if (pr_b_LoggedIn) {
+                if (Intensity <= 100.0 && Intensity >= 0.0) {
+                    pr_target_auxPowerOut = (UInt16)((UInt16.MaxValue / 100.0) * Intensity);
+                    objTelnetConnection.SendCommand("SI " + pr_BitOff_auxPowerOut + " " + pr_target_auxPowerOut);
+                }
+            }
+        }
+
+
+        /// <summary>
+        /// Load a aflexConfiguration
+        /// </summary>
+        /// <param name="ConfigNumber">Config number to load. 1-49 allowed</param>
+        public void LoadConfiguration(byte ConfigNumber) {
+            if (pr_b_LoggedIn) {
+                if (ConfigNumber < 50 && ConfigNumber > 0) {
+                    pr_target_ConfigNumber = ConfigNumber;
+                    objTelnetConnection.SendCommand("SI " + pr_BitOff_ConfigNumber + " " + pr_target_ConfigNumber);
+                }
+            }
+        }
+
+        /// <summary>
+        /// restart the ControlUnit. Telnet connection will be lost. Manual reconnect required.
+        /// </summary>
+        public void RestartController() {
+            if (pr_b_LoggedIn) {
+                    pr_target_ControllerRestart = Byte.MaxValue; 
+                    objTelnetConnection.SendCommand("SI " + pr_BitOff_ControllerRestart + " " + pr_target_ControllerRestart);
+            }
+        }
+        #endregion
+
+
+        #region Get/Set 
+      /// <summary>
+      /// Client logged in on the Telnet Server
+      /// </summary>
+        public bool LoggedIn {
+            get {
+                return pr_b_LoggedIn; 
+            }
+        }
+
+        /// <summary>
+        /// actual state of the Telnet Hearbeat. Toggles if connection established
+        /// </summary>
+        public bool HeartbeatState {
+            get {
+                return pr_b_HBT; 
+            }
+        }
+
+        /// <summary>
+        /// actual aflex intensity as double [%] 0-100%
+        /// </summary>
+        public double actual_intensity {
+            get {
+                return (double)((pr_actual_intensity * 100.0 / UInt16.MaxValue)); 
+            }
+        }
+
+
+        /// <summary>
+        /// actual aflex direction as double [°] 0-360°
+        /// </summary>
+        public double actual_direction {
+            get {
+                return (double)((pr_actual_direction * 360.0 / UInt16.MaxValue));  //Convert uint16 value to double [°] 
+            }
+        }
+
+
+        /// <summary>
+        /// actual ControlUnit auxPowerOutput as double [%] 0-100%
+        /// </summary>
+        public double actual_auxPowerOut {
+            get {
+                return (double)((pr_actual_auxPowerOut * 100.0 / UInt16.MaxValue)); 
+            }
+        }
+
+
+        /// <summary>
+        /// actual aflex Configuration Number as byte. 
+        /// </summary>
+        public byte actual_ConfigNumber {
+            get {
+                return pr_actual_ConfigNumber; 
+            }
+        }
+
+
+        /// <summary>
+        /// actual ControlUnit AutoMode. False - Manual | True - Automatic
+        /// </summary>
+        public bool actual_AutoMode {
+            get {
+                return pr_actual_AutoMode > 0 ? true : false; 
+            }
+        }
+
+        /// <summary>
+        /// actual ControlUnit General Release. False - inhibit | True - released (if inhibit all power outputs are blocked) 
+        /// </summary>
+        public bool actual_GeneralRelease {
+            get {
+                return pr_actual_GeneralRelease > 0 ? true : false;
+            }
+        }
+
+
+        /// <summary>
+        /// actual ControlUnit Restart bool
+        /// </summary>
+        public bool actual_ControllerRestart {
+            get {
+                return pr_actual_ControllerRestart > 0 ? true : false;
+            }
+        }
+        #endregion 
+    }
+
+}

+ 23 - 0
Team.FFFeederService/app.config

@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+  <runtime>
+    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+      <dependentAssembly>
+        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.5.0" newVersion="4.0.5.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.2.4.0" newVersion="4.2.4.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.5.0" newVersion="4.0.5.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-6.0.3.0" newVersion="6.0.3.0" />
+      </dependentAssembly>
+    </assemblyBinding>
+  </runtime>
+</configuration>

+ 15 - 0
Team.FFFeederService/packages.config

@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
+  <package id="System.Buffers" version="4.6.1" targetFramework="net48" />
+  <package id="System.Drawing.Common" version="9.0.9" targetFramework="net48" />
+  <package id="System.Memory" version="4.6.3" targetFramework="net48" />
+  <package id="System.Numerics.Vectors" version="4.6.1" targetFramework="net48" />
+  <package id="System.Runtime.CompilerServices.Unsafe" version="6.1.2" targetFramework="net48" />
+  <package id="System.Threading.Tasks.Extensions" version="4.6.3" targetFramework="net48" />
+  <package id="System.ValueTuple" version="4.6.1" targetFramework="net48" />
+  <package id="TouchSocket" version="3.1.17" targetFramework="net48" />
+  <package id="TouchSocket.Core" version="3.1.17" targetFramework="net48" />
+  <package id="ValueConverters" version="3.1.22" targetFramework="net48" />
+  <package id="ValueConverters.Annotations" version="3.1.22" targetFramework="net48" />
+</packages>

+ 31 - 0
TeamAAS-VM.sln

@@ -0,0 +1,31 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.9.34714.143
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TeamAAS-VP", "TeamAAS-VM\TeamAAS-VP.csproj", "{08877F07-4A1C-4530-9105-CF24945AF83C}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Team.FFFeederService", "Team.FFFeederService\Team.FFFeederService.csproj", "{26DA3704-77D7-46A7-8651-684878DAC898}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{08877F07-4A1C-4530-9105-CF24945AF83C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{08877F07-4A1C-4530-9105-CF24945AF83C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{08877F07-4A1C-4530-9105-CF24945AF83C}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{08877F07-4A1C-4530-9105-CF24945AF83C}.Release|Any CPU.Build.0 = Release|Any CPU
+		{26DA3704-77D7-46A7-8651-684878DAC898}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{26DA3704-77D7-46A7-8651-684878DAC898}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{26DA3704-77D7-46A7-8651-684878DAC898}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{26DA3704-77D7-46A7-8651-684878DAC898}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {0207FBE0-0CAE-4BD9-8142-0DE029ED98F9}
+	EndGlobalSection
+EndGlobal

+ 300 - 0
TeamAAS-VM/App.config

@@ -0,0 +1,300 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+  <configSections>
+    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
+    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
+    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
+  </configSections>
+  <appSettings>
+    <!--启动服务形式(0代表默认系统服务, 1代表exe方式启动)-->
+    <add key="StartServerByExe" value="0" />
+    <!--服务绝对路径,用于拉起服务(value为""时默认拉起系统服务,value为服务路径时为以进程方式启动)-->
+    <add key="ServerPath" value="" />
+    <!--<add key="ServerPath" value="E:\Program Files\VisionMaster\VisionMaster4.1.0\Applications\Server\VisionMasterServer.exe"/>-->
+    <add key="ClientSettingsProvider.ServiceUri" value="" />
+  </appSettings>
+  <startup>
+    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
+  </startup>
+  <log4net>
+    <root>
+      <level value="ALL" />
+    </root>
+    <logger name="OperationLog">
+      <level value="INFO" />
+      <appender-ref ref="OperationLogAppender" />
+    </logger>
+    <logger name="ErrorLog">
+      <level value="WARN" />
+      <appender-ref ref="ErrorLogAppender" />
+    </logger>
+    <!--错误日志类-->
+    <logger name="logerror">
+      <!--日志类的名字-->
+      <level value="ALL" />
+      <!--定义记录的日志级别-->
+      <appender-ref ref="ErrorAppender" />
+      <!--记录到哪个介质中去-->
+    </logger>
+    <!--信息日志类-->
+    <logger name="loginfo">
+      <level value="ALL" />
+      <appender-ref ref="InfoAppender" />
+    </logger>
+    <!--调试日志类-->
+    <logger name="logdebug">
+      <!--日志类的名字-->
+      <level value="ALL" />
+      <!--定义记录的日志级别-->
+      <appender-ref ref="DebugAppender" />
+      <!--记录到哪个介质中去-->
+    </logger>
+    <!--警告日志类-->
+    <logger name="logwarn">
+      <!--日志类的名字-->
+      <level value="ALL" />
+      <!--定义记录的日志级别-->
+      <appender-ref ref="WarnAppender" />
+      <!--记录到哪个介质中去-->
+    </logger>
+    <!--重大错误日志类-->
+    <logger name="logfatal">
+      <!--日志类的名字-->
+      <level value="ALL" />
+      <!--定义记录的日志级别-->
+      <appender-ref ref="FatalAppender" />
+      <!--记录到哪个介质中去-->
+    </logger>
+    <!--动态日志类-->
+    <logger name="logDynamic">
+      <level value="ALL" />
+      <appender-ref ref="DynamicAppender" />
+    </logger>
+    <!--定义输出到文件中-->
+    <!--错误日志附加介质-->
+    <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
+      <!-- name属性指定其名称,type则是log4net.Appender命名空间的一个类的名称,意思是,指定使用哪种介质-->
+      <param name="File" value="..\\Log\\LogError\\" />
+      <!--日志输出到exe程序这个相对目录下-->
+      <param name="AppendToFile" value="true" />
+      <!--输出的日志不会覆盖以前的信息-->
+      <param name="MaxSizeRollBackups" value="100" />
+      <!--备份文件的个数-->
+      <param name="MaxFileSize" value="10240" />
+      <!--当个日志文件的最大大小-->
+      <param name="StaticLogFileName" value="false" />
+      <!--是否使用静态文件名-->
+      <param name="DatePattern" value="yyyy-MM\\yyyy-MM-dd&quot;.htm&quot;" />
+      <!--日志文件名-->
+      <param name="RollingStyle" value="Date" />
+      <!--文件创建的方式,这里是以Date方式创建-->
+      <!--错误日志布局-->
+      <layout type="log4net.Layout.PatternLayout">
+        <param name="ConversionPattern" value="&lt;HR COLOR=red&gt;%n异常时间:%d [%t] &lt;BR&gt;%n异常级别:%-5p &lt;BR&gt;%n异 常 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;" />
+      </layout>
+    </appender>
+    <!--重大错误日志附加介质-->
+    <appender name="FatalAppender" type="log4net.Appender.RollingFileAppender">
+      <!-- name属性指定其名称,type则是log4net.Appender命名空间的一个类的名称,意思是,指定使用哪种介质-->
+      <param name="File" value="..\\Log\\LogFatal\\" />
+      <!--日志输出到exe程序这个相对目录下-->
+      <param name="AppendToFile" value="true" />
+      <!--输出的日志不会覆盖以前的信息-->
+      <param name="MaxSizeRollBackups" value="100" />
+      <!--备份文件的个数-->
+      <param name="MaxFileSize" value="10240" />
+      <!--当个日志文件的最大大小-->
+      <param name="StaticLogFileName" value="false" />
+      <!--是否使用静态文件名-->
+      <param name="DatePattern" value="yyyy-MM\\yyyy-MM-dd&quot;.htm&quot;" />
+      <!--日志文件名-->
+      <param name="RollingStyle" value="Date" />
+      <!--文件创建的方式,这里是以Date方式创建-->
+      <!--错误日志布局-->
+      <layout type="log4net.Layout.PatternLayout">
+        <param name="ConversionPattern" value="&lt;HR COLOR=red&gt;%n异常时间:%d [%t] &lt;BR&gt;%n异常级别:%-5p &lt;BR&gt;%n异 常 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;" />
+      </layout>
+    </appender>
+    <!--信息日志附加介质-->
+    <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
+      <param name="File" value="..\\Log\\LogInfo\\" />
+      <param name="AppendToFile" value="true" />
+      <param name="MaxFileSize" value="10240" />
+      <param name="MaxSizeRollBackups" value="100" />
+      <param name="StaticLogFileName" value="false" />
+      <param name="DatePattern" value="yyyy-MM\\yyyy-MM-dd&quot;.txt&quot;" />
+      <param name="RollingStyle" value="Date" />
+      <!--信息日志布局-->
+      <layout type="log4net.Layout.PatternLayout">
+        <!--param name="ConversionPattern" value="&lt;HR COLOR=blue&gt;%n日志时间:%d [%t] &lt;BR&gt;%n日志级别:%-5p &lt;BR&gt;%n日 志 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;"  /-->
+        <param name="ConversionPattern" value="[日志时间:%d] [%t] [%-5p]:%m%n" />
+      </layout>
+    </appender>
+    <!--调试日志附加介质-->
+    <appender name="DebugAppender" type="log4net.Appender.RollingFileAppender">
+      <param name="File" value="..\\Log\\LogDebug\\" />
+      <param name="AppendToFile" value="true" />
+      <param name="MaxFileSize" value="10240" />
+      <param name="MaxSizeRollBackups" value="100" />
+      <param name="StaticLogFileName" value="false" />
+      <param name="DatePattern" value="yyyy-MM\\yyyy-MM-dd&quot;.txt&quot;" />
+      <param name="RollingStyle" value="Date" />
+      <!--信息日志布局-->
+      <layout type="log4net.Layout.PatternLayout">
+        <!--param name="ConversionPattern" value="&lt;HR COLOR=blue&gt;%n日志时间:%d [%t] &lt;BR&gt;%n日志级别:%-5p &lt;BR&gt;%n日 志 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;"  /-->
+        <param name="ConversionPattern" value="[日志时间:%d] [%t] [%-5p]:%m%n" />
+      </layout>
+    </appender>
+    <!--警告日志附加介质-->
+    <appender name="WarnAppender" type="log4net.Appender.RollingFileAppender">
+      <param name="File" value="..\\Log\\LogWarn\\" />
+      <param name="AppendToFile" value="true" />
+      <param name="MaxFileSize" value="10240" />
+      <param name="MaxSizeRollBackups" value="100" />
+      <param name="StaticLogFileName" value="false" />
+      <param name="DatePattern" value="yyyy-MM\\yyyy-MM-dd&quot;.txt&quot;" />
+      <param name="RollingStyle" value="Date" />
+      <!--信息日志布局-->
+      <layout type="log4net.Layout.PatternLayout">
+        <!--param name="ConversionPattern" value="&lt;HR COLOR=blue&gt;%n日志时间:%d [%t] &lt;BR&gt;%n日志级别:%-5p &lt;BR&gt;%n日 志 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;"  /-->
+        <param name="ConversionPattern" value="[日志时间:%d] [%t] [%-5p]:%m%n" />
+      </layout>
+    </appender>
+    <!--动态日志附加介质-->
+    <appender name="DynamicAppender" type="log4net.Appender.RollingFileAppender">
+      <!--输出日志文件的路径-->
+      <param name="File" value="..\\Log\\LogOther\\" />
+      <!--输出日志时自动向后追加-->
+      <param name="AppendToFile" value="true" />
+      <!--防止多线程时不能写Log,官方说线程非安全,但实际使用时,本地测试正常,部署后有不能写日志的情况-->
+      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
+      <param name="MaxFileSize" value="10240" />
+      <param name="MaxSizeRollBackups" value="100" />
+      <param name="StaticLogFileName" value="false" />
+      <param name="DatePattern" value="yyyy-MM\\yyyy-MM-dd&quot;.txt&quot;" />
+      <param name="RollingStyle" value="Date" />
+      <!--输出格式-->
+      <!--样例:[日志时间:2023-11-08 10:56:12,247] [1] [INFO ]:系统启动!-->
+      <!--信息日志布局-->
+      <layout type="log4net.Layout.PatternLayout">
+        <param name="ConversionPattern" value="[日志时间:%d] [%t] [%-5p]:%m%n" />
+      </layout>
+    </appender>
+  </log4net>
+  <system.web>
+    <membership defaultProvider="ClientAuthenticationMembershipProvider">
+      <providers>
+        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
+      </providers>
+    </membership>
+    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
+      <providers>
+        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
+      </providers>
+    </roleManager>
+  </system.web>
+  <runtime>
+    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+      <dependentAssembly>
+        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-6.0.3.0" newVersion="6.0.3.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.2.4.0" newVersion="4.2.4.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.5.0" newVersion="4.0.5.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.5.0" newVersion="4.0.5.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="ExtendedNumerics.BigDecimal" publicKeyToken="65f1315a45ad8949" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3001.0.1.201" newVersion="3001.0.1.201" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="ICSharpCode.SharpZipLib" publicKeyToken="1b03e6acf1164f73" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-1.4.2.13" newVersion="1.4.2.13" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.1.6.0" newVersion="4.1.6.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Text.Encoding.CodePages" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-8.0.0.3" newVersion="8.0.0.3" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Reflection.Metadata" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Enums.NET" publicKeyToken="7ea1c1650d506225" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.CodeAnalysis" publicKeyToken="31bf3856ad364e35" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.14.0.0" newVersion="4.14.0.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.CodeAnalysis.CSharp" publicKeyToken="31bf3856ad364e35" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.14.0.0" newVersion="4.14.0.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.CodeAnalysis.Scripting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.14.0.0" newVersion="4.14.0.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.CodeAnalysis.CSharp.Scripting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.14.0.0" newVersion="4.14.0.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.IO.RecyclableMemoryStream" publicKeyToken="31bf3856ad364e35" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Formats.Asn1" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-1.0.118.0" newVersion="1.0.118.0" />
+      </dependentAssembly>
+    </assemblyBinding>
+  </runtime>
+  <entityFramework>
+    <providers>
+      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
+      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
+    </providers>
+  </entityFramework>
+  <system.data>
+    <DbProviderFactories>
+      <remove invariant="System.Data.SQLite.EF6" />
+      <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
+    <remove invariant="System.Data.SQLite" /><add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /></DbProviderFactories>
+  </system.data>
+</configuration>

+ 49 - 0
TeamAAS-VM/App.xaml

@@ -0,0 +1,49 @@
+<prism:PrismApplication x:Class="TeamAAS_VP.App"
+                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+                        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+                        xmlns:c="clr-namespace:TeamAAS_VP.ValueConverter"
+                        xmlns:wpf="clr-namespace:MaterialDesignThemes.Wpf;assembly=MaterialDesignThemes.Wpf"
+                        xmlns:local="clr-namespace:TeamAAS_VP"
+                        xmlns:prism="http://prismlibrary.com/">
+    <Application.Resources>
+        <ResourceDictionary>
+            <ResourceDictionary.MergedDictionaries>
+                
+                <!--<ResourceDictionary Source="Resources/Languages1/Chinese.xaml" />-->
+                <ResourceDictionary Source="Resources\Styles\DefaultColors.xaml" />
+
+                <ResourceDictionary Source="Resources/FontSize/DefaultFontSize.xaml" />
+
+                <materialDesign:BundledTheme BaseTheme="Inherit"
+                                             PrimaryColor="DeepPurple"
+                                             SecondaryColor="Purple" />
+                <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
+                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
+                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
+                <!-- Theme setting -->
+                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Blue.xaml" />
+                
+                <!--MaterialDesign-->
+                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
+                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesign3.Defaults.xaml" />
+                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
+                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Secondary/MaterialDesignColor.Lime.xaml" />
+                <!--MaterialDesign-->
+
+                <ResourceDictionary Source="pack://application:,,,/ICSharpCode.AvalonEdit;component/themes/generic.xaml" />
+            </ResourceDictionary.MergedDictionaries>
+            <FontFamily x:Key="DefaultFont">Microsoft YaHei</FontFamily>
+            <FontFamily x:Key="CodeFont">/TeamAAS-VM;Component/Resources/Fonts/#JetBrains Mono</FontFamily>
+            <c:StringFormatConverter x:Key="StringFormatConverter" />
+            <c:InvertBooleanConverter x:Key="InvertBooleanConverter" />
+            <c:ObjectToVisibilityConverter x:Key="ObjectToVisibilityConverter" />
+            <c:ObjectToVisibilityConverter x:Key="ObjectToCollapsedConverter"
+                                           Invert="True" />
+            <c:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
+            <c:BooleanToVisibilityConverter x:Key="BooleanToCollapsedConverter"
+                                            Invert="True" />
+        </ResourceDictionary>
+        
+    </Application.Resources>
+</prism:PrismApplication>

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

@@ -0,0 +1,246 @@
+using Prism.Ioc;
+using Prism.Modularity;
+using Prism.Services.Dialogs;
+using Prism.Unity;
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Web.UI.WebControls;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media.Media3D;
+using Team.Utility;
+using TeamAAS_VP.Controls;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Properties;
+using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.ViewModels;
+using TeamAAS_VP.ViewModels.Calibration;
+using TeamAAS_VP.ViewModels.DebugMod;
+using TeamAAS_VP.ViewModels.Home;
+using TeamAAS_VP.ViewModels.Product;
+using TeamAAS_VP.Views;
+using TeamAAS_VP.Views.Calibration;
+using TeamAAS_VP.Views.DebugMod;
+using TeamAAS_VP.Views.Product;
+using TeamAAS_VP.Views.Setting;
+using TeamAAS_VP.Views.User;
+using TeamAAS_VP;
+using WPFLocalizeExtension.Engine;
+
+[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", ConfigFileExtension = "config", Watch = true)]
+namespace TeamAAS_VP
+{
+    /// <summary>
+    /// App.xaml 的交互逻辑
+    /// </summary>
+    public partial class App : PrismApplication
+    {
+        private static System.Threading.Mutex mutex;
+        protected override Window CreateShell()
+        {
+            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+            return base.Container.Resolve<MainWindowView>();
+        }
+
+        protected override void RegisterTypes(IContainerRegistry containerRegistry)
+        {
+            //------------------------注册导航视图------------------------------------------------
+            containerRegistry.RegisterForNavigation<HomeView>();
+            containerRegistry.RegisterForNavigation<ProductsView>();
+            containerRegistry.RegisterForNavigation<DebugView>();
+            containerRegistry.RegisterForNavigation<SettingView>();
+            containerRegistry.RegisterForNavigation<CalibrationView>();
+            containerRegistry.RegisterForNavigation<StatisticsView>();
+            containerRegistry.RegisterForNavigation<UserView>();
+            containerRegistry.RegisterForNavigation<Views.User.LoginView>();
+            containerRegistry.RegisterForNavigation<SignUpView>();
+            containerRegistry.RegisterForNavigation<RobotManualStep>();
+            containerRegistry.RegisterForNavigation<FeederManual>();
+            containerRegistry.RegisterForNavigation<VisionSolution>();
+            containerRegistry.RegisterForNavigation<InchingControl>();
+            containerRegistry.RegisterForNavigation<ScriptHome>();
+            containerRegistry.RegisterForNavigation<FeederClear>();
+            containerRegistry.RegisterForNavigation<AfagFeederManual>();
+
+            //产品
+            containerRegistry.RegisterForNavigation<ProductHome>();
+            containerRegistry.RegisterForNavigation<ProductDescription>();
+            containerRegistry.RegisterForNavigation<ProductProcessManage>();
+            containerRegistry.RegisterForNavigation<ProcessBasics>();
+            containerRegistry.RegisterForNavigation<SimpleProcedure>();
+            containerRegistry.RegisterForNavigation<AdvancedProcedure>();
+            containerRegistry.RegisterForNavigation<CameraParams>();
+            containerRegistry.RegisterForNavigation<FeederParams>();
+            containerRegistry.RegisterForNavigation<ProcedureVisionOutput>();
+            containerRegistry.RegisterForNavigation<RobotPointParams>();
+            containerRegistry.RegisterForNavigation<ProductParams>();
+            containerRegistry.RegisterForNavigation<ProcedureParams>();
+            containerRegistry.RegisterForNavigation<AfagFeederParams>();
+            
+            //校准
+            containerRegistry.RegisterForNavigation<CalibrationAuto>();
+            containerRegistry.RegisterForNavigation<CalibrationBasics>();
+            containerRegistry.RegisterForNavigation<CalibrationCameraParams>();
+            containerRegistry.RegisterForNavigation<CalibrationEditVision>();
+            containerRegistry.RegisterForNavigation<CalibrationHome>();
+            containerRegistry.RegisterForNavigation<CalibrationResult>();
+            containerRegistry.RegisterForNavigation<CalibrationSelectTool>();
+            containerRegistry.RegisterForNavigation<CalibrationTeachCenterPoint>();
+            containerRegistry.RegisterForNavigation<CalibrationVerification>();
+            //**************************************************************************************
+
+            //------------------------注册单类------------------------------------------------
+            containerRegistry.RegisterSingleton<Management>();
+
+            containerRegistry.RegisterSingleton<ShowVisionRenderViewModel>();
+            containerRegistry.RegisterSingleton<InchingControlViewModel>();
+            //containerRegistry.RegisterSingleton<ScriptHomeViewModel>();
+            containerRegistry.RegisterSingleton<DebugViewModel>();
+            containerRegistry.RegisterSingleton<FeederClearViewModel>();
+            containerRegistry.RegisterSingleton<AfagFeederManual>();
+            //产品
+            containerRegistry.RegisterSingleton<ProductDescriptionViewModel>();
+            containerRegistry.RegisterSingleton<ProductHomeViewModel>();
+            containerRegistry.RegisterSingleton<ProductsViewModel>();
+            containerRegistry.RegisterSingleton<ProductProcessManageViewModel>();
+            containerRegistry.RegisterSingleton<ProcessBasicsViewModel>();
+            containerRegistry.RegisterSingleton<SimpleProcedureViewModel>();
+            containerRegistry.RegisterSingleton<AdvancedProcedureViewModel>();
+            containerRegistry.RegisterSingleton<CameraParamsViewModel>();
+            containerRegistry.RegisterSingleton<FeederParamsViewModel>();
+            containerRegistry.RegisterSingleton<ProcedureVisionOutputViewModel>();
+            containerRegistry.RegisterSingleton<RobotPointParamsViewModel>();
+            containerRegistry.RegisterSingleton<ProductParamsViewModel>();
+            containerRegistry.RegisterSingleton<ProcedureParamsViewModel>();
+            containerRegistry.RegisterSingleton<AfagFeederParamsViewModel>();
+            //校准
+            containerRegistry.RegisterSingleton<CalibrationAutoViewModel>();
+            containerRegistry.RegisterSingleton<CalibrationBasicsViewModel>();
+            containerRegistry.RegisterSingleton<CalibrationCameraParamsViewModel>();
+            containerRegistry.RegisterSingleton<CalibrationEditVisionViewModel>();
+            containerRegistry.RegisterSingleton<CalibrationHomeViewModel>();
+            containerRegistry.RegisterSingleton<CalibrationResultViewModel>();
+            containerRegistry.RegisterSingleton<CalibrationSelectToolViewModel>();
+            containerRegistry.RegisterSingleton<CalibrationTeachCenterPointViewModel>();
+            containerRegistry.RegisterSingleton<CalibrationVerificationViewModel>();
+            //**************************************************************************************
+
+            //------------------------注册对话框------------------------------------------------
+            containerRegistry.RegisterDialog<AddRobot>();
+            containerRegistry.RegisterDialog<AddFeeder>();
+            containerRegistry.RegisterDialog<AddPlc>();
+            containerRegistry.RegisterDialog<AddCamera>();
+            containerRegistry.RegisterDialog<EditCamera>();
+            containerRegistry.RegisterDialog<PalletManage>();
+            containerRegistry.RegisterDialog<UProgressBar>();
+            containerRegistry.RegisterDialog<CalibTool>();
+            containerRegistry.RegisterDialog<ShowCalibrationResult>();
+            containerRegistry.RegisterDialog<FeederBlobParams>();
+            containerRegistry.RegisterDialog<CalculateOffsetU>();
+            containerRegistry.RegisterDialog<VisionScriptPage>();
+            containerRegistry.RegisterDialog<SelectCameraBrand>();
+            //**************************************************************************************
+        }
+
+        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
+        {
+            base.ConfigureModuleCatalog(moduleCatalog);
+        }
+
+        protected override void OnStartup(StartupEventArgs e)
+        {
+            OpenCvSharp.Cv2.GetVersionString();
+            var currentDomain = AppDomain.CurrentDomain;
+            currentDomain.UnhandledException += UnhandledExceptionOccured;
+            // 在异常由应用程序引发但未进行处理时发生。主要指的是UI线程。
+            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
+            mutex = new System.Threading.Mutex(true, "Team-AAS-VM");
+            if (mutex.WaitOne(0, false))
+            {
+                //var softKey = new SoftKey();
+                //var ret = softKey.CheckKeyByReadEprom();
+                //if (ret == 0)
+                //{
+                //    LogHelper.WriteLogInfo(Lang.AASLicense正常使用);
+                //}
+                //else
+                //{
+                //    LogHelper.WriteLogInfo(Lang.未检测到正确的AASlicenseusb);
+                //    MessageBox.Show(Lang.未检测到正确的AASlicenseusb, "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
+                //    this.Shutdown();
+                //    return;
+                //}
+
+                //if (Cognex.VisionPro.CogMisc.GetLicensedFeatures(true).Count <= 0)
+                //{
+                //    LogHelper.WriteLogInfo(Lang.未检测到正确的VisionProlicense);
+                //    MessageBox.Show(Lang.未检测到正确的VisionProlicense, "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
+                //    this.Shutdown();
+                //    return;
+                //}
+                var culture = new CultureInfo("zh-CN");
+                App.Current.Dispatcher.Thread.CurrentCulture = culture;
+                App.Current.Dispatcher.Thread.CurrentUICulture = culture;
+                LocalizeDictionary.Instance.Culture = culture;
+                base.OnStartup(e);
+                LogHelper.WriteLogInfo("<<<=====================Team-AAS-VM Startup=====================");
+                try
+                {
+                    if (!RegeditHelper.IsFirstUse())
+                    {
+                        if (File.Exists(FilePath.UserDbPath))
+                        {
+                            File.Delete(FilePath.UserDbPath);
+                        }
+                        if (File.Exists(FilePath.ProductionRecordsDbPath))
+                        {
+                            File.Delete(FilePath.ProductionRecordsDbPath);
+                        }
+                        RegeditHelper.WriteFirstLog();
+                    }
+                    RegeditHelper.WriteAppVersion(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError(Lang.操作注册表时出错, ex);
+                }
+            }
+            else
+            {
+                MessageBox.Show(Lang.程序已经在运行, "AAS",MessageBoxButton.OK,MessageBoxImage.Asterisk);
+                this.Shutdown();
+            }
+        }
+
+        protected override void OnExit(ExitEventArgs e)
+        {
+            LogHelper.WriteLogInfo("=====================Team-AAS-VM End=====================>>>");
+            base.OnExit(e);
+        }
+
+        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
+        {
+            //可以记录日志并转向错误bug窗口友好提示用户
+            e.Handled = true;
+            LogHelper.WriteLogFatal("Application has crashed", e.Exception);
+            MessageBox.Show("Error:" + e.Exception.Message + " " + e.Exception.StackTrace,"AAS",MessageBoxButton.OK,MessageBoxImage.Asterisk);
+        }
+
+        private static void UnhandledExceptionOccured(object sender, UnhandledExceptionEventArgs args)
+        {
+            //全局异常记录
+            var e = (Exception)args.ExceptionObject;
+            LogHelper.WriteLogFatal("Application has crashed", e);
+            MessageBox.Show($"Error: something went wrong and the application must close:{e.ToString()} ", "AAS", MessageBoxButton.OK, MessageBoxImage.Asterisk);
+
+        }
+    }
+}

+ 15 - 0
TeamAAS-VM/Attributes/LocalizationAttribute.cs

@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Attributes
+{
+    [AttributeUsage(AttributeTargets.Field)]
+    public class LocalizationAttribute : Attribute
+    {
+        public string ResourceName { get; set; } 
+        public Type ResourceType { get; set; } 
+    }
+}

+ 92 - 0
TeamAAS-VM/Behaviors/ComboBoxSelectionBehavior.cs

@@ -0,0 +1,92 @@
+using Microsoft.Xaml.Behaviors;
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+
+namespace TeamAAS_VP.Behaviors
+{
+    public class ComboBoxSelectionBehavior : Behavior<ComboBox>
+    {
+
+        // 定义一个依赖属性,用于绑定命令
+        public static readonly DependencyProperty UserSelectionCommandProperty =
+            DependencyProperty.Register(
+                nameof(UserSelectionCommand),
+                typeof(ICommand),
+                typeof(ComboBoxSelectionBehavior));
+
+        public ICommand UserSelectionCommand
+        {
+            get => (ICommand)GetValue(UserSelectionCommandProperty);
+            set => SetValue(UserSelectionCommandProperty, value);
+        }
+
+        // 定义 CommandParameter 依赖属性
+        public static readonly DependencyProperty CommandParameterProperty =
+            DependencyProperty.Register(
+                nameof(CommandParameter),
+                typeof(object),
+                typeof(ComboBoxSelectionBehavior));
+
+        public object CommandParameter
+        {
+            get => GetValue(CommandParameterProperty);
+            set => SetValue(CommandParameterProperty, value);
+        }
+
+        protected override void OnAttached()
+        {
+            base.OnAttached();
+            AssociatedObject.SelectionChanged += OnSelectionChanged;
+            AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
+            AssociatedObject.PreviewMouseWheel += OnPreviewMouseWheel;// 处理鼠标滚轮事件
+        }
+
+        protected override void OnDetaching()
+        {
+            base.OnDetaching();
+            AssociatedObject.SelectionChanged -= OnSelectionChanged;
+            AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
+            AssociatedObject.PreviewMouseWheel -= OnPreviewMouseWheel; // 处理鼠标滚轮事件
+        }
+
+        private void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
+        {
+            if (sender is ComboBox comboBox)
+            {
+                if (!comboBox.IsDropDownOpen)
+                {
+                    // 吞掉滚轮事件,禁止它改变选项
+                    e.Handled = true;
+                }
+            }
+
+        }
+
+        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
+        {
+            
+        }
+
+        private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+        {
+            if (sender is ComboBox comboBox && comboBox.IsDropDownOpen)
+            {
+                if (UserSelectionCommand?.CanExecute(CommandParameter) == true)
+                {
+                    // 用户手动选择
+                    var selectedItem = AssociatedObject.SelectedItem;
+                    var parameter = new Tuple<object, object>(CommandParameter, comboBox.SelectedItem);
+                    UserSelectionCommand.Execute(parameter);
+                }
+            }
+        }
+    }
+}

+ 125 - 0
TeamAAS-VM/Controls/AddPalletView.xaml

@@ -0,0 +1,125 @@
+<UserControl x:Class="TeamAAS_VP.Controls.AddPalletView"
+             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.Controls"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:system="clr-namespace:System;assembly=mscorlib"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="450"
+             d:DesignWidth="800"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="auto" />
+            <RowDefinition Height="*" />
+            <RowDefinition Height="auto" />
+        </Grid.RowDefinitions>
+        <TextBlock Text="{lex:Loc 创建托盘}"
+                   Margin="10,5"
+                   FontWeight="Bold"
+                   FontSize="16" />
+        <materialDesign:Transitioner AutoApplyTransitionOrigins="True"
+                                     d:SelectedIndex="0"
+                                     SelectedIndex="{Binding SelectPageIndex}"
+                                     Grid.Row="1">
+            <!--选择托盘模式-->
+            <materialDesign:TransitionerSlide OpeningEffect="{materialDesign:TransitionEffect FadeIn}">
+                <StackPanel Orientation="Horizontal"
+                            HorizontalAlignment="Center">
+                    <RadioButton Content="{lex:Loc 普通托盘}"
+                                 IsChecked="{Binding IsCheckModel1}" />
+                    <RadioButton Content="{lex:Loc 组合托盘}"
+                                 IsChecked="{Binding IsCheckModel2}" />
+                </StackPanel>
+            </materialDesign:TransitionerSlide>
+
+            <!--选择坐标系模式-->
+            <Grid>
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="*" />
+                    <ColumnDefinition Width="*" />
+                </Grid.ColumnDefinitions>
+                <RadioButton IsChecked="{Binding Checked1}">
+                    <RadioButton.Content>
+                        <Grid>
+                            <Image Source="pack://application:,,,/TeamAAS-VP;component\Resources\Images\正交.png"
+                                   Width="200"
+                                   Height="200"
+                                   Stretch="Fill" />
+                            <TextBlock Text="{lex:Loc 正交}"
+                                       HorizontalAlignment="Center"
+                                       VerticalAlignment="Bottom" />
+                        </Grid>
+                    </RadioButton.Content>
+                </RadioButton>
+                <RadioButton Grid.Column="1"
+                             IsChecked="{Binding Checked2}">
+                    <RadioButton.Content>
+                        <Grid>
+                            <Image Source="pack://application:,,,/TeamAAS-VP;component\Resources\Images\切变.png"
+                                   Width="200"
+                                   Height="200"
+                                   Stretch="Fill" />
+                            <TextBlock Text="{lex:Loc 切变}"
+                                       HorizontalAlignment="Center"
+                                       VerticalAlignment="Bottom" />
+                        </Grid>
+                    </RadioButton.Content>
+                </RadioButton>
+            </Grid>
+
+            <!--输入托盘名称-->
+            <TextBox Grid.Row="1"
+                     Margin="2,6,2,0"
+                     materialDesign:HintAssist.Hint="{lex:Loc 请输入托盘的名称}"
+                     FontSize="16"
+                     HorizontalAlignment="Center"
+                     VerticalAlignment="Center"
+                     Style="{StaticResource MaterialDesignFloatingHintTextBox}"
+                     Text="{Binding PalletName}" />
+
+        </materialDesign:Transitioner>
+
+        <StackPanel Grid.Row="2"
+                    Margin="10"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Right">
+            <Button Command="{Binding GoBack}"
+                    Visibility="{Binding BackButtonVisibility}"
+                    IsDefault="True"
+                    Style="{StaticResource MaterialDesignFlatButton}"
+                    Content="{lex:Loc 上一步}">
+            </Button>
+            <Button Command="{Binding GoNext}"
+                    Visibility="{Binding NextButtonVisibility}"
+                    IsDefault="True"
+                    Style="{StaticResource MaterialDesignFlatButton}"
+                    Content="{lex:Loc 下一步}">
+            </Button>
+            <Button Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
+                    CommandParameter="{Binding DataContext}"
+                    Visibility="{Binding OKButtonVisibility}"
+                    IsDefault="True"
+                    Style="{StaticResource MaterialDesignFlatButton}"
+                    Content="{lex:Loc 确定}">
+            </Button>
+            <Button Margin="8,0,0,0"
+                    Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
+                    Visibility="{Binding CancelButtonVisibility}"
+                    IsCancel="True"
+                    Style="{StaticResource MaterialDesignFlatButton}"
+                    Content="{lex:Loc 取消}">
+                <Button.CommandParameter>
+                    <x:Null />
+                </Button.CommandParameter>
+            </Button>
+        </StackPanel>
+    </Grid>
+</UserControl>

+ 314 - 0
TeamAAS-VM/Controls/AddPalletView.xaml.cs

@@ -0,0 +1,314 @@
+using MaterialDesignThemes.Wpf;
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+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;
+using TeamAAS_VP.Enums;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// AddPalletView.xaml 的交互逻辑
+    /// </summary>
+    public partial class AddPalletView : UserControl, INotifyPropertyChanged
+    {
+        public AddPalletView()
+        {
+            InitializeComponent();
+            DataContext = this;
+        }
+
+        private int _SelectPageIndex=0;
+        /// <summary>
+        /// Page选择的索引
+        /// </summary>
+        public int SelectPageIndex
+        {
+            get { return _SelectPageIndex; }
+            set { SetProperty(ref _SelectPageIndex, value); }
+        }
+
+        private bool _IsCheckModel1=true;
+        /// <summary>
+        /// Pallet选择的模式(普通托盘)
+        /// </summary>
+        public bool IsCheckModel1
+        {
+            get { return _IsCheckModel1; }
+            set { SetProperty(ref _IsCheckModel1, value); }
+        }
+
+        private bool _IsCheckModel2=false;
+        /// <summary>
+        /// Pallet选择的模式(组合托盘)
+        /// </summary>
+        public bool IsCheckModel2
+        {
+            get { return _IsCheckModel2; }
+            set { SetProperty(ref _IsCheckModel2, value); }
+        }
+
+        private CoordinateModel _CoordinateModel= CoordinateModel.Orthogonality;
+        /// <summary>
+        /// 坐标系模式
+        /// </summary>
+        public CoordinateModel CoordinateModel
+        {
+            get { return _CoordinateModel; }
+            set { SetProperty(ref _CoordinateModel, value); }
+        }
+
+        private bool _Checked1=true;
+        /// <summary>
+        /// 正交坐标系
+        /// </summary>
+        public bool Checked1
+        {
+            get { return _Checked1; }
+            set
+            {
+                SetProperty(ref _Checked1, value);
+                if (value)
+                {
+                    Checked2 = false;
+                    CoordinateModel = CoordinateModel.Orthogonality;
+                }
+            }
+        }
+
+        private bool _Checked2=false;
+        /// <summary>
+        /// 切变坐标系
+        /// </summary>
+        public bool Checked2
+        {
+            get { return _Checked2; }
+            set
+            {
+                SetProperty(ref _Checked2, value);
+                if (value)
+                {
+                    Checked1 = false;
+                    CoordinateModel = CoordinateModel.Shear;
+                }
+            }
+        }
+
+        private string _PalletName;
+        /// <summary>
+        /// 托盘的名称
+        /// </summary>
+        public string PalletName
+        {
+            get { return _PalletName; }
+            set { SetProperty(ref _PalletName, value); }
+        }
+
+        private Visibility _BackButtonVisibility=Visibility.Collapsed;
+        /// <summary>
+        /// 上一步
+        /// </summary>
+        public Visibility BackButtonVisibility
+        {
+            get { return _BackButtonVisibility; }
+            set { SetProperty(ref _BackButtonVisibility, value); }
+        }
+
+        private Visibility _NextButtonVisibility = Visibility.Visible;
+        /// <summary>
+        /// 下一步
+        /// </summary>
+        public Visibility NextButtonVisibility
+        {
+            get { return _NextButtonVisibility; }
+            set { SetProperty(ref _NextButtonVisibility, value); }
+        }
+
+        private Visibility _OKButtonVisibility = Visibility.Collapsed;
+        /// <summary>
+        /// 确定
+        /// </summary>
+        public Visibility OKButtonVisibility
+        {
+            get { return _OKButtonVisibility; }
+            set { SetProperty(ref _OKButtonVisibility, value); }
+        }
+
+        private Visibility _CancelButtonVisibility = Visibility.Visible;
+        /// <summary>
+        /// 取消
+        /// </summary>
+        public Visibility CancelButtonVisibility
+        {
+            get { return _CancelButtonVisibility; }
+            set { SetProperty(ref _CancelButtonVisibility, value); }
+        }
+
+        private DelegateCommand _GoBack;
+        public DelegateCommand GoBack =>
+            _GoBack ?? (_GoBack = new DelegateCommand(ExecuteGoBack));
+
+        /// <summary>
+        /// 上一步
+        /// </summary>
+        void ExecuteGoBack()
+        {
+            if (SelectPageIndex == 1)
+            {
+                //进入托盘模式选择界面
+                SelectPageIndex = 0;
+                BackButtonVisibility = Visibility.Collapsed;
+                NextButtonVisibility = Visibility.Visible;
+                OKButtonVisibility = Visibility.Collapsed;
+                CancelButtonVisibility = Visibility.Visible;
+            }
+            else if (SelectPageIndex == 2)
+            {
+                if (IsCheckModel1)
+                {
+                    //进入托盘模式选择界面
+                    SelectPageIndex = 0;
+                    BackButtonVisibility = Visibility.Collapsed;
+                    NextButtonVisibility = Visibility.Visible;
+                    OKButtonVisibility = Visibility.Collapsed;
+                    CancelButtonVisibility = Visibility.Visible;
+                }
+                else
+                {
+                    //进入坐标系模式选择界面
+                    SelectPageIndex = 1;
+                    BackButtonVisibility = Visibility.Visible;
+                    NextButtonVisibility = Visibility.Visible;
+                    OKButtonVisibility = Visibility.Collapsed;
+                    CancelButtonVisibility = Visibility.Visible;
+                }
+            }
+        }
+
+        private DelegateCommand _GoNext;
+        public DelegateCommand GoNext =>
+            _GoNext ?? (_GoNext = new DelegateCommand(ExecuteGoNext));
+
+        /// <summary>
+        /// 下一步
+        /// </summary>
+        void ExecuteGoNext()
+        {
+            if (SelectPageIndex==0)
+            {
+                if (IsCheckModel1)
+                {
+                    //进入输入名称界面
+                    SelectPageIndex = 2;
+                    BackButtonVisibility= Visibility.Visible;
+                    NextButtonVisibility= Visibility.Collapsed;
+                    OKButtonVisibility = Visibility.Visible;
+                    CancelButtonVisibility = Visibility.Visible;
+                }
+                else
+                {
+                    //进入坐标系模式选择界面
+                    SelectPageIndex = 1;
+                    BackButtonVisibility = Visibility.Visible;
+                    NextButtonVisibility = Visibility.Visible;
+                    OKButtonVisibility = Visibility.Collapsed;
+                    CancelButtonVisibility = Visibility.Visible;
+                }
+            }
+            else if (SelectPageIndex == 1)
+            {
+                //进入输入名称界面
+                SelectPageIndex = 2;
+                BackButtonVisibility = Visibility.Visible;
+                NextButtonVisibility = Visibility.Collapsed;
+                OKButtonVisibility = Visibility.Visible;
+                CancelButtonVisibility = Visibility.Visible;
+            }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 60 - 0
TeamAAS-VM/Controls/AddProduct.xaml

@@ -0,0 +1,60 @@
+<UserControl x:Class="TeamAAS_VP.Controls.AddProduct"
+             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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:system="clr-namespace:System;assembly=mscorlib"
+             xmlns:local="clr-namespace:TeamAAS_VP.Controls"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="250"
+             d:DesignWidth="400"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <Grid Margin="16">
+
+        <Grid.RowDefinitions>
+            <RowDefinition Height="auto" />
+            <RowDefinition Height="*" />
+            <RowDefinition Height="auto" />
+        </Grid.RowDefinitions>
+        <TextBlock Text="{Binding Title}"
+                   FontSize="16"
+                   FontWeight="Bold"
+                   Margin="0,10"
+                   VerticalAlignment="Center"
+                   TextAlignment="Left"
+                   HorizontalAlignment="Left" />
+        <TextBox x:Name="txtName"
+                 Grid.Row="1"
+                 Margin="0,5"
+                 materialDesign:HintAssist.Hint="{Binding Item}"
+                 FontSize="16"
+                 Style="{StaticResource MaterialDesignFloatingHintTextBox}"
+                 Text="{Binding ProductName}">
+        </TextBox>
+        <StackPanel Grid.Row="2"
+                    Margin="0,10"
+                    Orientation="Horizontal">
+            <Button Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
+                    CommandParameter="{Binding ElementName=txtName,Path=Text}"
+                    IsDefault="True"
+                    Style="{StaticResource MaterialDesignFlatButton}"
+                    Content="{lex:Loc 确定}">
+            </Button>
+            <Button Margin="10,0"
+                    Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
+                    IsCancel="True"
+                    Style="{StaticResource MaterialDesignFlatButton}"
+                    Content="{lex:Loc 取消}">
+                <Button.CommandParameter>
+                    <x:Null />
+                </Button.CommandParameter>
+            </Button>
+        </StackPanel>
+    </Grid>
+</UserControl>

+ 130 - 0
TeamAAS-VM/Controls/AddProduct.xaml.cs

@@ -0,0 +1,130 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Security.Permissions;
+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.Controls
+{
+    /// <summary>
+    /// AddProduct.xaml 的交互逻辑
+    /// </summary>
+    public partial class AddProduct : UserControl, INotifyPropertyChanged
+    {
+        public AddProduct()
+        {
+            InitializeComponent();
+            DataContext = this;
+        }
+
+        private string _Title;
+
+        public string Title
+        {
+            get { return _Title; }
+            set { SetProperty(ref _Title,value); }
+        }
+
+        private string _Item;
+
+        public string Item
+        {
+            get { return _Item; }
+            set { SetProperty(ref _Item, value); }
+        }
+
+
+        private string _ProductName;
+
+        public string ProductName
+        {
+            get { return _ProductName; }
+            set { SetProperty(ref _ProductName,value); }
+        }
+
+        #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);
+        }
+        #endregion
+    }
+}

+ 170 - 0
TeamAAS-VM/Controls/AflexControl.xaml

@@ -0,0 +1,170 @@
+<UserControl x:Class="TeamAAS_VP.Controls.AflexControl"
+             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.Controls"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="450"
+             d:DesignWidth="800"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <Grid Margin="20">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="auto" />
+            <RowDefinition Height="auto" />
+            <RowDefinition Height="auto" />
+            <RowDefinition Height="auto" />
+        </Grid.RowDefinitions>
+        <Grid.ColumnDefinitions>
+            <ColumnDefinition Width="auto" />
+            <ColumnDefinition Width="auto" />
+            <ColumnDefinition Width="auto" />
+        </Grid.ColumnDefinitions>
+        <Grid.Resources>
+            <Style TargetType="TextBlock">
+                <Setter Property="HorizontalAlignment"
+                        Value="Right" />
+                <Setter Property="VerticalAlignment"
+                        Value="Center" />
+                <Setter Property="Margin"
+                        Value="10,0" />
+                <Setter Property="Grid.Column"
+                        Value="0" />
+            </Style>
+            <Style TargetType="Button"
+                   BasedOn="{StaticResource MaterialDesignRaisedButton}">
+                <Setter Property="Margin"
+                        Value="10,5" />
+                <Setter Property="HorizontalAlignment"
+                        Value="Center" />
+                <Setter Property="VerticalAlignment"
+                        Value="Center" />
+                <Setter Property="Grid.Column"
+                        Value="2" /> 
+            </Style>
+            <Style TargetType="mah:NumericUpDown">
+                <Setter Property="HorizontalAlignment"
+                        Value="Center" />
+                <Setter Property="VerticalAlignment"
+                        Value="Center" />
+                <Setter Property="Grid.Column"
+                        Value="1" />
+            </Style>
+        </Grid.Resources>
+        <!--选择配置-->
+        <TextBlock Grid.Row="0"
+                   Text="{lex:Loc 选择配置,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+        <ComboBox Grid.Row="0"
+                  Grid.Column="1"
+                  MinWidth="60"
+                  SelectedIndex="{Binding ConfigIndex}"
+                  materialDesign:HintAssist.Hint="{lex:Loc 配置编号}">
+            <ComboBoxItem>
+                <TextBlock Text="1|Flip"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="2|Move"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="3|Flip"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="4|Move"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="5|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="6|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="7|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="8|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="9|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="10|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="11|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="12|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+            <ComboBoxItem>
+                <TextBlock Text="13|"
+                           VerticalAlignment="Center" />
+            </ComboBoxItem>
+        </ComboBox>
+        <Button Grid.Row="0"
+                Content="{lex:Loc 确定}"
+                Command="{Binding ActionCommand}"
+                CommandParameter="1"/>
+        <!--强度-->
+        <TextBlock Grid.Row="1"
+                   Text="{lex:Loc 振动强度,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+        <mah:NumericUpDown Grid.Row="1"
+                           Maximum="100"
+                           Minimum="0"
+                           Interval="0.1"
+                           materialDesign:HintAssist.Hint="{lex:Loc 振动强度}"
+                           StringFormat="{}{0:N1} %"
+                           Value="{Binding Intensity,Mode=TwoWay}"/>
+        <Button Grid.Row="1"
+                Content="{lex:Loc 确定}"
+                Command="{Binding ActionCommand}"
+                CommandParameter="2" />
+        <!--方向-->
+        <TextBlock Grid.Row="2"
+                   Text="{lex:Loc 振动方向,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+        <mah:NumericUpDown Grid.Row="2"
+                           Maximum="360"
+                           Minimum="0"
+                           Interval="0.1"
+                           materialDesign:HintAssist.Hint="{lex:Loc 振动方向}"
+                           StringFormat="{}{0:N1} °"
+                           Value="{Binding Direction,Mode=TwoWay}" />
+        <Button Grid.Row="2"
+                Content="{lex:Loc 确定}"
+                Command="{Binding ActionCommand}"
+                CommandParameter="3" />
+        <!--背光亮度-->
+        <TextBlock Grid.Row="3"
+                   Text="{lex:Loc 背光亮度,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+        <mah:NumericUpDown Grid.Row="3"
+                           Maximum="100"
+                           Minimum="0"
+                           Interval="0.1"
+                           materialDesign:HintAssist.Hint="{lex:Loc 背光亮度}"
+                           StringFormat="{}{0:N1} %"
+                           Value="{Binding Backlight,Mode=TwoWay}" />
+        <Button Grid.Row="3"
+                Content="{lex:Loc 确定}"
+                Command="{Binding ActionCommand}"
+                CommandParameter="4" />
+    </Grid>
+</UserControl>

+ 186 - 0
TeamAAS-VM/Controls/AflexControl.xaml.cs

@@ -0,0 +1,186 @@
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+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;
+using Team.FFFeederService;
+using Team.FFFeederService.Interfaces;
+using TeamAAS_VP;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// AflexControl.xaml 的交互逻辑
+    /// </summary>
+    public partial class AflexControl : UserControl, INotifyPropertyChanged
+    {
+        public AflexControl()
+        {
+            InitializeComponent();
+            this.DataContext = this;
+        }
+
+        public AfagFeeder Feeder { get; set; }
+
+        private int _ConfigIndex;
+        /// <summary>
+        /// 配置编号
+        /// </summary>
+        public int ConfigIndex
+        {
+            get { return _ConfigIndex; }
+            set { SetProperty(ref _ConfigIndex, value); }
+        }
+
+        private double _Intensity;
+        /// <summary>
+        /// 振动强度
+        /// </summary>
+        public double Intensity
+        {
+            get { return _Intensity; }
+            set { SetProperty(ref _Intensity, value); }
+        }
+
+        private double _Direction;
+        /// <summary>
+        /// 方向
+        /// </summary>
+        public double Direction
+        {
+            get { return _Direction; }
+            set { SetProperty(ref _Direction, value); }
+        }
+
+        private double _Backlight;
+        /// <summary>
+        /// 背光亮度
+        /// </summary>
+        public double Backlight
+        {
+            get { return _Backlight; }
+            set { SetProperty(ref _Backlight, value); }
+        }
+
+        private DelegateCommand<string> _ActionCommand;
+        public DelegateCommand<string> ActionCommand =>
+            _ActionCommand ?? (_ActionCommand = new DelegateCommand<string>(ExecuteActionCommand));
+
+        /// <summary>
+        /// 执行命令
+        /// </summary>
+        /// <param name="cmd"></param>
+        void ExecuteActionCommand(string cmd)
+        {
+            try
+            {
+                if (Feeder == null) { return; }
+                switch (int.Parse(cmd))
+                {
+                    case 1:
+                        if (ConfigIndex<0) { return; }
+                        Feeder.LoadConfiguration(ConfigIndex+1);
+                        break;
+                    case 2:
+                        Feeder.SetIntensity(Intensity);
+                        break;
+                    case 3:
+                        Feeder.SetDirection(Direction);
+                        break;
+                    case 4:
+                        Feeder.SetBackLight(Backlight);
+                        break;
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Afag Feeder写入参数时出错!", ex);
+            }
+            
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 162 - 0
TeamAAS-VM/Controls/FeederOutput.xaml

@@ -0,0 +1,162 @@
+<UserControl x:Class="TeamAAS_VP.Controls.FeederOutput"
+             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.Controls"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:material="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="450"
+             d:DesignWidth="600"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <Viewbox Stretch="None">
+        <Grid>
+            <Grid.RowDefinitions>
+                <RowDefinition Height="auto" />
+                <RowDefinition Height="auto" />
+                <RowDefinition Height="auto" />
+                <RowDefinition Height="auto" />
+                <RowDefinition Height="auto" />
+            </Grid.RowDefinitions>
+            <StackPanel Grid.Row="0"
+                        Margin="0,10"
+                        Orientation="Horizontal">
+                <ComboBox x:Name="SequenceComboBox"
+                          MinWidth="60"
+                          Margin="5,5"
+                          HorizontalContentAlignment="Center"
+                          material:HintAssist.Hint="{lex:Loc 输出设定}"
+                          material:HintAssist.IsFloating="True"
+                          ItemsSource="{Binding SequenceCollection}"
+                          SelectedIndex="{Binding SelectedSequence}">
+                    <behavior:Interaction.Triggers>
+                        <behavior:EventTrigger EventName="SelectionChanged">
+                            <behavior:InvokeCommandAction Command="{Binding SelectSequenceCommand}" />
+                        </behavior:EventTrigger>
+                    </behavior:Interaction.Triggers>
+                </ComboBox>
+            </StackPanel>
+            <StackPanel Grid.Row="1"
+                        HorizontalAlignment="Center">
+                <UniformGrid Columns="2">
+                    <TextBlock VerticalAlignment="Center"
+                               Text="{lex:Loc 数字量输出,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}1: '}" />
+                    <mah:ToggleSwitch Margin="10,0,0,0"
+                                      VerticalAlignment="Center"
+                                      IsOn="{Binding CurrentUpperFeederParamDto.HopperDigitalOutput1}" />
+                    <TextBlock VerticalAlignment="Bottom"
+                               Text="{lex:Loc 模拟量输出,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}1: '}" />
+                    <local:myNumericUpDowm Margin="10,0,0,0"
+                                           Minimum="0"
+                                           Maximum="10"
+                                           StringFormat="{}{0:N0} %"
+                                           Value="{Binding CurrentUpperFeederParamDto.HopperAnalogOutput1, ValidatesOnDataErrors=True,Mode=TwoWay}" />
+                    <TextBlock VerticalAlignment="Center"
+                               Text="{lex:Loc 数字量输出,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}2: '}" />
+                    <mah:ToggleSwitch Margin="10,0,0,0"
+                                      IsOn="{Binding CurrentUpperFeederParamDto.HopperDigitalOutput2}" />
+                    <TextBlock VerticalAlignment="Bottom"
+                               Text="{lex:Loc 模拟量输出,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}2: '}" />
+                    <local:myNumericUpDowm Margin="10,0,0,0"
+                                           Minimum="0"
+                                           Maximum="10"
+                                           StringFormat="{}{0:N0} %"
+                                           Value="{Binding CurrentUpperFeederParamDto.HopperAnalogOutput2, ValidatesOnDataErrors=True,Mode=TwoWay}" />
+                    <TextBlock VerticalAlignment="Bottom"
+                               Text="{lex:Loc 振动持续时间,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                    <local:myNumericUpDowm Margin="10,0,0,0"
+                                           Width="150"
+                                           Height="20"
+                                           Minimum="0"
+                                           Interval="100"
+                                           Maximum="60000"
+                                           StringFormat="{}{0:N0} ms"
+                                           Value="{Binding CurrentUpperFeederParamDto.HopperDuration, ValidatesOnDataErrors=True,Mode=TwoWay}" />
+
+                </UniformGrid>
+                <StackPanel Margin="0,10"
+                            FlowDirection="RightToLeft"
+                            Orientation="Horizontal">
+
+                    <Button Margin="4,10"
+                            HorizontalAlignment="Center"
+                            material:ButtonAssist.CornerRadius="5"
+                            Command="{Binding StopActionCommand}"
+                            Content="{lex:Loc 停止}" />
+
+                    <Button Margin="4,10"
+                            HorizontalAlignment="Center"
+                            material:ButtonAssist.CornerRadius="5"
+                            Command="{Binding ExecuteActionCommand}"
+                            Content="{lex:Loc 执行}"
+                            Cursor="Hand" />
+                    <Button Margin="4,10"
+                            HorizontalAlignment="Center"
+                            material:ButtonAssist.CornerRadius="5"
+                            Command="{Binding WriteParamCommand}"
+                            Content="{lex:Loc 下载参数}"
+                            Cursor="Hand" />
+
+                </StackPanel>
+
+            </StackPanel>
+            <StackPanel Grid.Row="2">
+                <TextBlock Margin="5"
+                           Text="{lex:Loc 输入设定}" />
+            </StackPanel>
+            <StackPanel Grid.Row="3"
+                        HorizontalAlignment="Center">
+                <UniformGrid Columns="2">
+                    <TextBlock VerticalAlignment="Bottom"
+                               Text="{lex:Loc 输入1触发序列ID,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                    <ComboBox Margin="10,0,0,0"
+                              material:HintAssist.Hint="{lex:Loc 输入1触发序列ID}"
+                              material:HintAssist.IsFloating="True"
+                              ItemsSource="{Binding SequenceItems}"
+                              SelectedIndex="{Binding InputTriggerId1, ValidatesOnDataErrors=True}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectInputSequenceCommand1}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                    <TextBlock VerticalAlignment="Bottom"
+                               Text="{lex:Loc 输入2触发序列ID,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                    <ComboBox Margin="10,0,0,0"
+                              material:HintAssist.Hint="{lex:Loc 输入2触发序列ID}"
+                              material:HintAssist.IsFloating="True"
+                              ItemsSource="{Binding SequenceItems}"
+                              SelectedIndex="{Binding InputTriggerId2, ValidatesOnDataErrors=True}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectInputSequenceCommand2}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                </UniformGrid>
+                <StackPanel Grid.Row="4"
+                            Margin="0,10"
+                            FlowDirection="RightToLeft"
+                            Orientation="Horizontal">
+                    <Button Margin="4,10"
+                            HorizontalAlignment="Center"
+                            material:ButtonAssist.CornerRadius="5"
+                            Command="{Binding WriteInputCommand}"
+                            Content="{lex:Loc 下载参数}"
+                            Cursor="Hand" />
+
+                </StackPanel>
+            </StackPanel>
+
+        </Grid>
+    </Viewbox>
+    
+</UserControl>

+ 376 - 0
TeamAAS-VM/Controls/FeederOutput.xaml.cs

@@ -0,0 +1,376 @@
+using MaterialDesignThemes.Wpf;
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Security.Cryptography;
+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;
+using Team.FFFeederService.Interfaces;
+using Team.FFFeederService.Models;
+using TouchSocket.Core;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// FeederOutput.xaml 的交互逻辑
+    /// </summary>
+    public partial class FeederOutput : UserControl, INotifyPropertyChanged
+    {
+        public FeederOutput()
+        {
+            InitializeComponent();
+            this.DataContext = this;
+            SequenceCollection = new ObservableCollection<string>();
+            for (var i = 'A'; i < 'Z'; i++)
+            {
+                SequenceCollection.Add(i.ToString());
+            }
+            SequenceItems = new ObservableCollection<int>();
+            for (var i = 1; i <= 26; i++)
+            {
+                SequenceItems.Add(i);
+            }
+        }
+
+        #region 属性
+        public IVoiceCoilMotorFeeder Feeder { get; set; }
+
+        private ObservableCollection<string> _SequenceCollection;
+
+        /// <summary>
+        /// 输出振动集
+        /// </summary>
+        public ObservableCollection<string> SequenceCollection
+        {
+            get { return _SequenceCollection; }
+            set { SetProperty(ref _SequenceCollection,value); }
+        }
+
+        private int _SelectedSequence=-1;
+
+        /// <summary>
+        /// 当前选择输出
+        /// </summary>
+        public int SelectedSequence
+        {
+            get { return _SelectedSequence; }
+            set { SetProperty(ref _SelectedSequence, value); }
+        }
+
+        private HopperFeederParam _CurrentUpperFeederParamDto;
+        /// <summary>
+        /// 当前选中的料仓参数
+        /// </summary>
+        public HopperFeederParam CurrentUpperFeederParamDto
+        {
+            get { return _CurrentUpperFeederParamDto; }
+            set { SetProperty(ref _CurrentUpperFeederParamDto, value); }
+        }
+
+        private ObservableCollection<int> _SequenceItems;
+
+        /// <summary>
+        /// 输入触发序列集
+        /// </summary>
+        public ObservableCollection<int> SequenceItems
+        {
+            get { return _SequenceItems; }
+            set { SetProperty(ref _SequenceItems,value); }
+        }
+
+        private int _InputTriggerId1=-1;
+
+        /// <summary>
+        /// 当前1选中的序列
+        /// </summary>
+        public int InputTriggerId1
+        {
+            get { return _InputTriggerId1; }
+            set { SetProperty(ref _InputTriggerId1, value); }
+        }
+
+        private int _InputTriggerId2 = -1;
+
+        /// <summary>
+        /// 当前2选中的序列
+        /// </summary>
+        public int InputTriggerId2
+        {
+            get { return _InputTriggerId2; }
+            set { SetProperty(ref _InputTriggerId2, value); }
+        }
+        #endregion
+
+        #region 命令
+        private DelegateCommand _SelectSequenceCommand;
+        public DelegateCommand SelectSequenceCommand =>
+            _SelectSequenceCommand ?? (_SelectSequenceCommand = new DelegateCommand(ExecuteSelectSequenceCommand));
+
+        private DelegateCommand _StopActionCommand;
+        public DelegateCommand StopActionCommand =>
+            _StopActionCommand ?? (_StopActionCommand = new DelegateCommand(ExecuteStopActionCommand));
+
+        private DelegateCommand _WriteParamCommand;
+        public DelegateCommand WriteParamCommand =>
+            _WriteParamCommand ?? (_WriteParamCommand = new DelegateCommand(ExecuteWriteParamCommand));
+
+        private DelegateCommand _ExecuteActionCommand;
+        public DelegateCommand ExecuteActionCommand =>
+            _ExecuteActionCommand ?? (_ExecuteActionCommand = new DelegateCommand(ExecuteExecuteActionCommand));
+
+        private DelegateCommand _SelectInputSequenceCommand1;
+        public DelegateCommand SelectInputSequenceCommand1 =>
+            _SelectInputSequenceCommand1 ?? (_SelectInputSequenceCommand1 = new DelegateCommand(ExecuteSelectInputSequenceCommand1));
+
+        private DelegateCommand _SelectInputSequenceCommand2;
+        public DelegateCommand SelectInputSequenceCommand2 =>
+            _SelectInputSequenceCommand2 ?? (_SelectInputSequenceCommand2 = new DelegateCommand(ExecuteSelectInputSequenceCommand2));
+
+        private DelegateCommand _WriteInputCommand;
+        public DelegateCommand WriteInputCommand =>
+            _WriteInputCommand ?? (_WriteInputCommand = new DelegateCommand(ExecuteWriteInputCommand));
+
+        
+        #endregion
+
+        #region 方法
+        /// <summary>
+        /// 选中输出时
+        /// </summary>
+        async void ExecuteSelectSequenceCommand()
+        {
+            if (Feeder == null) return;
+            if (!Feeder.IsConnected) return;
+            if (SelectedSequence == -1) return;
+
+            var param = await Feeder.GetUpperParamAsync(SelectedSequence);
+            CurrentUpperFeederParamDto = param;
+            var index = await Feeder.GetInputTrigger(1);
+            if (index <= 0 || index > 26)
+            {
+                InputTriggerId2 = 1;
+            }
+
+            InputTriggerId1 = index - 1;
+            index = await Feeder.GetInputTrigger(2);
+            InputTriggerId2 = index - 1;
+        }
+
+        /// <summary>
+        /// 选中输入1触发序列时
+        /// </summary>
+        async void ExecuteSelectInputSequenceCommand1()
+        {
+            if (Feeder == null) return;
+            if (!Feeder.IsConnected) return;
+            if (InputTriggerId2 == -1) return;
+            try
+            {
+                var index = await Feeder.GetInputTrigger(1);
+                if (index <= 0 || index > 26)
+                {
+                    InputTriggerId1 = 1;
+                }
+                else
+                {
+                    InputTriggerId1 = index - 1;
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 选中输入2触发序列时
+        /// </summary>
+        async void ExecuteSelectInputSequenceCommand2()
+        {
+            if (Feeder == null) return;
+            if (!Feeder.IsConnected) return;
+            if (InputTriggerId2 == -1) return;
+            try
+            {
+                var index = await Feeder.GetInputTrigger(2);
+                if (index <= 0 || index > 26)
+                {
+                    InputTriggerId2 = 1;
+                }
+                else
+                {
+                    InputTriggerId2 = index - 1;
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 执行
+        /// </summary>
+        async void ExecuteExecuteActionCommand()
+        {
+            if (Feeder == null) return;
+            if (!Feeder.IsConnected) return;
+            if (SelectedSequence < 0) return;
+            try
+            {
+                await Feeder.OutputAsync(SelectedSequence + 1, CurrentUpperFeederParamDto.HopperDuration);
+            }
+            catch (Exception)
+            {
+                
+            }
+        }
+
+        /// <summary>
+        /// 停止
+        /// </summary>
+        async void ExecuteStopActionCommand()
+        {
+            if (Feeder == null) return;
+            if (!Feeder.IsConnected) return;
+            if (SelectedSequence < 0) return;
+            try
+            {
+                await Feeder.StopOutputAsync();
+            }
+            catch (Exception)
+            {
+                
+            }
+        }
+
+        /// <summary>
+        /// 下载参数
+        /// </summary>
+        async void ExecuteWriteParamCommand()
+        {
+            if (Feeder == null) return;
+            if (!Feeder.IsConnected) return;
+            if (SelectedSequence < 0) return;
+            if (CurrentUpperFeederParamDto == null)
+            {
+                return;
+            }
+            try
+            {
+                await Feeder.WriteOutputParamAsync(SelectedSequence, CurrentUpperFeederParamDto);
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 下载参数
+        /// </summary>
+        async void ExecuteWriteInputCommand()
+        {
+            if (Feeder == null) return;
+            if (!Feeder.IsConnected) return;
+            if (InputTriggerId1 < 0) return;
+            if (InputTriggerId1 < 2) return;
+            try
+            {
+                await Feeder.SetInputTrigger(1, InputTriggerId1 + 1);
+                await Feeder.SetInputTrigger(2, InputTriggerId2 + 1);
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 1384 - 0
TeamAAS-VM/Controls/FeederSequence.xaml

@@ -0,0 +1,1384 @@
+<UserControl x:Class="TeamAAS_VP.Controls.FeederSequence"
+             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.Controls"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:feederEnum="clr-namespace:Team.FFFeederService.Enums;assembly=Team.FFFeederService"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="450"
+             d:DesignWidth="800"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+
+    <UserControl.Resources>
+        <ObjectDataProvider x:Key="eActionType"
+                            MethodName="GetValues"
+                            ObjectType="{x:Type sys:Enum}">
+            <ObjectDataProvider.MethodParameters>
+                <x:Type TypeName="feederEnum:ActionType" />
+            </ObjectDataProvider.MethodParameters>
+        </ObjectDataProvider>
+        <ObjectDataProvider x:Key="eDurationMode"
+                            MethodName="GetValues"
+                            ObjectType="{x:Type sys:Enum}">
+            <ObjectDataProvider.MethodParameters>
+                <x:Type TypeName="feederEnum:DurationMode" />
+            </ObjectDataProvider.MethodParameters>
+        </ObjectDataProvider>
+    </UserControl.Resources>
+    <Viewbox Stretch="None">
+        <Grid>
+            <Grid.RowDefinitions>
+                <RowDefinition Height="Auto" />
+                <RowDefinition Height="Auto" />
+                <RowDefinition />
+                <RowDefinition Height="Auto" />
+            </Grid.RowDefinitions>
+
+            <StackPanel Grid.Row="1"
+                        Margin="0,10"
+                        Orientation="Horizontal">
+
+                <ComboBox x:Name="SequenceComboBox"
+                          MinWidth="60"
+                          Margin="5,5"
+                          HorizontalContentAlignment="Center"
+                          materialDesign:HintAssist.Hint="{lex:Loc 序列集调试}"
+                          materialDesign:HintAssist.IsFloating="True"
+                          ItemsSource="{Binding SequenceCollection}"
+                          SelectedIndex="{Binding SelectedSequence}">
+                    <behavior:Interaction.Triggers>
+                        <behavior:EventTrigger EventName="SelectionChanged">
+                            <behavior:InvokeCommandAction Command="{Binding SelectSequenceCommand}" />
+                        </behavior:EventTrigger>
+                    </behavior:Interaction.Triggers>
+                </ComboBox>
+                <local:myNumericUpDowm Margin="5,5"
+                                       materialDesign:HintAssist.Hint="{lex:Loc 极限值}"
+                                       materialDesign:HintAssist.IsFloating="True"
+                                       Value="{Binding CurrentSequencePartCntMax,Mode=TwoWay}" />
+                <Button Margin="5,5"
+                        Command="{Binding StartCommand}"
+                        materialDesign:ButtonAssist.CornerRadius="5"
+                        Style="{StaticResource MaterialDesignOutlinedButton}">
+                    <materialDesign:PackIcon Kind="Play" />
+                </Button>
+                <Button Margin="5,5"
+                        Command="{Binding StopCommand}"
+                        materialDesign:ButtonAssist.CornerRadius="5"
+                        Style="{StaticResource MaterialDesignOutlinedButton}">
+                    <materialDesign:PackIcon Kind="Stop" />
+                </Button>
+                <TextBlock Margin="5"
+                           VerticalAlignment="Center"
+                           Text="{lex:Loc 循环执行,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                <local:myNumericUpDowm MinWidth="20"
+                                       Margin="5"
+                                       Interval="1"
+                                       Maximum="20"
+                                       Minimum="1"
+                                       StringFormat="{}{0:N0}"
+                                       Value="{Binding CycleRunningTimes,Mode=TwoWay}" />
+                <Button 
+                        Margin="5"
+                        materialDesign:ButtonAssist.CornerRadius="5"
+                        Command="{Binding WriteParamCommand}"
+                        Content="{lex:Loc 下载}" />
+            </StackPanel>
+            <StackPanel Grid.Row="2"
+                        Margin="0,20,0,0"
+                        HorizontalAlignment="Center">
+                <StackPanel Orientation="Horizontal">
+                    <TextBlock Margin="5,5"
+                               VerticalAlignment="Center"
+                               Text="{lex:Loc 动作,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}1'}" />
+                    <ComboBox x:Name="ActionComboBox1"
+                              Width="100"
+                              MinWidth="60"
+                              Margin="5,5"
+                              HorizontalContentAlignment="Center"
+                              ItemsSource="{Binding Source={StaticResource eActionType}}"
+                              SelectedItem="{Binding SingleSequenceAction1.Type}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectActionCommand1}"
+                                                              CommandParameter="{Binding ElementName=ActionComboBox1, Path=SelectedIndex}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility1}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 程序选择}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  SelectedIndex="{Binding SingleSequenceAction1.ShakeId}">
+                            <!--A-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="A"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowLeftBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--B-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="B"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--C-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="C"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--D-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="D"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowDownBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--E-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="E"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowUpBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--F-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="F"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowRightBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--G-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="G"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--H-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="H"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--I-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="I"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowExpandAll"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--J-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="J"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseHorizontal"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--K-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="K"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseVertical"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--L-->
+                            <ComboBoxItem>L</ComboBoxItem>
+                            <!--M-->
+                            <ComboBoxItem>M</ComboBoxItem>
+                            <!--N-->
+                            <ComboBoxItem>N</ComboBoxItem>
+                            <!--O-->
+                            <ComboBoxItem>O</ComboBoxItem>
+                            <!--P-->
+                            <ComboBoxItem>P</ComboBoxItem>
+                            <!--Q-->
+                            <ComboBoxItem>Q</ComboBoxItem>
+                            <!--R-->
+                            <ComboBoxItem>R</ComboBoxItem>
+                            <!--S-->
+                            <ComboBoxItem>S</ComboBoxItem>
+                            <!--T-->
+                            <ComboBoxItem>T</ComboBoxItem>
+                            <!--U-->
+                            <ComboBoxItem>U</ComboBoxItem>
+                            <!--V-->
+                            <ComboBoxItem>V</ComboBoxItem>
+                            <!--W-->
+                            <ComboBoxItem>W</ComboBoxItem>
+                            <!--X-->
+                            <ComboBoxItem>X</ComboBoxItem>
+                            <!--Y-->
+                            <ComboBoxItem>Y</ComboBoxItem>
+                            <!--Z-->
+                            <ComboBoxItem>Z</ComboBoxItem>
+                        </ComboBox>
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续模式}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  ItemsSource="{Binding Source={StaticResource eDurationMode}}"
+                                  SelectedItem="{Binding SingleSequenceAction1.DurationMode}" />
+
+                    </DockPanel>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility1_2}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续时间}" />
+                        <local:myNumericUpDowm Width="96"
+                                               Interval="1"
+                                               Maximum="{Binding SingleSequenceAction1.Max,Mode=TwoWay}"
+                                               Minimum="1"
+                                               StringFormat="{Binding SingleSequenceAction1.Format,Mode=TwoWay}"
+                                               Value="{Binding SingleSequenceAction1.DurationValue,Mode=TwoWay}" />
+                    </DockPanel>
+
+                </StackPanel>
+                <StackPanel Orientation="Horizontal">
+                    <TextBlock Margin="5,5"
+                               VerticalAlignment="Center"
+                               Text="{lex:Loc 动作,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}2'}" />
+                    <ComboBox x:Name="ActionComboBox2"
+                              Width="100"
+                              MinWidth="60"
+                              Margin="5,5"
+                              HorizontalContentAlignment="Center"
+                              ItemsSource="{Binding Source={StaticResource eActionType}}"
+                              SelectedItem="{Binding SingleSequenceAction2.Type}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectActionCommand2}"
+                                                              CommandParameter="{Binding ElementName=ActionComboBox2, Path=SelectedIndex}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility2}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 程序选择}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  SelectedIndex="{Binding SingleSequenceAction2.ShakeId}">
+                            <!--A-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="A"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowLeftBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--B-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="B"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--C-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="C"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--D-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="D"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowDownBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--E-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="E"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowUpBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--F-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="F"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowRightBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--G-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="G"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--H-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="H"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--I-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="I"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowExpandAll"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--J-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="J"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseHorizontal"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--K-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="K"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseVertical"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--L-->
+                            <ComboBoxItem>L</ComboBoxItem>
+                            <!--M-->
+                            <ComboBoxItem>M</ComboBoxItem>
+                            <!--N-->
+                            <ComboBoxItem>N</ComboBoxItem>
+                            <!--O-->
+                            <ComboBoxItem>O</ComboBoxItem>
+                            <!--P-->
+                            <ComboBoxItem>P</ComboBoxItem>
+                            <!--Q-->
+                            <ComboBoxItem>Q</ComboBoxItem>
+                            <!--R-->
+                            <ComboBoxItem>R</ComboBoxItem>
+                            <!--S-->
+                            <ComboBoxItem>S</ComboBoxItem>
+                            <!--T-->
+                            <ComboBoxItem>T</ComboBoxItem>
+                            <!--U-->
+                            <ComboBoxItem>U</ComboBoxItem>
+                            <!--V-->
+                            <ComboBoxItem>V</ComboBoxItem>
+                            <!--W-->
+                            <ComboBoxItem>W</ComboBoxItem>
+                            <!--X-->
+                            <ComboBoxItem>X</ComboBoxItem>
+                            <!--Y-->
+                            <ComboBoxItem>Y</ComboBoxItem>
+                            <!--Z-->
+                            <ComboBoxItem>Z</ComboBoxItem>
+                        </ComboBox>
+
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续模式}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  ItemsSource="{Binding Source={StaticResource eDurationMode}}"
+                                  SelectedItem="{Binding SingleSequenceAction2.DurationMode}" />
+
+                    </DockPanel>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility2_2}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续时间}" />
+                        <local:myNumericUpDowm Width="96"
+                                               Interval="1"
+                                               Maximum="{Binding SingleSequenceAction2.Max,Mode=TwoWay}"
+                                               Minimum="1"
+                                               StringFormat="{Binding SingleSequenceAction2.Format,Mode=TwoWay}"
+                                               Value="{Binding SingleSequenceAction2.DurationValue,Mode=TwoWay}" />
+                    </DockPanel>
+
+                </StackPanel>
+                <StackPanel Orientation="Horizontal">
+                    <TextBlock Margin="5,5"
+                               VerticalAlignment="Center"
+                               Text="{lex:Loc 动作,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}3'}" />
+                    <ComboBox x:Name="ActionComboBox3"
+                              Width="100"
+                              MinWidth="60"
+                              Margin="5,5"
+                              HorizontalContentAlignment="Center"
+                              ItemsSource="{Binding Source={StaticResource eActionType}}"
+                              SelectedItem="{Binding SingleSequenceAction3.Type}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectActionCommand3}"
+                                                              CommandParameter="{Binding ElementName=ActionComboBox3, Path=SelectedIndex}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility3}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 程序选择}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  SelectedIndex="{Binding SingleSequenceAction3.ShakeId}">
+                            <!--A-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="A"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowLeftBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--B-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="B"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--C-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="C"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--D-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="D"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowDownBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--E-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="E"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowUpBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--F-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="F"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowRightBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--G-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="G"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--H-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="H"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--I-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="I"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowExpandAll"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--J-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="J"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseHorizontal"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--K-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="K"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseVertical"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--L-->
+                            <ComboBoxItem>L</ComboBoxItem>
+                            <!--M-->
+                            <ComboBoxItem>M</ComboBoxItem>
+                            <!--N-->
+                            <ComboBoxItem>N</ComboBoxItem>
+                            <!--O-->
+                            <ComboBoxItem>O</ComboBoxItem>
+                            <!--P-->
+                            <ComboBoxItem>P</ComboBoxItem>
+                            <!--Q-->
+                            <ComboBoxItem>Q</ComboBoxItem>
+                            <!--R-->
+                            <ComboBoxItem>R</ComboBoxItem>
+                            <!--S-->
+                            <ComboBoxItem>S</ComboBoxItem>
+                            <!--T-->
+                            <ComboBoxItem>T</ComboBoxItem>
+                            <!--U-->
+                            <ComboBoxItem>U</ComboBoxItem>
+                            <!--V-->
+                            <ComboBoxItem>V</ComboBoxItem>
+                            <!--W-->
+                            <ComboBoxItem>W</ComboBoxItem>
+                            <!--X-->
+                            <ComboBoxItem>X</ComboBoxItem>
+                            <!--Y-->
+                            <ComboBoxItem>Y</ComboBoxItem>
+                            <!--Z-->
+                            <ComboBoxItem>Z</ComboBoxItem>
+                        </ComboBox>
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续模式}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  ItemsSource="{Binding Source={StaticResource eDurationMode}}"
+                                  SelectedItem="{Binding SingleSequenceAction3.DurationMode}" />
+
+                    </DockPanel>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility3_2}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续时间}" />
+                        <local:myNumericUpDowm Width="96"
+                                               Interval="1"
+                                               Maximum="{Binding SingleSequenceAction3.Max,Mode=TwoWay}"
+                                               Minimum="1"
+                                               StringFormat="{Binding SingleSequenceAction3.Format,Mode=TwoWay}"
+                                               Value="{Binding SingleSequenceAction3.DurationValue,Mode=TwoWay}" />
+                    </DockPanel>
+
+                </StackPanel>
+                <StackPanel Orientation="Horizontal">
+                    <TextBlock Margin="5,5"
+                               VerticalAlignment="Center"
+                               Text="{lex:Loc 动作,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}4'}" />
+                    <ComboBox x:Name="ActionComboBox4"
+                              Width="100"
+                              MinWidth="60"
+                              Margin="5,5"
+                              HorizontalContentAlignment="Center"
+                              ItemsSource="{Binding Source={StaticResource eActionType}}"
+                              SelectedItem="{Binding SingleSequenceAction4.Type}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectActionCommand4}"
+                                                              CommandParameter="{Binding ElementName=ActionComboBox4, Path=SelectedIndex}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility4}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 程序选择}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  SelectedIndex="{Binding SingleSequenceAction4.ShakeId}">
+                            <!--A-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="A"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowLeftBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--B-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="B"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--C-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="C"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--D-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="D"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowDownBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--E-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="E"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowUpBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--F-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="F"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowRightBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--G-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="G"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--H-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="H"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--I-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="I"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowExpandAll"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--J-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="J"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseHorizontal"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--K-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="K"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseVertical"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--L-->
+                            <ComboBoxItem>L</ComboBoxItem>
+                            <!--M-->
+                            <ComboBoxItem>M</ComboBoxItem>
+                            <!--N-->
+                            <ComboBoxItem>N</ComboBoxItem>
+                            <!--O-->
+                            <ComboBoxItem>O</ComboBoxItem>
+                            <!--P-->
+                            <ComboBoxItem>P</ComboBoxItem>
+                            <!--Q-->
+                            <ComboBoxItem>Q</ComboBoxItem>
+                            <!--R-->
+                            <ComboBoxItem>R</ComboBoxItem>
+                            <!--S-->
+                            <ComboBoxItem>S</ComboBoxItem>
+                            <!--T-->
+                            <ComboBoxItem>T</ComboBoxItem>
+                            <!--U-->
+                            <ComboBoxItem>U</ComboBoxItem>
+                            <!--V-->
+                            <ComboBoxItem>V</ComboBoxItem>
+                            <!--W-->
+                            <ComboBoxItem>W</ComboBoxItem>
+                            <!--X-->
+                            <ComboBoxItem>X</ComboBoxItem>
+                            <!--Y-->
+                            <ComboBoxItem>Y</ComboBoxItem>
+                            <!--Z-->
+                            <ComboBoxItem>Z</ComboBoxItem>
+                        </ComboBox>
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续模式}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  ItemsSource="{Binding Source={StaticResource eDurationMode}}"
+                                  SelectedItem="{Binding SingleSequenceAction4.DurationMode}" />
+
+                    </DockPanel>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility4_2}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续时间}" />
+                        <local:myNumericUpDowm Width="96"
+                                               Interval="1"
+                                               Maximum="{Binding SingleSequenceAction4.Max,Mode=TwoWay}"
+                                               Minimum="1"
+                                               StringFormat="{Binding SingleSequenceAction4.Format,Mode=TwoWay}"
+                                               Value="{Binding SingleSequenceAction4.DurationValue,Mode=TwoWay}" />
+                    </DockPanel>
+
+                </StackPanel>
+                <StackPanel Orientation="Horizontal">
+                    <TextBlock Margin="5,5"
+                               VerticalAlignment="Center"
+                               Text="{lex:Loc 动作,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}5'}" />
+                    <ComboBox x:Name="ActionComboBox5"
+                              Width="100"
+                              MinWidth="60"
+                              Margin="5,5"
+                              HorizontalContentAlignment="Center"
+                              ItemsSource="{Binding Source={StaticResource eActionType}}"
+                              SelectedItem="{Binding SingleSequenceAction5.Type}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectActionCommand5}"
+                                                              CommandParameter="{Binding ElementName=ActionComboBox5, Path=SelectedIndex}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility5}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 程序选择}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  SelectedIndex="{Binding SingleSequenceAction5.ShakeId}">
+                            <!--A-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="A"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowLeftBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--B-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="B"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--C-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="C"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--D-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="D"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowDownBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--E-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="E"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowUpBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--F-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="F"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowRightBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--G-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="G"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--H-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="H"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--I-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="I"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowExpandAll"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--J-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="J"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseHorizontal"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--K-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="K"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseVertical"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--L-->
+                            <ComboBoxItem>L</ComboBoxItem>
+                            <!--M-->
+                            <ComboBoxItem>M</ComboBoxItem>
+                            <!--N-->
+                            <ComboBoxItem>N</ComboBoxItem>
+                            <!--O-->
+                            <ComboBoxItem>O</ComboBoxItem>
+                            <!--P-->
+                            <ComboBoxItem>P</ComboBoxItem>
+                            <!--Q-->
+                            <ComboBoxItem>Q</ComboBoxItem>
+                            <!--R-->
+                            <ComboBoxItem>R</ComboBoxItem>
+                            <!--S-->
+                            <ComboBoxItem>S</ComboBoxItem>
+                            <!--T-->
+                            <ComboBoxItem>T</ComboBoxItem>
+                            <!--U-->
+                            <ComboBoxItem>U</ComboBoxItem>
+                            <!--V-->
+                            <ComboBoxItem>V</ComboBoxItem>
+                            <!--W-->
+                            <ComboBoxItem>W</ComboBoxItem>
+                            <!--X-->
+                            <ComboBoxItem>X</ComboBoxItem>
+                            <!--Y-->
+                            <ComboBoxItem>Y</ComboBoxItem>
+                            <!--Z-->
+                            <ComboBoxItem>Z</ComboBoxItem>
+                        </ComboBox>
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续模式}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  ItemsSource="{Binding Source={StaticResource eDurationMode}}"
+                                  SelectedItem="{Binding SingleSequenceAction5.DurationMode}" />
+                    </DockPanel>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility5_2}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续时间}" />
+                        <local:myNumericUpDowm Width="96"
+                                               Interval="1"
+                                               Maximum="{Binding SingleSequenceAction5.Max,Mode=TwoWay}"
+                                               Minimum="1"
+                                               StringFormat="{Binding SingleSequenceAction5.Format,Mode=TwoWay}"
+                                               Value="{Binding SingleSequenceAction5.DurationValue,Mode=TwoWay}" />
+                    </DockPanel>
+
+                </StackPanel>
+                <StackPanel Orientation="Horizontal">
+                    <TextBlock Margin="5,5"
+                               VerticalAlignment="Center"
+                               Text="{lex:Loc 动作,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}6'}" />
+                    <ComboBox x:Name="ActionComboBox6"
+                              Width="100"
+                              MinWidth="60"
+                              Margin="5,5"
+                              HorizontalContentAlignment="Center"
+                              ItemsSource="{Binding Source={StaticResource eActionType}}"
+                              SelectedItem="{Binding SingleSequenceAction6.Type}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectActionCommand6}"
+                                                              CommandParameter="{Binding ElementName=ActionComboBox6, Path=SelectedIndex}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility6}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 程序选择}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  SelectedIndex="{Binding SingleSequenceAction6.ShakeId}">
+                            <!--A-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="A"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowLeftBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--B-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="B"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--C-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="C"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--D-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="D"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowDownBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--E-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="E"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowUpBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--F-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="F"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowRightBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--G-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="G"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--H-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="H"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--I-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="I"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowExpandAll"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--J-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="J"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseHorizontal"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--K-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="K"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseVertical"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--L-->
+                            <ComboBoxItem>L</ComboBoxItem>
+                            <!--M-->
+                            <ComboBoxItem>M</ComboBoxItem>
+                            <!--N-->
+                            <ComboBoxItem>N</ComboBoxItem>
+                            <!--O-->
+                            <ComboBoxItem>O</ComboBoxItem>
+                            <!--P-->
+                            <ComboBoxItem>P</ComboBoxItem>
+                            <!--Q-->
+                            <ComboBoxItem>Q</ComboBoxItem>
+                            <!--R-->
+                            <ComboBoxItem>R</ComboBoxItem>
+                            <!--S-->
+                            <ComboBoxItem>S</ComboBoxItem>
+                            <!--T-->
+                            <ComboBoxItem>T</ComboBoxItem>
+                            <!--U-->
+                            <ComboBoxItem>U</ComboBoxItem>
+                            <!--V-->
+                            <ComboBoxItem>V</ComboBoxItem>
+                            <!--W-->
+                            <ComboBoxItem>W</ComboBoxItem>
+                            <!--X-->
+                            <ComboBoxItem>X</ComboBoxItem>
+                            <!--Y-->
+                            <ComboBoxItem>Y</ComboBoxItem>
+                            <!--Z-->
+                            <ComboBoxItem>Z</ComboBoxItem>
+                        </ComboBox>
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续模式}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  ItemsSource="{Binding Source={StaticResource eDurationMode}}"
+                                  SelectedItem="{Binding SingleSequenceAction6.DurationMode}" />
+
+                    </DockPanel>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility6_2}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续时间}" />
+                        <local:myNumericUpDowm Width="96"
+                                               Interval="1"
+                                               Maximum="{Binding SingleSequenceAction6.Max,Mode=TwoWay}"
+                                               Minimum="1"
+                                               StringFormat="{Binding SingleSequenceAction6.Format,Mode=TwoWay}"
+                                               Value="{Binding SingleSequenceAction6.DurationValue,Mode=TwoWay}" />
+                    </DockPanel>
+
+                </StackPanel>
+                <StackPanel Orientation="Horizontal">
+                    <TextBlock Margin="5,5"
+                               VerticalAlignment="Center"
+                               Text="{lex:Loc 动作,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}7'}" />
+                    <ComboBox x:Name="ActionComboBox7"
+                              Width="100"
+                              MinWidth="60"
+                              Margin="5,5"
+                              HorizontalContentAlignment="Center"
+                              ItemsSource="{Binding Source={StaticResource eActionType}}"
+                              SelectedItem="{Binding SingleSequenceAction7.Type}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="SelectionChanged">
+                                <behavior:InvokeCommandAction Command="{Binding SelectActionCommand7}"
+                                                              CommandParameter="{Binding ElementName=ActionComboBox7, Path=SelectedIndex}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </ComboBox>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility7}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 程序选择}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  SelectedIndex="{Binding SingleSequenceAction7.ShakeId}">
+                            <!--A-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="A"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowLeftBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--B-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="B"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--C-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="C"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopLeftThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--D-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="D"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowDownBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--E-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="E"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowUpBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--F-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="F"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowRightBold"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--G-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="G"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowBottomRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--H-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="H"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowTopRightThick"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--I-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="I"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowExpandAll"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--J-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="J"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseHorizontal"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--K-->
+                            <ComboBoxItem>
+                                <StackPanel Orientation="Horizontal">
+                                    <TextBlock Text="K"
+                                               VerticalAlignment="Center" />
+                                    <materialDesign:PackIcon Kind="ArrowCollapseVertical"
+                                                             Margin="5,0" />
+                                </StackPanel>
+                            </ComboBoxItem>
+                            <!--L-->
+                            <ComboBoxItem>L</ComboBoxItem>
+                            <!--M-->
+                            <ComboBoxItem>M</ComboBoxItem>
+                            <!--N-->
+                            <ComboBoxItem>N</ComboBoxItem>
+                            <!--O-->
+                            <ComboBoxItem>O</ComboBoxItem>
+                            <!--P-->
+                            <ComboBoxItem>P</ComboBoxItem>
+                            <!--Q-->
+                            <ComboBoxItem>Q</ComboBoxItem>
+                            <!--R-->
+                            <ComboBoxItem>R</ComboBoxItem>
+                            <!--S-->
+                            <ComboBoxItem>S</ComboBoxItem>
+                            <!--T-->
+                            <ComboBoxItem>T</ComboBoxItem>
+                            <!--U-->
+                            <ComboBoxItem>U</ComboBoxItem>
+                            <!--V-->
+                            <ComboBoxItem>V</ComboBoxItem>
+                            <!--W-->
+                            <ComboBoxItem>W</ComboBoxItem>
+                            <!--X-->
+                            <ComboBoxItem>X</ComboBoxItem>
+                            <!--Y-->
+                            <ComboBoxItem>Y</ComboBoxItem>
+                            <!--Z-->
+                            <ComboBoxItem>Z</ComboBoxItem>
+                        </ComboBox>
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续模式}" />
+                        <ComboBox Width="100"
+                                  MinWidth="60"
+                                  Margin="5,5"
+                                  HorizontalContentAlignment="Center"
+                                  ItemsSource="{Binding Source={StaticResource eDurationMode}}"
+                                  SelectedItem="{Binding SingleSequenceAction7.DurationMode}" />
+
+                    </DockPanel>
+                    <DockPanel Margin="5"
+                               Visibility="{Binding IsVisibility7_2}">
+                        <TextBlock Margin="5,5"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 持续时间}" />
+                        <local:myNumericUpDowm Width="96"
+                                               Interval="1"
+                                               Maximum="{Binding SingleSequenceAction7.Max,Mode=TwoWay}"
+                                               Minimum="1"
+                                               StringFormat="{Binding SingleSequenceAction6.Format,Mode=TwoWay}"
+                                               Value="{Binding SingleSequenceAction7.DurationValue,Mode=TwoWay}" />
+                    </DockPanel>
+                </StackPanel>
+            </StackPanel>
+        </Grid>
+    </Viewbox>
+    
+</UserControl>

+ 697 - 0
TeamAAS-VM/Controls/FeederSequence.xaml.cs

@@ -0,0 +1,697 @@
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Security.Cryptography;
+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;
+using Team.FFFeederService.Enums;
+using Team.FFFeederService.Interfaces;
+using Team.FFFeederService.Models;
+using TeamAAS_VP;
+using TouchSocket.Core;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// FeederSequence.xaml 的交互逻辑
+    /// </summary>
+    public partial class FeederSequence : UserControl, INotifyPropertyChanged
+    {
+        private bool _manualStop = false;
+        public FeederSequence()
+        {
+            InitializeComponent();
+            this.DataContext = this;
+            SequenceCollection.Clear();
+            for (int i = 1; i <= 26; i++)
+            {
+                SequenceCollection.Add(i);
+                char chn = (char)('A' + i);
+            }
+        }
+
+        #region 属性
+        public IVoiceCoilMotorFeeder Feeder { get; set; }
+
+        private ObservableCollection<int> _SequenceCollection = new ObservableCollection<int>();
+
+        /// <summary>
+        /// 序列集
+        /// </summary>
+        public ObservableCollection<int> SequenceCollection
+        {
+            get { return _SequenceCollection; }
+            set { SetProperty(ref _SequenceCollection, value); }
+        }
+
+        private int _SelectedSequence = -1;
+        /// <summary>
+        /// 当前选中的序列
+        /// </summary>
+        public int SelectedSequence
+        {
+            get { return _SelectedSequence; }
+            set { SetProperty(ref _SelectedSequence, value); }
+        }
+
+        private int _CurrentSequencePartCntMax;
+        /// <summary>
+        /// 极限值
+        /// </summary>
+        public int CurrentSequencePartCntMax
+        {
+            get { return _CurrentSequencePartCntMax; }
+            set { SetProperty(ref _CurrentSequencePartCntMax, value); }
+        }
+
+        private int _CycleRunningTimes;
+
+        /// <summary>
+        /// 循环次数
+        /// </summary>
+        public int CycleRunningTimes
+        {
+            get { return _CycleRunningTimes; }
+            set { SetProperty(ref _CycleRunningTimes, value); }
+        }
+
+        private SingleSequenceActionGroup _CurrentSequenceActionGroup;
+
+        /// <summary>
+        /// 序列集
+        /// </summary>
+        public SingleSequenceActionGroup CurrentSequenceActionGroup
+        {
+            get { return _CurrentSequenceActionGroup; }
+            set { SetProperty(ref _CurrentSequenceActionGroup, value); }
+        }
+
+        private SingleSequenceAction _SingleSequenceAction1;
+        /// <summary>
+        /// 1
+        /// </summary>
+        public SingleSequenceAction SingleSequenceAction1
+        {
+            get { return _SingleSequenceAction1; }
+            set { SetProperty(ref _SingleSequenceAction1, value); }
+        }
+        private SingleSequenceAction _SingleSequenceAction2;
+        /// <summary>
+        /// 2
+        /// </summary>
+        public SingleSequenceAction SingleSequenceAction2
+        {
+            get { return _SingleSequenceAction2; }
+            set { SetProperty(ref _SingleSequenceAction2, value); }
+        }
+        private SingleSequenceAction _SingleSequenceAction3;
+        /// <summary>
+        /// 3
+        /// </summary>
+        public SingleSequenceAction SingleSequenceAction3
+        {
+            get { return _SingleSequenceAction3; }
+            set { SetProperty(ref _SingleSequenceAction3, value); }
+        }
+        private SingleSequenceAction _SingleSequenceAction4;
+        /// <summary>
+        /// 4
+        /// </summary>
+        public SingleSequenceAction SingleSequenceAction4
+        {
+            get { return _SingleSequenceAction4; }
+            set { SetProperty(ref _SingleSequenceAction4, value); }
+        }
+        private SingleSequenceAction _SingleSequenceAction5;
+        /// <summary>
+        /// 5
+        /// </summary>
+        public SingleSequenceAction SingleSequenceAction5
+        {
+            get { return _SingleSequenceAction5; }
+            set { SetProperty(ref _SingleSequenceAction5, value); }
+        }
+        private SingleSequenceAction _SingleSequenceAction6;
+        /// <summary>
+        /// 6
+        /// </summary>
+        public SingleSequenceAction SingleSequenceAction6
+        {
+            get { return _SingleSequenceAction6; }
+            set { SetProperty(ref _SingleSequenceAction6, value); }
+        }
+        private SingleSequenceAction _SingleSequenceAction7;
+        /// <summary>
+        /// 7
+        /// </summary>
+        public SingleSequenceAction SingleSequenceAction7
+        {
+            get { return _SingleSequenceAction7; }
+            set { SetProperty(ref _SingleSequenceAction7, value); }
+        }
+        #region 属性视图显示
+        private Visibility _IsVisibility1 = Visibility.Collapsed;
+
+        public Visibility IsVisibility1
+        {
+            get { return _IsVisibility1; }
+            set { SetProperty(ref _IsVisibility1, value); }
+        }
+
+        private Visibility _IsVisibility1_2 = Visibility.Collapsed;
+
+        public Visibility IsVisibility1_2
+        {
+            get { return _IsVisibility1_2; }
+            set { SetProperty(ref _IsVisibility1_2, value); }
+        }
+
+        private Visibility _IsVisibility2 = Visibility.Collapsed;
+
+        public Visibility IsVisibility2
+        {
+            get { return _IsVisibility2; }
+            set { SetProperty(ref _IsVisibility2, value); }
+        }
+
+        private Visibility _IsVisibility2_2 = Visibility.Collapsed;
+
+        public Visibility IsVisibility2_2
+        {
+            get { return _IsVisibility2_2; }
+            set { SetProperty(ref _IsVisibility2_2, value); }
+        }
+        private Visibility _IsVisibility3 = Visibility.Collapsed;
+
+        public Visibility IsVisibility3
+        {
+            get { return _IsVisibility3; }
+            set { SetProperty(ref _IsVisibility3, value); }
+        }
+
+        private Visibility _IsVisibility3_2 = Visibility.Collapsed;
+
+        public Visibility IsVisibility3_2
+        {
+            get { return _IsVisibility1_2; }
+            set { SetProperty(ref _IsVisibility1_2, value); }
+        }
+
+        private Visibility _IsVisibility4 = Visibility.Collapsed;
+
+        public Visibility IsVisibility4
+        {
+            get { return _IsVisibility4; }
+            set { SetProperty(ref _IsVisibility4, value); }
+        }
+
+        private Visibility _IsVisibility4_2 = Visibility.Collapsed;
+
+        public Visibility IsVisibility4_2
+        {
+            get { return _IsVisibility4_2; }
+            set { SetProperty(ref _IsVisibility4_2, value); }
+        }
+        private Visibility _IsVisibility5 = Visibility.Collapsed;
+
+        public Visibility IsVisibility5
+        {
+            get { return _IsVisibility5; }
+            set { SetProperty(ref _IsVisibility5, value); }
+        }
+
+        private Visibility _IsVisibility5_2 = Visibility.Collapsed;
+
+        public Visibility IsVisibility5_2
+        {
+            get { return _IsVisibility5_2; }
+            set { SetProperty(ref _IsVisibility5_2, value); }
+        }
+        private Visibility _IsVisibility6 = Visibility.Collapsed;
+
+        public Visibility IsVisibility6
+        {
+            get { return _IsVisibility6; }
+            set { SetProperty(ref _IsVisibility6, value); }
+        }
+
+        private Visibility _IsVisibility6_2 = Visibility.Collapsed;
+
+        public Visibility IsVisibility6_2
+        {
+            get { return _IsVisibility6_2; }
+            set { SetProperty(ref _IsVisibility6_2, value); }
+        }
+        private Visibility _IsVisibility7 = Visibility.Collapsed;
+
+        public Visibility IsVisibility7
+        {
+            get { return _IsVisibility7; }
+            set { SetProperty(ref _IsVisibility7, value); }
+        }
+
+        private Visibility _IsVisibility7_2 = Visibility.Collapsed;
+
+        public Visibility IsVisibility7_2
+        {
+            get { return _IsVisibility7_2; }
+            set { SetProperty(ref _IsVisibility7_2, value); }
+        }
+        #endregion
+        #endregion
+
+        #region 命令
+        private DelegateCommand _SelectSequenceCommand;
+        public DelegateCommand SelectSequenceCommand =>
+            _SelectSequenceCommand ?? (_SelectSequenceCommand = new DelegateCommand(ExecuteSelectSequenceCommand));
+
+        private DelegateCommand _StartCommand;
+        public DelegateCommand StartCommand =>
+            _StartCommand ?? (_StartCommand = new DelegateCommand(ExecuteStartCommand));
+
+        private DelegateCommand _StopCommand;
+        public DelegateCommand StopCommand =>
+            _StopCommand ?? (_StopCommand = new DelegateCommand(ExecuteStopCommand));
+
+        private DelegateCommand _WriteParamCommand;
+        public DelegateCommand WriteParamCommand =>
+            _WriteParamCommand ?? (_WriteParamCommand = new DelegateCommand(ExecuteWriteParamCommand));
+
+        private DelegateCommand<int?> _SelectActionCommand1;
+        public DelegateCommand<int?> SelectActionCommand1 =>
+            _SelectActionCommand1 ?? (_SelectActionCommand1 = new DelegateCommand<int?>(ExecuteSelectActionCommand1));
+
+        private DelegateCommand<int?> _SelectActionCommand2;
+        public DelegateCommand<int?> SelectActionCommand2 =>
+            _SelectActionCommand2 ?? (_SelectActionCommand2 = new DelegateCommand<int?>(ExecuteSelectActionCommand2));
+
+        private DelegateCommand<int?> _SelectActionCommand3;
+        public DelegateCommand<int?> SelectActionCommand3 =>
+            _SelectActionCommand3 ?? (_SelectActionCommand3 = new DelegateCommand<int?>(ExecuteSelectActionCommand3));
+        private DelegateCommand<int?> _SelectActionCommand4;
+        public DelegateCommand<int?> SelectActionCommand4 =>
+            _SelectActionCommand4 ?? (_SelectActionCommand4 = new DelegateCommand<int?>(ExecuteSelectActionCommand4));
+        private DelegateCommand<int?> _SelectActionCommand5;
+        public DelegateCommand<int?> SelectActionCommand5 =>
+            _SelectActionCommand5 ?? (_SelectActionCommand5 = new DelegateCommand<int?>(ExecuteSelectActionCommand5));
+        private DelegateCommand<int?> _SelectActionCommand6;
+        public DelegateCommand<int?> SelectActionCommand6 =>
+            _SelectActionCommand6 ?? (_SelectActionCommand6 = new DelegateCommand<int?>(ExecuteSelectActionCommand6));
+        private DelegateCommand<int?> _SelectActionCommand7;
+        public DelegateCommand<int?> SelectActionCommand7 =>
+            _SelectActionCommand7 ?? (_SelectActionCommand7 = new DelegateCommand<int?>(ExecuteSelectActionCommand7));
+        #endregion
+
+        #region 方法
+        /// <summary>
+        /// 选中序列时
+        /// </summary>
+        async void ExecuteSelectSequenceCommand()
+        {
+            if (SelectedSequence == -1)
+            {
+                return;
+            }
+            if (Feeder == null || !Feeder.IsConnected)
+            {
+                return;
+            }
+            try
+            {
+                var id = SelectedSequence;
+                CurrentSequenceActionGroup = await Feeder.GetSequenceGroupAsync(id);
+                CurrentSequencePartCntMax = CurrentSequenceActionGroup.PartCntMax;
+
+                SingleSequenceAction1 = CurrentSequenceActionGroup.SingleSequenceActions[0];
+                SingleSequenceAction2 = CurrentSequenceActionGroup.SingleSequenceActions[1];
+                SingleSequenceAction3 = CurrentSequenceActionGroup.SingleSequenceActions[2];
+                SingleSequenceAction4 = CurrentSequenceActionGroup.SingleSequenceActions[3];
+                SingleSequenceAction5 = CurrentSequenceActionGroup.SingleSequenceActions[4];
+                SingleSequenceAction6 = CurrentSequenceActionGroup.SingleSequenceActions[5];
+                SingleSequenceAction7 = CurrentSequenceActionGroup.SingleSequenceActions[6];
+
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("选中Feeder序列时时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 开始执行序列
+        /// </summary>
+        async void ExecuteStartCommand()
+        {
+            if (Feeder == null)
+            {
+                return;
+            }
+            if (SelectedSequence == -1)
+            {
+                return;
+            }
+            try
+            {
+                var needToExecute = CycleRunningTimes;
+                while (true)
+                {
+                    var value = await Feeder.StartOneSequenceAsync(SelectedSequence + 1);
+                    await Task.Delay(value);
+                    needToExecute--;
+                    if (needToExecute != 0 && !_manualStop) continue;
+                    _manualStop = !_manualStop;
+                    break;
+                }
+
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("执行Feeder序列时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 停止执行序列
+        /// </summary>
+        async void ExecuteStopCommand()
+        {
+            try
+            {
+                if (Feeder == null)
+                {
+                    return;
+                }
+
+                await Feeder.StopOneSequenceAsync();
+                _manualStop = true;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("停止Feeder序列时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 下载
+        /// </summary>
+        async void ExecuteWriteParamCommand()
+        {
+            try
+            {
+                var singleSequenceActions = new[]
+            {
+                SingleSequenceAction1,SingleSequenceAction2,SingleSequenceAction3,
+                SingleSequenceAction4,SingleSequenceAction5,SingleSequenceAction6,
+                SingleSequenceAction7
+            };
+                for (var i = 0; i < singleSequenceActions.Length; i++)
+                {
+                    await Feeder.SetSequenceAsync(SelectedSequence, i, singleSequenceActions[i]);
+                }
+                await Feeder.SaveSequenceAsync();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存Feeder序列时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 选择动作1时触发
+        /// </summary>
+        void ExecuteSelectActionCommand1(int? index)
+        {
+            switch (index)
+            {
+                case null:
+                    return;
+                case 1:
+                    IsVisibility1 = Visibility.Visible;
+                    IsVisibility1_2 = Visibility.Visible;
+                    break;
+                case 2:
+                    IsVisibility1 = Visibility.Visible;
+                    IsVisibility1_2 = Visibility.Visible;
+                    break;
+                case 3:
+                    IsVisibility1 = Visibility.Collapsed;
+                    IsVisibility1_2 = Visibility.Visible;
+                    break;
+                default:
+                    IsVisibility1 = Visibility.Collapsed;
+                    IsVisibility1_2 = Visibility.Collapsed;
+                    break;
+            }
+        }
+        /// <summary>
+        /// 选择动作2时触发
+        /// </summary>
+        void ExecuteSelectActionCommand2(int? index)
+        {
+            switch (index)
+            {
+                case null:
+                    return;
+                case 1:
+                    IsVisibility2 = Visibility.Visible;
+                    IsVisibility2_2 = Visibility.Visible;
+                    break;
+                case 2:
+                    IsVisibility2 = Visibility.Visible;
+                    IsVisibility2_2 = Visibility.Visible;
+                    break;
+                case 3:
+                    IsVisibility2 = Visibility.Collapsed;
+                    IsVisibility2_2 = Visibility.Visible;
+                    break;
+                default:
+                    IsVisibility2 = Visibility.Collapsed;
+                    IsVisibility2_2 = Visibility.Collapsed;
+                    break;
+            }
+        }
+
+        /// <summary>
+        /// 选择动作3时触发
+        /// </summary>
+        void ExecuteSelectActionCommand3(int? index)
+        {
+            switch (index)
+            {
+                case null:
+                    return;
+                case 1:
+                    IsVisibility3 = Visibility.Visible;
+                    IsVisibility3_2 = Visibility.Visible;
+                    break;
+                case 2:
+                    IsVisibility3 = Visibility.Visible;
+                    IsVisibility3_2 = Visibility.Visible;
+                    break;
+                case 3:
+                    IsVisibility3 = Visibility.Collapsed;
+                    IsVisibility3_2 = Visibility.Visible;
+                    break;
+                default:
+                    IsVisibility3 = Visibility.Collapsed;
+                    IsVisibility3_2 = Visibility.Collapsed;
+                    break;
+            }
+        }
+        /// <summary>
+        /// 选择动作4时触发
+        /// </summary>
+        void ExecuteSelectActionCommand4(int? index)
+        {
+            switch (index)
+            {
+                case null:
+                    return;
+                case 1:
+                    IsVisibility4 = Visibility.Visible;
+                    IsVisibility4_2 = Visibility.Visible;
+                    break;
+                case 2:
+                    IsVisibility4 = Visibility.Visible;
+                    IsVisibility4_2 = Visibility.Visible;
+                    break;
+                case 3:
+                    IsVisibility4 = Visibility.Collapsed;
+                    IsVisibility4_2 = Visibility.Visible;
+                    break;
+                default:
+                    IsVisibility4 = Visibility.Collapsed;
+                    IsVisibility4_2 = Visibility.Collapsed;
+                    break;
+            }
+        }
+        /// <summary>
+        /// 选择动作5时触发
+        /// </summary>
+        void ExecuteSelectActionCommand5(int? index)
+        {
+            switch (index)
+            {
+                case null:
+                    return;
+                case 1:
+                    IsVisibility5 = Visibility.Visible;
+                    IsVisibility5_2 = Visibility.Visible;
+                    break;
+                case 2:
+                    IsVisibility5 = Visibility.Visible;
+                    IsVisibility5_2 = Visibility.Visible;
+                    break;
+                case 3:
+                    IsVisibility5 = Visibility.Collapsed;
+                    IsVisibility5_2 = Visibility.Visible;
+                    break;
+                default:
+                    IsVisibility5 = Visibility.Collapsed;
+                    IsVisibility5_2 = Visibility.Collapsed;
+                    break;
+            }
+        }
+        /// <summary>
+        /// 选择动作6时触发
+        /// </summary>
+        void ExecuteSelectActionCommand6(int? index)
+        {
+            switch (index)
+            {
+                case null:
+                    return;
+                case 1:
+                    IsVisibility6 = Visibility.Visible;
+                    IsVisibility6_2 = Visibility.Visible;
+                    break;
+                case 2:
+                    IsVisibility6 = Visibility.Visible;
+                    IsVisibility6_2 = Visibility.Visible;
+                    break;
+                case 3:
+                    IsVisibility6 = Visibility.Collapsed;
+                    IsVisibility6_2 = Visibility.Visible;
+                    break;
+                default:
+                    IsVisibility6 = Visibility.Collapsed;
+                    IsVisibility6_2 = Visibility.Collapsed;
+                    break;
+            }
+        }
+        /// <summary>
+        /// 选择动作7时触发
+        /// </summary>
+        void ExecuteSelectActionCommand7(int? index)
+        {
+            switch (index)
+            {
+                case null:
+                    return;
+                case 1:
+                    IsVisibility7 = Visibility.Visible;
+                    IsVisibility7_2 = Visibility.Visible;
+                    break;
+                case 2:
+                    IsVisibility7 = Visibility.Visible;
+                    IsVisibility7_2 = Visibility.Visible;
+                    break;
+                case 3:
+                    IsVisibility7 = Visibility.Collapsed;
+                    IsVisibility7_2 = Visibility.Visible;
+                    break;
+                default:
+                    IsVisibility7 = Visibility.Collapsed;
+                    IsVisibility7_2 = Visibility.Collapsed;
+                    break;
+            }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 148 - 0
TeamAAS-VM/Controls/FeederSystemParam.xaml

@@ -0,0 +1,148 @@
+<UserControl x:Class="TeamAAS_VP.Controls.FeederSystemParam"
+             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.Controls"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="250"
+             d:DesignWidth="400"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <Viewbox Stretch="None">
+        <Grid Margin="10">
+            <StackPanel Margin="0,20">
+                <DockPanel Margin="0,5"
+                           HorizontalAlignment="Center"
+                           LastChildFill="False">
+                    <TextBlock Width="125"
+                               Margin="5,0"
+                               VerticalAlignment="Bottom"
+                               Text="{lex:Loc 背光超时时间,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                    <local:myNumericUpDowm x:Name="lighttimeout"
+                                           MinWidth="100"
+                                           Margin="5,0"
+                                           Maximum="65535"
+                                           Minimum="1"
+                                           StringFormat="{}{0:N0} ms"
+                                           Value="{Binding LightTimeOutValue,Mode=TwoWay}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="ValueChanged">
+                                <behavior:InvokeCommandAction Command="{Binding LightTimeOutValueChangedCommand}"
+                                                              CommandParameter="{Binding ElementName=lighttimeout, Path=Value}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </local:myNumericUpDowm>
+                </DockPanel>
+
+                <DockPanel Margin="0,5"
+                           HorizontalAlignment="Center"
+                           LastChildFill="False">
+                    <TextBlock Width="125"
+                               Margin="5,0"
+                               VerticalAlignment="Bottom"
+                               Text="{lex:Loc 光源亮度设定,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                    <local:myNumericUpDowm x:Name="lightValue"
+                                           MinWidth="100"
+                                           Margin="5,0"
+                                           Maximum="100"
+                                           Minimum="1"
+                                           Interval="1"
+                                           StringFormat="{}{0:N0} %"
+                                           Value="{Binding LightValue,Mode=TwoWay}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="ValueChanged">
+                                <behavior:InvokeCommandAction Command="{Binding LightValueChangedCommand}"
+                                                              CommandParameter="{Binding ElementName=lightValue, Path=Value}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </local:myNumericUpDowm>
+                </DockPanel>
+                <DockPanel Margin="0,5"
+                           HorizontalAlignment="Center"
+                           LastChildFill="False">
+                    <TextBlock Width="125"
+                               Margin="5,0"
+                               VerticalAlignment="Bottom"
+                               Text="{lex:Loc 闪烁时间,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                    <local:myNumericUpDowm x:Name="LightFlashTime"
+                                           MinWidth="100"
+                                           Margin="5,0"
+                                           Maximum="65535"
+                                           Minimum="1"
+                                           Interval="100"
+                                           StringFormat="{}{0:N0} ms"
+                                           Value="{Binding BackLightFlashTime,Mode=TwoWay}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="ValueChanged">
+                                <behavior:InvokeCommandAction Command="{Binding LightFlashTimeChangedCommand}"
+                                                              CommandParameter="{Binding ElementName=LightFlashTime, Path=Value}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </local:myNumericUpDowm>
+                </DockPanel>
+                <DockPanel Margin="0,5"
+                           HorizontalAlignment="Center"
+                           LastChildFill="False">
+                    <TextBlock Width="125"
+                               Margin="5,0"
+                               VerticalAlignment="Bottom"
+                               Text="{lex:Loc 平台振动超时,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                    <local:myNumericUpDowm x:Name="platShakeTimeout"
+                                           MinWidth="100"
+                                           Margin="5,0"
+                                           Maximum="65535"
+                                           Minimum="1"
+                                           Interval="100"
+                                           StringFormat="{}{0:N0} ms"
+                                           Value="{Binding PlatShakeTimeout ,Mode=TwoWay}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="ValueChanged">
+                                <behavior:InvokeCommandAction Command="{Binding PlatShakeTimeoutChangedCommand}"
+                                                              CommandParameter="{Binding ElementName=platShakeTimeout, Path=Value}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </local:myNumericUpDowm>
+                </DockPanel>
+                <DockPanel Margin="0,5"
+                           HorizontalAlignment="Center"
+                           LastChildFill="False">
+                    <TextBlock Width="125"
+                               Margin="5,0"
+                               VerticalAlignment="Bottom"
+                               Text="{lex:Loc 料斗振动超时,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}" />
+                    <local:myNumericUpDowm x:Name="UpperFeeder"
+                                           MinWidth="100"
+                                           Margin="5,0"
+                                           Maximum="65535"
+                                           Minimum="1"
+                                           StringFormat="{}{0:N0} ms"
+                                           Value="{Binding UpperFeederShakeTimeout,Mode=TwoWay}">
+                        <behavior:Interaction.Triggers>
+                            <behavior:EventTrigger EventName="ValueChanged">
+                                <behavior:InvokeCommandAction Command="{Binding UpperFeederShakeTimeoutChangedCommand}"
+                                                              CommandParameter="{Binding ElementName=UpperFeeder, Path=Value}" />
+                            </behavior:EventTrigger>
+                        </behavior:Interaction.Triggers>
+                    </local:myNumericUpDowm>
+
+                </DockPanel>
+                <Button Margin="10,10"
+                        MaxWidth="200"
+                        VerticalAlignment="Bottom"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Command="{Binding WriteCommand}"
+                        Content="{lex:Loc 保存}" />
+            </StackPanel>
+        </Grid>
+    </Viewbox>
+    
+</UserControl>

+ 318 - 0
TeamAAS-VM/Controls/FeederSystemParam.xaml.cs

@@ -0,0 +1,318 @@
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+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;
+using Team.FFFeederService.Interfaces;
+using TeamAAS_VP;
+using static NPOI.HSSF.Util.HSSFColor;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// FeederSystemParam.xaml 的交互逻辑
+    /// </summary>
+    public partial class FeederSystemParam : UserControl, INotifyPropertyChanged
+    {
+        private bool IsLoading = false;
+        public FeederSystemParam()
+        {
+            InitializeComponent();
+            this.DataContext = this;
+            this.Loaded += FeederSystemParam_Loaded;
+        }
+
+        #region 属性
+        public IVoiceCoilMotorFeeder Feeder { get; set; }
+
+        private ushort _LightTimeOutValue;
+
+        /// <summary>
+        /// 背光超时时长
+        /// </summary>
+        public ushort LightTimeOutValue
+        {
+            get { return _LightTimeOutValue; }
+            set { SetProperty(ref _LightTimeOutValue,value); }
+        }
+
+        private ushort _LightValue;
+        /// <summary>
+        /// 背光亮度
+        /// </summary>
+        public ushort LightValue
+        {
+            get { return _LightValue; }
+            set { SetProperty(ref _LightValue, value); }
+        }
+
+        private int _BackLightFlashTime;
+        /// <summary>
+        /// 背光闪烁时间
+        /// </summary>
+        public int BackLightFlashTime
+        {
+            get { return _BackLightFlashTime; }
+            set { SetProperty(ref _BackLightFlashTime, value); }
+        }
+
+        private int _PlatShakeTimeout;
+        /// <summary>
+        /// 平台振动超时
+        /// </summary>
+        public int PlatShakeTimeout
+        {
+            get { return _BackLightFlashTime; }
+            set { SetProperty(ref _BackLightFlashTime, value); }
+        }
+
+        private int _UpperFeederShakeTimeout;
+        /// <summary>
+        /// 料斗振动超时
+        /// </summary>
+        public int UpperFeederShakeTimeout
+        {
+            get { return _UpperFeederShakeTimeout; }
+            set { SetProperty(ref _UpperFeederShakeTimeout, value); }
+        }
+        #endregion
+
+        #region 命令
+        private DelegateCommand<double?> _LightTimeOutValueChangedCommand;
+        public DelegateCommand<double?> LightTimeOutValueChangedCommand =>
+            _LightTimeOutValueChangedCommand ?? (_LightTimeOutValueChangedCommand = new DelegateCommand<double?>(ExecuteLightTimeOutValueChangedCommand));
+
+        private DelegateCommand<double?> _LightValueChangedCommand;
+        public DelegateCommand<double?> LightValueChangedCommand =>
+            _LightValueChangedCommand ?? (_LightValueChangedCommand = new DelegateCommand<double?>(ExecuteLightValueChangedCommand));
+
+        private DelegateCommand<double?> _LightFlashTimeChangedCommand;
+        public DelegateCommand<double?> LightFlashTimeChangedCommand =>
+            _LightFlashTimeChangedCommand ?? (_LightFlashTimeChangedCommand = new DelegateCommand<double?>(ExecuteLightFlashTimeChangedCommand));
+
+        private DelegateCommand<double?> _PlatShakeTimeoutChangedCommand;
+        public DelegateCommand<double?> PlatShakeTimeoutChangedCommand =>
+            _PlatShakeTimeoutChangedCommand ?? (_PlatShakeTimeoutChangedCommand = new DelegateCommand<double?>(ExecutePlatShakeTimeoutChangedCommand));
+
+        private DelegateCommand<double?> _UpperFeederShakeTimeoutChangedCommand;
+        public DelegateCommand<double?> UpperFeederShakeTimeoutChangedCommand =>
+            _UpperFeederShakeTimeoutChangedCommand ?? (_UpperFeederShakeTimeoutChangedCommand = new DelegateCommand<double?>(ExecuteUpperFeederShakeTimeoutChangedCommand));
+
+        private DelegateCommand _WriteCommand;
+        public DelegateCommand WriteCommand =>
+            _WriteCommand ?? (_WriteCommand = new DelegateCommand(ExecuteWriteCommand));
+
+
+        #endregion
+
+        #region 方法
+
+        private async void FeederSystemParam_Loaded(object sender, RoutedEventArgs e)
+        {
+            if (Feeder == null || !Feeder.IsConnected) return;
+            IsLoading = true;
+            try
+            {
+                LightTimeOutValue = await Feeder.GetLightTimeoutAsync();
+                LightValue = await Feeder.GetLightBrightnessAsync();
+                BackLightFlashTime = await Feeder.GetBackLightFlashTimeAsync();
+                UpperFeederShakeTimeout = await Feeder.GetUpperFeederShakeTimeoutAsync();
+                PlatShakeTimeout = await Feeder.GetPlatShakeTimeoutAsync();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder系统参数加载时出错!", ex);
+            }
+            IsLoading = false;
+        }
+
+        /// <summary>
+        /// 背光超时时长修改时
+        /// </summary>
+        async void ExecuteLightTimeOutValueChangedCommand(double? lightvalue)
+        {
+            if (Feeder == null || !Feeder.IsConnected || IsLoading) return;
+            if (lightvalue == null) return;
+            try
+            {
+                await Feeder.SetLightTimeOutAsync((ushort)lightvalue);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder背光超时时长修改时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 背光亮度改变时
+        /// </summary>
+        async void ExecuteLightValueChangedCommand(double? lightvalue)
+        {
+            if (Feeder == null || !Feeder.IsConnected || IsLoading) return;
+            if (lightvalue==null) return;
+            try
+            {
+                await Feeder.SetLightValueToBufferAsync((ushort)lightvalue);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder背光亮度改变时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 背光闪烁时间改变时
+        /// </summary>
+        /// <param name="lightvalue"></param>
+        async void ExecuteLightFlashTimeChangedCommand(double? lightvalue)
+        {
+            if (Feeder == null || !Feeder.IsConnected || IsLoading) return;
+            if (lightvalue == null) return;
+            try
+            {
+                await Feeder.SetBackLightFlashTimeAsync((ushort)lightvalue);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder背光闪烁时间改变时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 平台振动超时改变时
+        /// </summary>
+        async void ExecutePlatShakeTimeoutChangedCommand(double? time)
+        {
+            if (Feeder == null || !Feeder.IsConnected || IsLoading) return;
+            if (time == null) return;
+            try
+            {
+                await Feeder.SetPlatShakeTimeoutAsync((ushort)time);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder平台振动超时改变时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 料斗振动超时改变时
+        /// </summary>
+        /// <param name="time"></param>
+        async void ExecuteUpperFeederShakeTimeoutChangedCommand(double? time)
+        {
+            if (Feeder == null || !Feeder.IsConnected || IsLoading) return;
+            if (time == null) return;
+            try
+            {
+                await Feeder.SetUpperFeederShakeTimeoutAsync((ushort)time);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder料斗振动超时时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存
+        /// </summary>
+        async void ExecuteWriteCommand()
+        {
+            if (Feeder == null || !Feeder.IsConnected || IsLoading) return;
+            try
+            {
+                await Feeder.SaveGlobalSetAsync();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder保存系统参数时出错!", ex);
+            }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 74 - 0
TeamAAS-VM/Controls/ParameterEdit.xaml

@@ -0,0 +1,74 @@
+<UserControl x:Class="TeamAAS_VP.Controls.ParameterEdit"
+             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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:local="clr-namespace:TeamAAS_VP.Controls"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="450"
+             d:DesignWidth="800"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+        <StackPanel Grid.Row="0"
+                    Orientation="Vertical">
+            <StackPanel Orientation="Horizontal">
+                <Button Content="{lex:Loc 增加}"
+                        Margin="10"
+                        Command="{Binding AddCommand}" />
+                <Button Content="{lex:Loc 移除}"
+                        Command="{Binding RemoveCommand}" 
+                        CommandParameter="{Binding ElementName=dg_params,Path=SelectedItem}"/>
+                <TextBlock Text="{lex:Loc 总数,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}: '}"
+                           VerticalAlignment="Center"
+                           Margin="20,0,0,0" />
+                <TextBlock Text="{Binding ElementName=dg_params,Path=Items.Count}" VerticalAlignment="Center" Margin="5,0" />
+            </StackPanel>
+        </StackPanel>
+        
+        <DataGrid x:Name="dg_params" Grid.Row="1" AutoGenerateColumns="False"
+                  CanUserAddRows="False"
+                  ColumnWidth="*"
+                  SelectionUnit="FullRow"
+                  SelectionMode="Single"
+                  SelectedItem="{Binding SelectParam}"
+                  ItemsSource="{Binding GlobalParamListCollection}"
+                  HeadersVisibility="All">
+            <DataGrid.Columns>
+                <DataGridTextColumn Header="{lex:Loc 编号}"
+                                    IsReadOnly="True"
+                                    MinWidth="60"
+                                    Binding="{Binding Number, Mode=TwoWay}">
+                </DataGridTextColumn>
+                <DataGridTextColumn Header="Name"
+                                    MinWidth="80"
+                                    Binding="{Binding Name, Mode=TwoWay}" />
+                <DataGridTextColumn Header="Param1"
+                                    MinWidth="80"
+                                    Binding="{Binding Param1, Mode=TwoWay}" />
+                <DataGridTextColumn Header="Param2"
+                                    MinWidth="80"
+                                    Binding="{Binding Param2, Mode=TwoWay}" />
+                <DataGridTextColumn Header="Param3"
+                                    MinWidth="80"
+                                    Binding="{Binding Param3, Mode=TwoWay}" />
+                <DataGridTextColumn Header="Param4"
+                                    MinWidth="80"
+                                    Binding="{Binding Param4, Mode=TwoWay}" />
+            </DataGrid.Columns>
+        </DataGrid>
+        
+    </Grid>
+</UserControl>

+ 147 - 0
TeamAAS-VM/Controls/ParameterEdit.xaml.cs

@@ -0,0 +1,147 @@
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+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;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// ParameterEdit.xaml 的交互逻辑
+    /// </summary>
+    public partial class ParameterEdit : UserControl, INotifyPropertyChanged
+    {
+        public ParameterEdit()
+        {
+            InitializeComponent();
+            DataContext = this;
+        }
+
+        private ProductGlobalParam _SelectParam;
+
+        public ProductGlobalParam SelectParam
+        {
+            get { return _SelectParam; }
+            set { SetProperty(ref _SelectParam,value); }
+        }
+
+
+        private ObservableCollection<ProductGlobalParam> _GlobalParamListCollection;
+        /// <summary>
+        /// 产品全局参数集合
+        /// </summary>
+        public ObservableCollection<ProductGlobalParam> GlobalParamListCollection
+        {
+            get { return _GlobalParamListCollection; }
+            set { SetProperty(ref _GlobalParamListCollection, value); }
+        }
+
+        private DelegateCommand _AddCommand;
+        public DelegateCommand AddCommand =>
+            _AddCommand ?? (_AddCommand = new DelegateCommand(ExecuteAddCommand));
+
+        private DelegateCommand<ProductGlobalParam> _RemoveCommand;
+        public DelegateCommand<ProductGlobalParam> RemoveCommand =>
+            _RemoveCommand ?? (_RemoveCommand = new DelegateCommand<ProductGlobalParam>(ExecuteRemoveCommand));
+
+        void ExecuteRemoveCommand(ProductGlobalParam param)
+        {
+            GlobalParamListCollection.Remove(param);
+            for (int i = 0; i < GlobalParamListCollection.Count; i++)
+            {
+                GlobalParamListCollection[i].Number = i;
+            }
+        }
+
+        void ExecuteAddCommand()
+        {
+            GlobalParamListCollection.Add(new ProductGlobalParam() { Number= GlobalParamListCollection .Count});
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 36 - 0
TeamAAS-VM/Controls/PictureDisplayControl.xaml

@@ -0,0 +1,36 @@
+<UserControl x:Class="TeamAAS_VP.Controls.PictureDisplayControl"
+             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.Controls"
+             mc:Ignorable="d">
+    <Grid>
+        <ScrollViewer x:Name="Sv"
+                      HorizontalScrollBarVisibility="Auto"
+                      VerticalScrollBarVisibility="Auto"
+                      Background="#242424">
+            <Viewbox x:Name="Box"
+                     Stretch="Uniform"
+                     Margin="10"
+                     MouseWheel="Viewbox_MouseWheel"
+                     PreviewMouseLeftButtonDown="Viewbox_PreviewMouseLeftButtonDown"
+                     PreviewMouseLeftButtonUp="Viewbox_PreviewMouseLeftButtonUp"
+                     PreviewMouseMove="Viewbox_PreviewMouseMove">
+                <Viewbox.RenderTransform>
+                    <MatrixTransform>
+                        <MatrixTransform.Matrix>
+                            <Matrix OffsetX="0"
+                                    OffsetY="0" />
+                        </MatrixTransform.Matrix>
+                    </MatrixTransform>
+                </Viewbox.RenderTransform>
+                <Grid>
+                    <Image x:Name="Img"></Image>
+                    <!--<Border BorderBrush="Green"
+                            BorderThickness="1" />-->
+                </Grid>
+            </Viewbox>
+        </ScrollViewer>
+    </Grid>
+</UserControl>

+ 154 - 0
TeamAAS-VM/Controls/PictureDisplayControl.xaml.cs

@@ -0,0 +1,154 @@
+using OxyPlot;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Eventing.Reader;
+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.Controls
+{
+    /// <summary>
+    /// PictureDisplayControl.xaml 的交互逻辑
+    /// </summary>
+    public partial class PictureDisplayControl : UserControl
+    {
+        private bool _startMove;
+        private Point _start;
+        private bool _isFirst = true;
+
+        public PictureDisplayControl()
+        {
+            InitializeComponent();
+            Loaded+=(s, e) =>
+            {
+                FitImageToControl();
+            };
+        }
+
+        public BitmapSource Image
+        {
+            get { return (BitmapSource)GetValue(ImageProperty); }
+            set { SetValue(ImageProperty, value);
+                if (value != null)
+                {
+                    FitImageToControl();
+                }
+                //if (_isFirst && value!=null)
+                //{
+                //    FitImageToControl();
+                //    _isFirst = false;
+                //}
+            }
+        }
+
+        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty ImageProperty =
+            DependencyProperty.Register("Image", typeof(BitmapSource), typeof(PictureDisplayControl), new PropertyMetadata(null, new PropertyChangedCallback(ImageValueChanged)));
+
+        private static void ImageValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        {
+            PictureDisplayControl obj = (PictureDisplayControl)d;
+            if (obj != null)
+            {
+                obj.Update(e.NewValue as BitmapSource);
+            }
+        }
+
+        private void Update(BitmapSource bitmap)
+        {
+            App.Current.Dispatcher.Invoke(() =>
+            {
+                if (bitmap != null)
+                {
+                    this.Img.Source = bitmap;
+                    FitImageToControl();
+                }
+                else
+                {
+                    this.Img.Source = bitmap;
+                }
+            });
+        }
+
+        private void Viewbox_MouseWheel(object sender, MouseWheelEventArgs e)
+        {
+            var centerPt = e.GetPosition(Box);
+            ChangSize(e.Delta > 0, Box, centerPt.X, centerPt.Y);
+            e.Handled = true; //避免缩放时同时影响滚动条;
+        }
+
+        private void Viewbox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            if (Box.IsMouseCaptured) return;
+            Box.CaptureMouse();
+            _start = e.MouseDevice.GetPosition(Sv);
+            e.Handled = true;
+            _startMove = true;
+        }
+
+        private void Viewbox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
+        {
+            Box.ReleaseMouseCapture();
+            _startMove = false;
+        }
+
+        private void Viewbox_PreviewMouseMove(object sender, MouseEventArgs e)
+        {
+            if (!Box.IsMouseCaptured || !_startMove) return;
+            var point = e.MouseDevice.GetPosition(Sv);
+            var m = Box.RenderTransform.Value;
+            //计算x偏移量 
+            m.OffsetX = m.OffsetX + point.X - _start.X;
+            //计算y偏移量
+            m.OffsetY = m.OffsetY + point.Y - _start.Y;
+            Box.RenderTransform = new MatrixTransform(m);
+            //给鼠标起点和图片临时位置重新赋值
+            _start = point;
+        }
+
+        private void ChangSize(bool big, FrameworkElement ctrl, double centerX, double centerY)
+        {
+            var m = ((MatrixTransform)ctrl.RenderTransform).Matrix;
+            if (big)
+            {
+                m.ScaleAtPrepend(1.1, 1.1, centerX, centerY);
+            }
+            else
+            {
+                m.ScaleAtPrepend(1 / 1.1, 1 / 1.1, centerX, centerY);
+            }
+            ctrl.RenderTransform = new MatrixTransform(m);
+        }
+
+        private void FitImageToControl()
+        {
+            if (Image==null)
+            {
+                return;  
+            }
+            var imageWidth = Image.PixelWidth;
+            var imageHeight = Image.PixelHeight;
+            var controlWidth = this.ActualWidth;
+            var controlHeight = this.ActualHeight;
+
+            double scaleX = controlWidth / imageWidth;
+            double scaleY = controlHeight / imageHeight;
+            double scale = Math.Min(scaleX, scaleY);
+
+            var m = new Matrix();
+            m.Scale(scale, scale);
+            m.Translate((controlWidth - imageWidth * scale) / 2, (controlHeight - imageHeight * scale) / 2);
+            Box.RenderTransform = new MatrixTransform(m);
+        }
+    }
+}

+ 230 - 0
TeamAAS-VM/Controls/RobotManual.xaml

@@ -0,0 +1,230 @@
+<UserControl x:Class="TeamAAS_VP.Controls.RobotManual"
+             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.Controls"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:uControl="clr-namespace:TeamAAS_VP.Controls"
+             xmlns:convert="clr-namespace:TeamAAS_VP.ValueConverter"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <UserControl.Resources>
+        <convert:JogConverter x:Key="JogConverter" />
+    </UserControl.Resources>
+    <Grid VerticalAlignment="Center">
+        <Grid VerticalAlignment="Center">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="auto" />
+                <ColumnDefinition Width="*" />
+            </Grid.ColumnDefinitions>
+
+            <Grid Grid.Column="0">
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                </Grid.RowDefinitions>
+                <Button Content="{lex:Loc 连接}"
+                        Grid.Row="0"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding ConnectCommand}" />
+                <Button Content="{lex:Loc 断开连接}"
+                        Grid.Row="1"
+                        Margin="0,10,0,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding DisConnectCommand}" />
+                <Button Content="{lex:Loc 上使能}"
+                        Grid.Row="2"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding MotorCommand}"
+                        CommandParameter="True" />
+                <Button Content="{lex:Loc 下使能}"
+                        Grid.Row="3"
+                        Margin="0,10,0,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding MotorCommand}"
+                        CommandParameter="False" />
+                <Button Content="{lex:Loc 复位错误}"
+                        Grid.Row="4"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding ResetCommand}" />
+                <Button Content="{lex:Loc 释放刹车}"
+                        Grid.Row="5"
+                        Margin="0,10,0,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding sFreeCommand}" />
+                <Button Content="{lex:Loc 锁定刹车}"
+                        Grid.Row="6"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding SLockCommand}" />
+            </Grid>
+
+            <Grid Grid.Column="1"
+                  Margin="20">
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="auto" />
+                    <ColumnDefinition Width="auto" />
+                    <ColumnDefinition Width="auto" />
+                    <ColumnDefinition Width="auto" />
+                </Grid.ColumnDefinitions>
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                    <RowDefinition Height="auto" />
+                </Grid.RowDefinitions>
+                <ComboBox Grid.Column="0"
+                          Grid.Row="0"
+                          Margin="10,5"
+                          materialDesign:HintAssist.Hint="{lex:Loc 选择Tool}"
+                          materialDesign:HintAssist.HelperText="{lex:Loc 选择Tool}"
+                          SelectedItem="{Binding SelectTool,Mode=TwoWay}"
+                          ItemsSource="{Binding Tools}" />
+                <Button Content="X-"
+                        Grid.Row="2"
+                        Grid.Column="0"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=X-}" />
+                <Button Content="X+"
+                        Grid.Row="2"
+                        Grid.Column="2"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=X+}" />
+                <Button Content="Y+"
+                        Grid.Row="1"
+                        Grid.Column="1"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=Y+}" />
+                <Button Content="Y-"
+                        Grid.Row="3"
+                        Grid.Column="1"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=Y-}" />
+                <Button Content="Z+"
+                        Grid.Row="1"
+                        Grid.Column="3"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=Z+}" />
+                <Button Content="Z-"
+                        Grid.Row="3"
+                        Grid.Column="3"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=Z-}" />
+                <Button Content="U+"
+                        Grid.Row="4"
+                        Grid.Column="0"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=U+}" />
+                <Button Content="U-"
+                        Grid.Row="5"
+                        Grid.Column="0"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=U-}" />
+                <Button Content="V+"
+                        Grid.Row="4"
+                        Grid.Column="1"
+                        Grid.ColumnSpan="2"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=V+}" />
+                <Button Content="V-"
+                        Grid.Row="5"
+                        Grid.Column="1"
+                        Grid.ColumnSpan="2"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=V-}" />
+                <Button Content="W+"
+                        Grid.Row="4"
+                        Grid.Column="3"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=W+}" />
+                <Button Content="W-"
+                        Grid.Row="5"
+                        Grid.Column="3"
+                        Margin="10,10,10,10"
+                        materialDesign:ButtonAssist.CornerRadius="10"
+                        Style="{StaticResource MaterialDesignRaisedDarkButton}"
+                        Command="{Binding JogCommand}"
+                        CommandParameter="{Binding ElementName=txtDistance,Path=Value,Converter={StaticResource JogConverter}, ConverterParameter=W-}" />
+                <StackPanel Grid.Row="6"
+                            Grid.ColumnSpan="7"
+                            Margin="10,10,0,10"
+                            Grid.Column="0"
+                            VerticalAlignment="Center"
+                            Orientation="Horizontal">
+                    <TextBlock Text="{lex:Loc 步进距离}"
+                               VerticalAlignment="Center" />
+                    <uControl:myNumericUpDowm x:Name="txtDistance"
+                                              MinWidth="100"
+                                              Interval="0.1"
+                                              Minimum="0"
+                                              Maximum="100"
+                                              StringFormat="{}{0:N3} mm"
+                                              Value="{Binding Distance,Mode=TwoWay}"
+                                              Margin="10,0" />
+                </StackPanel>
+            </Grid>
+
+
+        </Grid>
+        <materialDesign:Snackbar x:Name="snackbar"
+                                 Opacity="0.9"
+                                 HorizontalContentAlignment="Center"
+                                 VerticalAlignment="Bottom" />
+    </Grid>
+</UserControl>

+ 472 - 0
TeamAAS-VM/Controls/RobotManual.xaml.cs

@@ -0,0 +1,472 @@
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+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;
+using TeamAAS_VP.Events;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.ViewModels;
+using TeamAAS_VP;
+using System.Collections.ObjectModel;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Core.Robots;
+using TeamAAS_VP.Resources.Languages;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// RobotManual.xaml 的交互逻辑
+    /// </summary>
+    public partial class RobotManual : UserControl,INotifyPropertyChanged
+    {
+        public RobotManual()
+        {
+            InitializeComponent();
+            DataContext = this;
+            this.Loaded += RobotManual_Loaded;
+        }
+
+        private void RobotManual_Loaded(object sender, RoutedEventArgs e)
+        {
+
+        }
+
+        #region 属性
+        private IRobot _Robot;
+
+        public IRobot Robot
+        {
+            get { return _Robot; }
+            set { SetProperty(ref _Robot,value);
+                try
+                {
+                    var config = FileHelper.ReadApplicationConfiguration();
+                    if (config.RobotJogSetpDistance.TryGetValue(value.Id,out double distance))
+                    {
+                        this.Distance = distance;
+                    }
+                    if (value is FanucRobot)
+                    {
+                        Tools = new ObservableCollection<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
+                        SelectTool = Robot.SelectedTool;
+                    }
+                    else
+                    {
+                        Tools = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
+                        SelectTool = Robot.SelectedTool;
+                    }
+                }
+                catch (Exception)
+                {
+
+                }
+            }
+        }
+
+        private double _Distance=1;
+
+        public double Distance
+        {
+            get { return _Distance; }
+            set { SetProperty(ref _Distance, value); 
+                try
+                {
+                    if (Robot==null)
+                    {
+                        return;
+                    }
+                    var config = FileHelper.ReadApplicationConfiguration();
+                    if (config.RobotJogSetpDistance.ContainsKey(Robot.Id))
+                    {
+                        config.RobotJogSetpDistance[Robot.Id] =value;
+                    }
+                    else
+                    {
+                        config.RobotJogSetpDistance.Add(Robot.Id,value);
+                    }
+                    FileHelper.SaveApplicationConfiguration(config);
+                }
+                catch (Exception)
+                {
+
+                }
+            }
+        }
+
+        private ObservableCollection<int> _Tools = new ObservableCollection<int>();
+        /// <summary>
+        /// 机器人Tool集合
+        /// </summary>
+        public ObservableCollection<int> Tools
+        {
+            get { return _Tools; }
+            set { SetProperty(ref _Tools, value); }
+        }
+
+        private int _SelectTool;
+        /// <summary>
+        /// 选中的Tool
+        /// </summary>
+        public int SelectTool
+        {
+            get { return _SelectTool; }
+            set
+            {
+                SetProperty(ref _SelectTool, value);
+                if (value >= 0)
+                {
+                    if (Robot != null && Robot.IsConnected)
+                    {
+                        try
+                        {
+                            Robot.SelectToolAsync(value);
+                        }
+                        catch (Exception)
+                        {
+
+                        }
+                    }
+                }
+            }
+        }
+        #endregion
+
+        #region 命令
+
+        private DelegateCommand _ConnectCommand;
+        public DelegateCommand ConnectCommand =>
+            _ConnectCommand ?? (_ConnectCommand = new DelegateCommand(ExecuteConnectCommand));
+
+
+
+        private DelegateCommand _DisConnectCommand;
+        public DelegateCommand DisConnectCommand =>
+            _DisConnectCommand ?? (_DisConnectCommand = new DelegateCommand(ExecuteDisConnectCommand));
+
+
+
+        private DelegateCommand<string> _MotorCommand;
+        public DelegateCommand<string> MotorCommand =>
+            _MotorCommand ?? (_MotorCommand = new DelegateCommand<string>(ExecuteMotorCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(()=>Robot).ObservesProperty(() => Robot.CanExecute));
+
+
+
+        private DelegateCommand _ResetCommand;
+        public DelegateCommand ResetCommand =>
+            _ResetCommand ?? (_ResetCommand = new DelegateCommand(ExecuteResetCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute));
+
+
+
+        private DelegateCommand<object> _JogCommand;
+        public DelegateCommand<object> JogCommand =>
+            _JogCommand ?? (_JogCommand = new DelegateCommand<object>(ExecuteJogCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute));
+
+        private DelegateCommand _sFreeCommand;
+        public DelegateCommand sFreeCommand =>
+            _sFreeCommand ?? (_sFreeCommand = new DelegateCommand(ExecutesFreeCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute));
+
+        private DelegateCommand _SLockCommand;
+        public DelegateCommand SLockCommand =>
+            _SLockCommand ?? (_SLockCommand = new DelegateCommand(ExecuteSLockCommand).ObservesCanExecute(() => CanExecute).ObservesProperty(() => Robot).ObservesProperty(() => Robot.CanExecute));
+        #endregion
+
+        #region 事件
+
+        #endregion
+
+        #region 方法
+
+        private void ShowMsg(string msg)
+        {
+            if (snackbar.MessageQueue==null)
+            {
+                snackbar.MessageQueue = new MaterialDesignThemes.Wpf.SnackbarMessageQueue();
+            }
+            snackbar.MessageQueue?.Enqueue(
+                msg,
+                null,
+                null,
+                null,
+                false,
+                true,
+                TimeSpan.FromSeconds(1));
+        }
+        /// <summary>
+        /// 连接机器人
+        /// </summary>
+        private async void ExecuteConnectCommand()
+        {
+            if (Robot == null || !Robot.IsConnected) return;
+            try
+            {
+                await Robot.ConnectAsync();
+                ShowMsg($"{Lang.完成}!");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("连接机器人时出错!",ex);
+                ShowMsg(ex.Message);
+            }
+        }
+
+        /// <summary>
+        /// 断开机器人
+        /// </summary>
+        private void ExecuteDisConnectCommand()
+        {
+            if (Robot == null || !Robot.IsConnected) return;
+            try
+            {
+                Robot.Disconnect();
+                ShowMsg($"{Lang.完成}!");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("断开机器人时出错!", ex);
+                ShowMsg(ex.Message);
+            }
+        }
+
+        /// <summary>
+        /// 电机
+        /// </summary>
+        /// <param name="obj"></param>
+        private async void ExecuteMotorCommand(string obj)
+        {
+            if (Robot == null || !Robot.IsConnected) return;
+            try
+            {
+                await Robot.MotorAsync(Convert.ToBoolean(obj));
+                ShowMsg($"{Lang.完成}!");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("机器人点击操作时出错!", ex);
+                ShowMsg(ex.Message);
+            }
+        }
+
+        /// <summary>
+        /// 重置
+        /// </summary>
+        private async void ExecuteResetCommand()
+        {
+            if (Robot == null || !Robot.IsConnected) return;
+            try
+            {
+                await Robot.ResetAsync();
+                
+                ShowMsg($"{Lang.完成}!");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("重置机器人时出错!", ex);
+                ShowMsg(ex.Message);
+            }
+        }
+
+        /// <summary>
+        /// 点动
+        /// </summary>
+        /// <param name="obj"></param>
+        private async void ExecuteJogCommand(object obj)
+        {
+            if (Robot == null || !Robot.IsConnected) return;
+            try
+            {
+                Robot.Timeout = 6000000;
+                var items = ((string)obj).Split(':');
+                switch (items[0])
+                {
+                    case "X+":
+                        await Robot.JogAsync("X", double.Parse(items[1]));
+                        break;
+                    case "X-":
+                        await Robot.JogAsync("X", -double.Parse(items[1]));
+                        break;
+                    case "Y+":
+                        await Robot.JogAsync("Y", double.Parse(items[1]));
+                        break;
+                    case "Y-":
+                        await Robot.JogAsync("Y", -double.Parse(items[1]));
+                        break;
+                    case "Z+":
+                        await Robot.JogAsync("Z", double.Parse(items[1]));
+                        break;
+                    case "Z-":
+                        await Robot.JogAsync("Z", -double.Parse(items[1]));
+                        break;
+                    case "U+":
+                        await Robot.JogAsync("U", double.Parse(items[1]));
+                        break;
+                    case "U-":
+                        await Robot.JogAsync("U", -double.Parse(items[1]));
+                        break;
+                    case "V+":
+                        await Robot.JogAsync("V", double.Parse(items[1]));
+                        break;
+                    case "V-":
+                        await Robot.JogAsync("V", -double.Parse(items[1]));
+                        break;
+                    case "W+":
+                        await Robot.JogAsync("W", double.Parse(items[1]));
+                        break;
+                    case "W-":
+                        await Robot.JogAsync("W", -double.Parse(items[1]));
+                        break;
+                    default:
+                        break;
+                }
+                Robot.Timeout = 5000;
+
+                
+                ShowMsg($"{Lang.完成}!");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("机器点动时出错!", ex);
+                ShowMsg(ex.Message);
+            }
+        }
+
+        /// <summary>
+        /// 锁定刹车
+        /// </summary>
+        private async void ExecuteSLockCommand()
+        {
+            if (Robot == null || !Robot.IsConnected) return;
+            try
+            {
+                await Robot.SLockAsync();
+                
+                ShowMsg($"{Lang.完成}!");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("机器人锁定刹车时出错!", ex);
+                ShowMsg(ex.Message);
+            }
+        }
+
+        /// <summary>
+        /// 释放刹车
+        /// </summary>
+        private async void ExecutesFreeCommand()
+        {
+            if (Robot == null || !Robot.IsConnected) return;
+            try
+            {
+                await Robot.SFreeAsync();
+                
+                ShowMsg($"{Lang.完成}!");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("机器人释放刹车时出错!", ex);
+                ShowMsg(ex.Message);
+            }
+        }
+
+        private bool CanExecute
+        {
+            get
+            {
+                if (Robot != null)
+                {
+                    return Robot.CanExecute;
+                }
+                else
+                {
+                    return false;
+                }
+            }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 224 - 0
TeamAAS-VM/Controls/ScriptEditControl.xaml

@@ -0,0 +1,224 @@
+<UserControl x:Class="TeamAAS_VP.Controls.ScriptEditControl"
+             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:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
+             xmlns:AvalonEdit="clr-namespace:ICSharpCode.AvalonEdit;assembly=ICSharpCode.AvalonEdit"
+             xmlns:local="clr-namespace:TeamAAS_VP.Controls"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="450"
+             d:DesignWidth="1000"
+             d:Background="White">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="auto" />
+            <RowDefinition Height="*" />
+            <RowDefinition Height="100" />
+        </Grid.RowDefinitions>
+        <ToolBar Grid.Row="0">
+            <ToolBar.Resources>
+                <Style TargetType="{x:Type Image}">
+                    <Style.Triggers>
+                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ButtonBase}, AncestorLevel=1}, Path=IsEnabled}"
+                                     Value="False">
+                            <Setter Property="Opacity"
+                                    Value="0.30" />
+                        </DataTrigger>
+                    </Style.Triggers>
+                </Style>
+            </ToolBar.Resources>
+            <Button x:Name="btn1"
+                    Click="Button_Click"
+                    ToolTip="{lex:Loc 打开脚本文件}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/Open.png"
+                       Height="16" />
+            </Button>
+            <Button x:Name="btn2"
+                    Click="Button_Click_1"
+                    ToolTip="{lex:Loc 保存脚本}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/Save.png"
+                       Height="16" />
+            </Button>
+            <Button x:Name="btn3"
+                    Click="Button_Click_2"
+                    ToolTip="{lex:Loc 另存为}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/SaveAs.png"
+                       Height="16" />
+            </Button>
+            <Separator />
+            <Button x:Name="btn4"
+                    Command="Cut"
+                    ToolTip="{lex:Loc 剪切}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/Cut.png"
+                       Height="16" />
+            </Button>
+            <Button x:Name="btn5"
+                    Command="Copy"
+                    ToolTip="{lex:Loc 复制}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/Copy.png"
+                       Height="16" />
+            </Button>
+            <Button x:Name="btn6"
+                    Command="Paste"
+                    ToolTip="{lex:Loc 粘贴}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/Paste.png"
+                       Height="16" />
+            </Button>
+            <Button  x:Name="btn7"
+                     Command="Delete"
+                     ToolTip="{lex:Loc 删除}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/Delete.png"
+                       Height="16" />
+            </Button>
+            <Separator />
+            <Button  x:Name="btn8"
+                     Command="Undo"
+                     ToolTip="{lex:Loc 撤销}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/Undo.png"
+                       Height="16" />
+            </Button>
+            <Button  x:Name="btn9"
+                     Command="Redo"
+                     ToolTip="{lex:Loc 重做}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/Redo.png"
+                       Height="16" />
+            </Button>
+            <Separator />
+            <Button  x:Name="btn10"
+                     Click="Button_Click_3">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/FontAdd.png"
+                       Height="16" />
+            </Button>
+            <Button  x:Name="btn11"
+                     Click="Button_Click_4">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/FontSubtract.png"
+                       Height="16" />
+            </Button>
+            <Separator />
+            <ToggleButton  x:Name="btnWordWrap"
+                           IsChecked="{Binding ElementName=textEditor,Path=WordWrap}"
+                           Style="{StaticResource MaterialDesignFlatToggleButton}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/WordWrap.png"
+                       Height="16" />
+            </ToggleButton>
+            <ToggleButton  x:Name="btnShowLineNumbers"
+                           IsChecked="{Binding ElementName=textEditor,Path=ShowLineNumbers}"
+                           Style="{StaticResource MaterialDesignFlatToggleButton}">
+                <TextBlock Width="16"
+                           TextAlignment="Center">#</TextBlock>
+            </ToggleButton>
+            <ToggleButton x:Name="btnShowEndOfLine"
+                          IsChecked="{Binding ElementName=textEditor,Path=Options.ShowEndOfLine}"
+                          Style="{StaticResource MaterialDesignFlatToggleButton}">
+                <TextBlock Width="16"
+                           TextAlignment="Center">¶</TextBlock>
+            </ToggleButton>
+            <Separator />
+            <Button  x:Name="btn12"
+                     Click="Button_Click_5"
+                     ToolTip="{lex:Loc 编译}"
+                     materialDesign:ButtonProgressAssist.IsIndeterminate="{Binding IsCompile,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource InvertBooleanConverter}}"
+                     materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding IsCompile,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource InvertBooleanConverter}}"
+                     materialDesign:ButtonProgressAssist.Value="-1"
+                     Background="Transparent"
+                     BorderBrush="Transparent"
+                     Style="{StaticResource MaterialDesignOutlinedDarkButton}">
+                <Image Source="pack://application:,,,/TeamAAS-VP;component/Resources/Images/compile.png"
+                       Height="16" />
+            </Button>
+
+        </ToolBar>
+        <Border Grid.Row="1"
+                BorderThickness="1,1,1,0">
+            <Border.BorderBrush>
+                <VisualBrush>
+                    <VisualBrush.Visual>
+                        <Rectangle StrokeDashArray="4 2"
+                                   Stroke="Gray"
+                                   StrokeThickness="1"
+                                   Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
+                                   Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualHeight}" />
+                    </VisualBrush.Visual>
+                </VisualBrush>
+            </Border.BorderBrush>
+            <avalonEdit:TextEditor Name="textEditor"
+                                   FontFamily="{StaticResource CodeFont}"
+                                   WordWrap="True"
+                                   SyntaxHighlighting="C#"
+                                   LineNumbersForeground="Black"
+                                   ShowLineNumbers="True">
+            </avalonEdit:TextEditor>
+        </Border>
+        <GridSplitter Grid.Row="2"
+                      Height="4"
+                      VerticalAlignment="Top"
+                      HorizontalAlignment="Stretch" />
+        <Border Grid.Row="2"
+                BorderThickness="1,0,1,1">
+            <Border.BorderBrush>
+                <VisualBrush>
+                    <VisualBrush.Visual>
+                        <Rectangle StrokeDashArray="4 2"
+                                   Stroke="Gray"
+                                   StrokeThickness="1"
+                                   Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
+                                   Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualHeight}" />
+                    </VisualBrush.Visual>
+                </VisualBrush>
+            </Border.BorderBrush>
+            <ListView x:Name="messagelist"
+                      ScrollViewer.VerticalScrollBarVisibility="Auto"
+                      ScrollViewer.CanContentScroll="False"
+                      BorderThickness="0"
+                      Background="Transparent"
+                      Margin="0,4,0,0"
+                      ScrollViewer.HorizontalScrollBarVisibility="Disabled">
+                <ListView.Resources>
+                    <Style TargetType="{x:Type GridViewHeaderRowPresenter}">
+                        <Setter Property="FrameworkElement.Visibility"
+                                Value="Collapsed" />
+                    </Style>
+                </ListView.Resources>
+                <ListView.ItemContainerStyle>
+                    <Style TargetType="ListViewItem">
+                        <Setter Property="HorizontalContentAlignment"
+                                Value="Left" />
+                        <Setter Property="VerticalContentAlignment"
+                                Value="Top" />
+                    </Style>
+                </ListView.ItemContainerStyle>
+                <ListView.ItemTemplate>
+                    <DataTemplate>
+                        <Grid>
+                            <Grid.ColumnDefinitions>
+                                <ColumnDefinition Width="auto" />
+                                <ColumnDefinition Width="auto" />
+                                <ColumnDefinition Width="*" />
+                            </Grid.ColumnDefinitions>
+                            <materialDesign:PackIcon Kind="{Binding Kind}"
+                                                     Foreground="{Binding FontColol}" />
+                            <TextBlock Grid.Column="1"
+                                       TextAlignment="Left"
+                                       Foreground="{Binding FontColol}"
+                                       Text="{Binding DT,StringFormat={}{0:HH:mm:ss.fff}:}" />
+                            <TextBlock Grid.Column="2"
+                                       TextWrapping="Wrap"
+                                       TextAlignment="Left"
+                                       Foreground="{Binding FontColol}"
+                                       Text="{Binding Message}" />
+                        </Grid>
+                    </DataTemplate>
+                </ListView.ItemTemplate>
+            </ListView>
+        </Border>
+
+    </Grid>
+</UserControl>

+ 619 - 0
TeamAAS-VM/Controls/ScriptEditControl.xaml.cs

@@ -0,0 +1,619 @@
+using ICSharpCode.AvalonEdit.CodeCompletion;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Folding;
+using Microsoft.Win32;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Text.RegularExpressions;
+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;
+using System.Windows.Threading;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.ViewModels.DebugMod;
+using Prism.Commands;
+using TeamAAS_VP;
+using TeamAAS_VP.Resources.Languages;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// ScriptEditControl.xaml 的交互逻辑
+    /// </summary>
+    public partial class ScriptEditControl : UserControl
+    {
+        /// <summary>
+        /// 当前app的所有程序集中的类
+        /// </summary>
+        Dictionary<string, Type> ClassMemberlist = new Dictionary<string, Type>();
+        #region 属性
+        private double _fontSize = 14;
+        public double FontSize
+        {
+            get { return _fontSize; }
+            set { _fontSize = value;
+                this.textEditor.FontSize = value;
+            }
+        }
+
+        private TextDocument _document = new TextDocument();
+        public TextDocument Document
+        {
+            get { return _document; }
+            set { _document = value;
+            }
+        }
+
+        private TextArea _mTextArea;
+
+        public TextArea mTextArea
+        {
+            get { return _mTextArea; }
+            set { _mTextArea = value; }
+        }
+
+
+        private ObservableCollection<ScriptCompileMessage> _CompileMessageList = new ObservableCollection<ScriptCompileMessage>();
+
+        public ObservableCollection<ScriptCompileMessage> CompileMessageList
+        {
+            get { return _CompileMessageList; }
+            set {
+                _CompileMessageList = value;
+                this.messagelist.ItemsSource = value;
+
+                    }
+        }
+
+        private bool _IsCompile = true;
+
+        public bool IsCompile
+        {
+            get { return _IsCompile; }
+            set { _IsCompile = value;
+                this.Dispatcher.Invoke(new Action(() => { 
+                    this.btn1.IsEnabled = value;
+                    this.btn2.IsEnabled = value;
+                    this.btn3.IsEnabled = value;
+                    this.btn4.IsEnabled = value;
+                    this.btn5.IsEnabled = value;
+                    this.btn6.IsEnabled = value;
+                    this.btn7.IsEnabled = value;
+                    this.btn8.IsEnabled = value;
+                    this.btn9.IsEnabled = value;
+                    this.btn10.IsEnabled = value;
+                    this.btn11.IsEnabled = value;
+                    this.btn12.IsEnabled = value;
+                    this.btnShowEndOfLine.IsEnabled= value;
+                    this.btnShowLineNumbers.IsEnabled= value;
+                    this.btnWordWrap.IsEnabled= value;
+                    this.textEditor.IsEnabled= value;
+                }));
+            }
+        }
+
+
+        [Bindable(true)]
+        [Category("Common")]
+        [DefaultValue("")]
+        public string Text
+        {
+            get { return (string)GetValue(TextProperty); }
+            set { SetValue(TextProperty, value); 
+            }
+        }
+
+        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty TextProperty =
+            DependencyProperty.Register("Text", typeof(string), typeof(ScriptEditControl), new PropertyMetadata(default(string),new PropertyChangedCallback(OnValueChanged)));
+        
+        private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        {
+            if (d is ScriptEditControl control)
+            {
+                if (e.NewValue!=e.OldValue)
+                {
+                    if (!control.isWrite)
+                    {
+                        control.textEditor.Document.Text = (string)e.NewValue;
+                    }
+                    
+                }
+            }
+        }
+
+
+        [Bindable(true)]
+        [Category("Common")]
+        [DefaultValue("")]
+        public string ScriptPath
+        {
+            get { return (string)GetValue(ScriptPathProperty); }
+            set { SetValue(ScriptPathProperty, value); }
+        }
+
+        // Using a DependencyProperty as the backing store for ScriptPath.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty ScriptPathProperty =
+            DependencyProperty.Register("ScriptPath", typeof(string), typeof(ScriptEditControl), new PropertyMetadata(default(string), new PropertyChangedCallback(OnPathChanged)));
+
+        private static void OnPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        {
+            if (d is ScriptEditControl control)
+            {
+                if (e.NewValue != e.OldValue)
+                {
+                    
+                }
+            }
+        }
+
+        [Bindable(true)]
+        [Category("Common")]
+        [DefaultValue("")]
+        public string CompileType
+        {
+            get { return (string)GetValue(CompileTypeProperty); }
+            set { SetValue(CompileTypeProperty, value); }
+        }
+
+        // Using a DependencyProperty as the backing store for CompileType.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty CompileTypeProperty =
+            DependencyProperty.Register("CompileType", typeof(string), typeof(ScriptEditControl), new PropertyMetadata(default(string)));
+
+        #endregion
+
+        #region 命令
+
+        #endregion
+
+        #region 事件
+        public static readonly RoutedEvent SaveScriptEvent=EventManager.RegisterRoutedEvent("OnSaveScript", RoutingStrategy.Bubble,typeof(RoutedEventHandler),typeof(ScriptEditControl));
+        public event RoutedEventHandler OnSaveScript
+        {
+            add { AddHandler(SaveScriptEvent, value);}
+            remove { RemoveHandler(SaveScriptEvent, value);}
+        }
+        #endregion
+
+        public ScriptEditControl()
+        {
+            InitializeComponent();
+            this.Loaded += ScriptEditControl_Loaded;
+            this.textEditor.PreviewMouseWheel += TextEditor_PreviewMouseWheel;
+            this.messagelist.SelectionChanged += Messagelist_SelectionChanged;
+            this.textEditor.Document = Document;
+            this.textEditor.Document.TextChanged += Document_TextChanged;
+            this.messagelist.ItemsSource= new ObservableCollection<ScriptCompileMessage>();
+        }
+
+        bool isWrite = false;
+        private void Document_TextChanged(object sender, EventArgs e)
+        {
+            isWrite = true;
+            Text = this.textEditor.Document.Text;
+            isWrite = false;
+        }
+
+        #region 方法
+        bool isFirst=true;
+        private async void ScriptEditControl_Loaded(object sender, RoutedEventArgs e)
+        {
+            if (isFirst)
+            {
+                textEditor.Options.HighlightCurrentLine = true;
+                mTextArea = textEditor.TextArea;
+                textEditor.TextArea.TextEntering += TextArea_TextEntering;
+                textEditor.TextArea.TextEntered += TextArea_TextEntered;
+                //textEditor.PreviewMouseWheel += vm.TextEditor_PreviewMouseWheel;
+                ICSharpCode.AvalonEdit.Search.SearchPanel.Install(textEditor);
+                foldingManager = FoldingManager.Install(textEditor.TextArea);
+                foldingStrategy = new BraceFoldingStrategy();
+                DispatcherTimer foldingUpdateTimer = new DispatcherTimer();
+                foldingUpdateTimer.Interval = TimeSpan.FromSeconds(2);
+                foldingUpdateTimer.Tick += delegate { UpdateFoldings(); };
+                foldingUpdateTimer.Start();
+                await Task.Run(() =>
+                {
+                    try
+                    {
+                        var cc = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "TeamAAS_VP");
+                        foreach (var item in GetTypesInNamespace(Assembly.GetExecutingAssembly(), "TeamAAS_VP"))
+                        {
+                            if (!item.IsPublic)
+                            {
+                                continue;
+                            }
+                            ClassMemberlist.Add(item.Name, item);
+                        }
+                        //获取当前应用域中加载的所有程序集数组
+                        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
+                        foreach (var item in assemblies)
+                        {
+                            try
+                            {
+                                foreach (var item1 in GetTypesInNamespace(Assembly.Load(item.FullName)))
+                                {
+                                    if (!item1.IsPublic)
+                                    {
+                                        continue;
+                                    }
+                                    ClassMemberlist.Add(item1.Name, item1);
+                                }
+                            }
+                            catch (Exception)
+                            {
+                            }
+
+                        }
+                    }
+                    catch (Exception)
+                    {
+                    }
+                });
+                isFirst = false;
+            }
+        }
+
+        /// <summary>
+        /// 打开脚本文件
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void Button_Click(object sender, RoutedEventArgs e)
+        {
+            try
+            {
+                OpenFileDialog dlg = new OpenFileDialog();
+                dlg.Title = Lang.打开脚本;
+                dlg.Filter = $"{Lang.脚本文件}|*.cs|{Lang.所有文件}.*|*.*";
+                dlg.CheckFileExists = true;
+                if (dlg.ShowDialog() ?? false)
+                {
+                    this.textEditor.Document.Text = FileHelper.ReadFile(dlg.FileName);
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 保存脚本
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void Button_Click_1(object sender, RoutedEventArgs e)
+        {
+            try
+            {
+                if (string.IsNullOrEmpty(ScriptPath))
+                {
+                    return;
+                }
+                FileHelper.WriteFile(this.textEditor.Document.Text, ScriptPath);
+                RoutedEventArgs args = new RoutedEventArgs(ScriptEditControl.SaveScriptEvent, Text);
+                RaiseEvent(args);
+                MessageBox.Show("Succed!");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存脚本文件时出错",ex);
+                MessageBox.Show(ex.Message);
+            }
+        }
+
+        /// <summary>
+        /// 另存为
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void Button_Click_2(object sender, RoutedEventArgs e)
+        {
+            try
+            {
+                SaveFileDialog dlg = new SaveFileDialog();
+                dlg.Title = $"{Lang.保存脚本}";
+                dlg.DefaultExt = ".cs";
+                dlg.Filter = $"C# {Lang.文件} (*.cs)|*.cs|{Lang.所有文件} (*.txt)|*.txt|All files (*.*)|*.*";
+                if (dlg.ShowDialog() ?? false)
+                {
+                    FileHelper.WriteFile(this.textEditor.Document.Text, dlg.FileName);
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 字体放大
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void Button_Click_3(object sender, RoutedEventArgs e)
+        {
+            if (FontSize < 50)
+            {
+                FontSize += 1;
+            }
+        }
+
+        /// <summary>
+        /// 字体缩小
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void Button_Click_4(object sender, RoutedEventArgs e)
+        {
+            if (FontSize > 1)
+                FontSize -= 1;
+        }
+
+        /// <summary>
+        /// 编译
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private async void Button_Click_5(object sender, RoutedEventArgs e)
+        {
+            IsCompile = false;
+            CompileMessageList.Clear();
+            this.messagelist.ItemsSource = CompileMessageList;
+            CompileMessageList.Add(new ScriptCompileMessage() { DT = DateTime.Now, Kind = MaterialDesignThemes.Wpf.PackIconKind.InformationSlabCircleOutline, FontColol = new SolidColorBrush(Colors.Black), Message = "开始编译...!" });
+            if (!string.IsNullOrEmpty(CompileType) && CompileType== "VisionScripting")
+            {
+                var rst = await ScriptHelper.CompileVisionScriptingAsync(this.textEditor.Document.Text,null,null,null,null,null,null);
+                if (rst.Item1)
+                {
+                    CompileMessageList.Add(new ScriptCompileMessage() { DT = DateTime.Now, Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle, FontColol = new SolidColorBrush(Colors.Green), Message = "编译完成!" });
+                    //rst.Item3.Invoke(rst.Item4,null);
+                }
+                else
+                {
+                    foreach (var item in rst.Item2)
+                    {
+                        CompileMessageList.Add(new ScriptCompileMessage() { DT = DateTime.Now, Kind = MaterialDesignThemes.Wpf.PackIconKind.CloseCircle, FontColol = new SolidColorBrush(Colors.Red), Message = item });
+                    }
+
+                }
+            }
+            else
+            {
+                var rst = await ScriptHelper.CompileAsync(this.textEditor.Document.Text, null, null, null);
+                if (rst.Item1)
+                {
+                    CompileMessageList.Add(new ScriptCompileMessage() { DT = DateTime.Now, Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle, FontColol = new SolidColorBrush(Colors.Green), Message = "编译完成!" });
+                    //rst.Item3.Invoke(rst.Item4,null);
+                }
+                else
+                {
+                    foreach (var item in rst.Item2)
+                    {
+                        CompileMessageList.Add(new ScriptCompileMessage() { DT = DateTime.Now, Kind = MaterialDesignThemes.Wpf.PackIconKind.CloseCircle, FontColol = new SolidColorBrush(Colors.Red), Message = item });
+                    }
+
+                }
+            }
+            
+            this.messagelist.ItemsSource = CompileMessageList;
+            IsCompile = true;
+        }
+
+        CompletionWindow completionWindow;
+        public void TextArea_TextEntered(object sender, System.Windows.Input.TextCompositionEventArgs e)
+        {
+            if (e.Text == ".")
+            {
+                //1.获取.前面的字符串
+
+                // 获取当前光标位置
+                int caretOffset = mTextArea.Caret.Offset;
+                // 获取当前光标位置前面的单词(以空格、标点等作为分隔符)
+                TextDocument document = Document;
+                int startOffset = Math.Max(0, caretOffset - 1); // 从当前位置的前一个字符开始
+                                                                // 找到单词的起始位置
+                while (startOffset >= 0 && !char.IsWhiteSpace(document.GetCharAt(startOffset)))
+                {
+                    startOffset--;
+                }
+                startOffset++; // 回到单词的起始位置
+                // 获取单词的文本
+                int endOffset = caretOffset - 1;
+                // 使用 AvalonEdit 提供的 TextUtilities 获取当前位置前面的单词
+                string word = document.GetText(startOffset, endOffset - startOffset);
+
+                //2.检索字符串,并得到对象
+                var type = word.GetType();
+                foreach (var item in ClassMemberlist)
+                {
+                    if (item.Key.ToLower().Trim(' ') == word.ToLower().Trim(' '))
+                    {
+                        type = item.Value;
+                        break;
+                    }
+                }
+                if (type == null)
+                    return;
+                //3.检索对象中所有的属性,字段,事件,方法,并做提示
+                // open code completion after the user has pressed dot:
+                completionWindow = new CompletionWindow(((ICSharpCode.AvalonEdit.Editing.TextArea)sender));
+                // provide AvalonEdit with the data:
+                IList<ICompletionData> data = completionWindow.CompletionList.CompletionData;
+
+                System.Reflection.MethodInfo[] methodInfos = type.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static);
+                System.Reflection.PropertyInfo[] propertyInfos = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static);            // System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static
+                System.Reflection.EventInfo[] eventInfos = type.GetEvents(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static);
+                System.Reflection.FieldInfo[] fieldInfos = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static);
+                List<String> proposals = new List<string>();
+                //遍历字段
+                foreach (var item in fieldInfos)
+                {
+                    data.Add(new ScriptCompletionData(item.Name, CoreMemberType.Field));
+                }
+                //遍历属性
+                foreach (var item in propertyInfos)
+                {
+                    data.Add(new ScriptCompletionData(item.Name, CoreMemberType.Property));
+                }
+                //遍历方法
+                foreach (var item in methodInfos)
+                {
+                    if (item.IsSpecialName)
+                    {
+                        continue;
+                    }
+                    if (item.ToString().Split(' ').Length >= 2)
+                    {
+                        data.Add(new ScriptCompletionData(item.ToString().Split(" ".ToCharArray(), 2)[1].Replace(" ", ""), CoreMemberType.Void));
+                    }
+                    else
+                    {
+                        data.Add(new ScriptCompletionData(item.Name, CoreMemberType.Void));
+                    }
+
+                }
+                //遍历事件
+                foreach (var item in eventInfos)
+                {
+                    data.Add(new ScriptCompletionData(item.Name, CoreMemberType.Event));
+                }
+                completionWindow.Show();
+                completionWindow.Closed += delegate {
+                    completionWindow = null;
+                };
+            }
+            else if (e.Text == "(")
+            {
+                Document.Insert(mTextArea.Caret.Offset, ")");
+                mTextArea.Caret.Offset = mTextArea.Caret.Offset - 1;
+            }
+            else if (e.Text == "{")
+            {
+                Document.Insert(mTextArea.Caret.Offset, "}");
+                mTextArea.Caret.Offset = mTextArea.Caret.Offset - 1;
+            }
+        }
+
+        public void TextArea_TextEntering(object sender, System.Windows.Input.TextCompositionEventArgs e)
+        {
+            if (e.Text.Length > 0 && completionWindow != null)
+            {
+                if (!char.IsLetterOrDigit(e.Text[0]))
+                {
+                    // Whenever a non-letter is typed while the completion window is open,
+                    // insert the currently selected element.
+                    completionWindow.CompletionList.RequestInsertion(e);
+                }
+            }
+            // do not set e.Handled=true - we still want to insert the character that was typed
+        }
+
+        /// <summary>
+        /// 获取指定命名空间下的所有类
+        /// </summary>
+        /// <param name="assembly"></param>
+        /// <param name="nameSpace"></param>
+        /// <returns></returns>
+        private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace = null)
+        {
+            if (nameSpace == null)
+            {
+                return assembly.GetTypes();
+            }
+            else
+            {
+                return assembly.GetTypes();
+                //return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
+            }
+        }
+
+        public void TextEditor_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
+        {
+            // 检查是否按下了 Ctrl 键
+            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
+            {
+                // 根据鼠标滚轮方向调整字体大小
+                if (e.Delta > 0)
+                {
+                    Button_Click_3(null,null);
+                }
+                else
+                {
+                    Button_Click_4(null,null);
+                }
+
+                // 禁止事件继续传播,防止影响文本编辑器的滚动
+                e.Handled = true;
+            }
+        }
+
+        /// <summary>
+        /// 编辑输出信息选中时
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void Messagelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
+        {
+            ListView listView = sender as ListView;
+            ScriptCompileMessage item = listView.SelectedItem as ScriptCompileMessage;
+            if (item == null)
+            {
+                return;
+            }
+            if (item.Kind != MaterialDesignThemes.Wpf.PackIconKind.CloseCircle)
+            {
+                return;
+            }
+            // 正则表达式
+            string pattern = @"<script>\((\d+),(\d+)\): error (\w+): (.*)";
+            // 匹配正则表达式
+            Match match = Regex.Match(item.Message, pattern);
+            // 如果匹配成功,提取各个部分
+            if (match.Success)
+            {
+                string fullMatch = match.Groups[0].Value;    // 完整匹配结果
+                string lineNumber = match.Groups[1].Value;   // 行号
+                string charNumber = match.Groups[2].Value;   // 字符号
+                string errorCode = match.Groups[3].Value;    // 错误编码
+                string errorDescription = match.Groups[4].Value;  // 错误信息
+                mTextArea.Caret.Line = int.Parse(lineNumber);
+                mTextArea.Caret.BringCaretToView();
+            }
+        }
+        #endregion
+
+        #region Folding
+        FoldingManager foldingManager;
+        object foldingStrategy;
+
+        void UpdateFoldings()
+        {
+            if (foldingStrategy is BraceFoldingStrategy)
+            {
+                ((BraceFoldingStrategy)foldingStrategy).UpdateFoldings(foldingManager, textEditor.Document);
+            }
+            if (foldingStrategy is XmlFoldingStrategy)
+            {
+                ((XmlFoldingStrategy)foldingStrategy).UpdateFoldings(foldingManager, textEditor.Document);
+            }
+        }
+        #endregion
+    }
+}

+ 69 - 0
TeamAAS-VM/Controls/ShowMessage.xaml

@@ -0,0 +1,69 @@
+<UserControl x:Class="TeamAAS_VP.Controls.ShowMessage"
+             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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:system="clr-namespace:System;assembly=mscorlib"
+             xmlns:local="clr-namespace:TeamAAS_VP.Controls"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <Grid Margin="0"
+          MinWidth="300"
+          MinHeight="200" >
+        <Grid.RowDefinitions>
+            <RowDefinition Height="auto"/>
+            <RowDefinition Height="*"/>
+            <RowDefinition Height="auto"/>
+        </Grid.RowDefinitions>
+        <TextBlock Text="{Binding Title}"
+                   FontSize="16"
+                   VerticalAlignment="Center"
+                   Margin="10,5" 
+                   TextWrapping="Wrap"/>
+        <Border VerticalAlignment="Bottom"
+                Height="1"
+                BorderThickness="1"
+                BorderBrush="Gray" />
+        <TextBlock Grid.Row="1"
+                   Margin="10,5"
+                   Text="{Binding Message}"
+                   Foreground="Black"
+                   TextAlignment="Center"
+                   FontSize="16"
+                   VerticalAlignment="Center"
+                   HorizontalAlignment="Left"
+                   TextWrapping="Wrap">
+        </TextBlock>
+        <StackPanel Grid.Row="2"
+                    Margin="10,10"
+                    Orientation="Horizontal"
+                    HorizontalAlignment="Right">
+            <Button Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
+                    IsDefault="True"
+                    FontSize="16"
+                    Style="{StaticResource MaterialDesignFlatButton}"
+                    Content="{lex:Loc 确定}">
+                <Button.CommandParameter>
+                    <system:Boolean>True</system:Boolean>
+                </Button.CommandParameter>
+            </Button>
+            <Button Margin="8,0,0,0"
+                    Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
+                    IsCancel="True"
+                    FontSize="16"
+                    Visibility="{Binding IsCancel,Converter={StaticResource BooleanToVisibilityConverter}}"
+                    Style="{StaticResource MaterialDesignFlatButton}"
+                    Content="{lex:Loc 取消}">
+                <Button.CommandParameter>
+                    <system:Boolean>False</system:Boolean>
+                </Button.CommandParameter>
+            </Button>
+        </StackPanel>
+    </Grid>
+</UserControl>

+ 131 - 0
TeamAAS-VM/Controls/ShowMessage.xaml.cs

@@ -0,0 +1,131 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+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.Controls
+{
+    /// <summary>
+    /// ShowMessage.xaml 的交互逻辑
+    /// </summary>
+    public partial class ShowMessage : UserControl, INotifyPropertyChanged
+    {
+        public ShowMessage(string title,string message,bool cancel=true)
+        {
+            InitializeComponent();
+            DataContext = this;
+            Title = title;
+            Message = message;
+            IsCancel = cancel;
+        }
+
+        private string _Title;
+
+        public string Title
+        {
+            get { return _Title; }
+            set { SetProperty(ref _Title, value); }
+        }
+
+        private string _Message;
+
+        public string Message
+        {
+            get { return _Message; }
+            set { SetProperty(ref _Message, value); }
+        }
+
+        private bool _IsCancel;
+
+        public bool IsCancel
+        {
+            get { return _IsCancel; }
+            set { SetProperty(ref _IsCancel, value); }
+        }
+
+        #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);
+        }
+        #endregion
+    }
+}

+ 63 - 0
TeamAAS-VM/Controls/UProgressBar.xaml

@@ -0,0 +1,63 @@
+<UserControl x:Class="TeamAAS_VP.Controls.UProgressBar"
+             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.Controls"
+             xmlns:prism="http://prismlibrary.com/"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             Background="Transparent"
+             VerticalAlignment="Center"
+             FontFamily="{DynamicResource DefaultFont}">
+    <prism:Dialog.WindowStyle>
+        <Style TargetType="Window">
+            <Setter Property="prism:Dialog.WindowStartupLocation"
+                    Value="CenterScreen" />
+            <Setter Property="ShowInTaskbar"
+                    Value="False" />
+            <Setter Property="WindowStyle"
+                    Value="None" />
+            <Setter Property="AllowsTransparency"
+                    Value="True" />
+            <Setter Property="Background"
+                    Value="Transparent" />
+            <Setter Property="WindowState"
+                    Value="Maximized" />
+            <Setter Property="Topmost"
+                    Value="True" />
+        </Style>
+    </prism:Dialog.WindowStyle>
+
+    <Border CornerRadius="20"
+            Opacity="0.9"
+            Margin="2,0"
+            Width="800"
+            Background="#fafafa"
+            HorizontalAlignment="Center"
+            VerticalAlignment="Center">
+        <StackPanel Orientation="Vertical"
+                    Margin="10,5,10,5">
+            <TextBlock x:Name="txtSubText"
+                       Text="{Binding SubTitle}"
+                       Margin="0,5,0,5"
+                       FontSize="18"
+                       TextAlignment="Center"
+                       TextWrapping="Wrap" />
+            <ProgressBar x:Name="progress"
+                         Height="20"
+                         Maximum="{Binding Maximum}"
+                         Minimum="{Binding Minimum}"
+                         Value="{Binding Value}"
+                         IsIndeterminate="True" />
+            <TextBlock x:Name="txtInfo"
+                       Margin="0,5,0,0"
+                       Text="{Binding Message}"
+                       FontSize="12"
+                       TextAlignment="Center"
+                       TextWrapping="Wrap" />
+        </StackPanel>
+    </Border>
+</UserControl>

+ 239 - 0
TeamAAS-VM/Controls/UProgressBar.xaml.cs

@@ -0,0 +1,239 @@
+using NPOI.SS.Formula.Functions;
+using Prism.Events;
+using Prism.Mvvm;
+using Prism.Services.Dialogs;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+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;
+using TeamAAS_VP.Events;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// UProgressBar.xaml 的交互逻辑
+    /// </summary>
+    public partial class UProgressBar : UserControl, IDialogAware, INotifyPropertyChanged
+    {
+        public struct ProgressParameter
+        {
+            public double Maximum;
+            public double Minimum;
+            public string SubTitle;
+            public string Message;
+            public double Value;
+        }
+
+        IEventAggregator eventAggregator;
+
+        #region 属性
+
+        private double maximum = 100;
+        /// <summary>
+        /// 进度最大值
+        /// </summary>
+        public double Maximum
+        {
+            get { return maximum; }
+            set { SetProperty(ref maximum, value); }
+        }
+
+        private double minimum = 0;
+        /// <summary>
+        /// 进度最小值
+        /// </summary>
+        public double Minimum
+        {
+            get { return minimum; }
+            set { SetProperty(ref minimum, value); }
+        }
+
+        private double _value = 0;
+        /// <summary>
+        /// 进度当前值
+        /// </summary>
+        public double Value
+        {
+            get { return _value; }
+            set { SetProperty(ref _value, value); }
+        }
+
+        private string subTitle = "";
+        /// <summary>
+        /// 副标题
+        /// </summary>
+        public string SubTitle
+        {
+            get { return subTitle; }
+            set { SetProperty(ref subTitle, value); }
+        }
+
+        private string message = "";
+        /// <summary>
+        /// 信息
+        /// </summary>
+        public string Message
+        {
+            get { return message; }
+            set { SetProperty(ref message, value); }
+        }
+
+        public string Title => "";
+        #endregion
+
+        #region 命令
+
+        #endregion
+
+        #region 事件
+        public event Action<IDialogResult> RequestClose;
+        #endregion
+
+        public UProgressBar(IEventAggregator ea)
+        {
+            eventAggregator = ea;
+            InitializeComponent();
+            DataContext = this;
+            eventAggregator.GetEvent<ProgressNotification>().Subscribe(progressChanged);
+        }
+
+        #region 方法
+
+        private void progressChanged(ProgressParameter obj)
+        {
+            if (obj.Value < obj.Minimum)
+            {
+                CloseDialog("True");
+            }
+            else
+            {
+                App.Current.Dispatcher.BeginInvoke(new Action(() => {
+                    Minimum = obj.Minimum;
+                    Maximum = obj.Maximum;
+                    SubTitle = obj.SubTitle;
+                    Message = obj.Message;
+                    Value = obj.Value;
+                }));
+            }
+        }
+
+        protected virtual void CloseDialog(string parameter)
+        {
+            ButtonResult result = ButtonResult.None;
+
+            if (parameter?.ToLower() == "true")
+                result = ButtonResult.OK;
+            else if (parameter?.ToLower() == "false")
+                result = ButtonResult.Cancel;
+
+            RaiseRequestClose(new DialogResult(result));
+        }
+
+        public virtual void RaiseRequestClose(IDialogResult dialogResult)
+        {
+            RequestClose?.Invoke(dialogResult);
+        }
+
+        public bool CanCloseDialog()
+        {
+            return true;
+        }
+
+        public void OnDialogClosed()
+        {
+            
+        }
+
+        public void OnDialogOpened(IDialogParameters parameters)
+        {
+            
+        }
+
+        #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);
+        }
+        #endregion
+    }
+}

+ 276 - 0
TeamAAS-VM/Controls/VibrationControl.xaml

@@ -0,0 +1,276 @@
+<UserControl x:Class="TeamAAS_VP.Controls.VibrationControl"
+             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.Controls"
+             xmlns:icon="http://metro.mahapps.com/winfx/xaml/iconpacks"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <UserControl.Resources>
+        <Style TargetType="Button"
+               BasedOn="{StaticResource MaterialDesignIconForegroundButton}">
+            <Setter Property="Background"
+                    Value="Transparent" />
+            <Setter Property="BorderBrush"
+                    Value="Transparent" />
+            <Setter Property="HorizontalAlignment"
+                    Value="Center" />
+            <Setter Property="VerticalAlignment"
+                    Value="Center" />
+            <Setter Property="Width"
+                    Value="48" />
+            <Setter Property="Height"
+                    Value="48" />
+        </Style>
+        <Style TargetType="TextBlock">
+            <Setter Property="Margin"
+                    Value="0,30,0,0" />
+            <Setter Property="FontSize"
+                    Value="16" />
+            <Setter Property="Foreground"
+                    Value="#ff0078d7" />
+        </Style>
+        <Style TargetType="materialDesign:PackIcon">
+            <Setter Property="FontSize"
+                    Value="30" />
+            <Setter Property="Width"
+                    Value="50" />
+            <Setter Property="Height"
+                    Value="50" />
+        </Style>
+    </UserControl.Resources>
+    <Viewbox Stretch="Uniform">
+        <Grid Width="400" Height="250">
+            <Grid.Background>
+                <ImageBrush ImageSource="pack://application:,,,/TeamAAS-VP;component/Resources/Images/FFFEEDER.png"
+                            Stretch="Fill" />
+            </Grid.Background>
+            <Grid Margin="43,18,107,20">
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="*" />
+                    <ColumnDefinition Width="*" />
+                    <ColumnDefinition Width="*" />
+                </Grid.ColumnDefinitions>
+                <Grid.RowDefinitions>
+                    <RowDefinition />
+                    <RowDefinition />
+                    <RowDefinition />
+                </Grid.RowDefinitions>
+                <Button Grid.Row="0"
+                        Grid.Column="0"
+                        HorizontalAlignment="Center"
+                        VerticalAlignment="Center"
+                        Width="50"
+                        Height="50"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="6">
+                    <Grid>
+                        <materialDesign:PackIcon HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowBottomRightThick" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="G" />
+                    </Grid>
+
+                </Button>
+                
+                <Button Grid.Row="0"
+                        Grid.Column="1"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="3">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowDownBold" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="D" />
+                    </Grid>
+
+                </Button>
+                <Button Grid.Row="1"
+                        Grid.Column="1"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="8">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowExpandAll" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="I" />
+                    </Grid>
+
+                </Button>
+                <Button Grid.Row="2"
+                        Grid.Column="1"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="4">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowUpBold" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="E" />
+                    </Grid>
+                    <!--<icon:PackIconMaterial
+    Width="{Binding IconWidth}"
+    Height="{Binding IconHeight}"
+    Kind="ArrowUp" />-->
+                </Button>
+                <Button Grid.Row="1"
+                        Grid.Column="0"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="5">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowRightBold" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="F" />
+                    </Grid>
+                </Button>
+                <Button Grid.Row="2"
+                        Grid.Column="0"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="7">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowTopRightThick" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="H" />
+                    </Grid>
+                </Button>
+                <Button Grid.Row="0"
+                        Grid.Column="2"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="1">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowBottomLeftThick" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="B" />
+                    </Grid>
+                </Button>
+                <Button Grid.Row="1"
+                        Grid.Column="2"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="0">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowLeftBold" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="A" />
+                    </Grid>
+
+                </Button>
+                <Button Grid.Row="2"
+                        Grid.Column="2"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="2">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowTopLeftThick" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="C" />
+                    </Grid>
+
+                </Button>
+            </Grid>
+
+            <Grid Margin="318,16,15,16">
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="*" />
+                    <RowDefinition Height="*" />
+                    <RowDefinition Height="*" />
+                </Grid.RowDefinitions>
+                <Button Grid.Row="0"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="9">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 Foreground="White"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowCollapseHorizontal" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="J" />
+                    </Grid>
+                </Button>
+                <Button Grid.Row="1"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="10">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 Foreground="White"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="ArrowCollapseVertical" />
+                        <TextBlock HorizontalAlignment="Right"
+                                   VerticalAlignment="Bottom"
+                                   Text="K" />
+                    </Grid>
+                </Button>
+                <Button Grid.Row="2"
+                        Command="{Binding ActionCommand}"
+                        CommandParameter="-1">
+                    <Grid>
+                        <materialDesign:PackIcon Margin="1"
+                                                 Foreground="White"
+                                                 HorizontalAlignment="Center"
+                                                 VerticalAlignment="Center"
+                                                 Kind="{Binding LightKind}">
+                            <materialDesign:PackIcon.Style>
+                                <Style TargetType="materialDesign:PackIcon">
+                                    <Style.Triggers>
+                                        <Trigger Property="Kind"
+                                                 Value="LightbulbOnOutline">
+                                            <Setter Property="Foreground"
+                                                    Value="Orange" />
+                                        </Trigger>
+                                        <Trigger Property="Kind"
+                                                 Value="LightbulbOutline">
+                                            <Setter Property="Foreground"
+                                                    Value="Black" />
+                                        </Trigger>
+                                    </Style.Triggers>
+                                </Style>
+                            </materialDesign:PackIcon.Style>
+                        </materialDesign:PackIcon>
+
+                    </Grid>
+                </Button>
+            </Grid>
+        </Grid>
+    </Viewbox>
+</UserControl>

+ 195 - 0
TeamAAS-VM/Controls/VibrationControl.xaml.cs

@@ -0,0 +1,195 @@
+using MaterialDesignThemes.Wpf;
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Security.Cryptography;
+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;
+using Team.FFFeederService.Interfaces;
+using TeamAAS_VP;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// VibrationControl.xaml 的交互逻辑
+    /// </summary>
+    public partial class VibrationControl : UserControl, INotifyPropertyChanged
+    {
+        public VibrationControl()
+        {
+            InitializeComponent();
+            this.DataContext = this;
+            this.Loaded += VibrationControl_Loaded;
+        }
+
+        private async void VibrationControl_Loaded(object sender, RoutedEventArgs e)
+        {
+            if (Feeder != null && Feeder.IsConnected)
+            {
+                if (await Feeder.QueryLightStateAsync())
+                {
+                    LightKind = PackIconKind.LightbulbOutline;
+                }
+                else
+                {
+                    LightKind = PackIconKind.LightbulbOnOutline;
+                }
+            }
+        }
+
+        #region 属性
+        public IVoiceCoilMotorFeeder Feeder { get;set; }
+
+        private PackIconKind _LightKind= PackIconKind.LightbulbOnOutline;
+
+        public PackIconKind LightKind
+        {
+            get { return _LightKind; }
+            set { SetProperty(ref _LightKind,value); }
+        }
+
+        #endregion
+
+        #region 命令
+        private DelegateCommand<string> _ActionCommand;
+        public DelegateCommand<string> ActionCommand =>
+            _ActionCommand ?? (_ActionCommand = new DelegateCommand<string>(ExecuteActionCommand));
+
+
+        #endregion
+
+        #region 方法
+        /// <summary>
+        /// 执行动作命令
+        /// </summary>
+        async void ExecuteActionCommand(string action)
+        {
+            try
+            {
+                if (int.TryParse(action, out int index))
+                {
+                    if (Feeder == null) return;
+                    if (!Feeder.IsConnected) return;
+                    switch (index)
+                    {
+                        case -1:
+                            if (await Feeder.QueryLightStateAsync())
+                            {
+                                await Feeder.CloseLightAsync(); //关闭光源
+                                LightKind = PackIconKind.LightbulbOutline;
+                            }
+                            else
+                            {
+                                await Feeder.OpenLightAsync();      //打开光源
+                                LightKind = PackIconKind.LightbulbOnOutline;
+                            }
+                            break;
+                        case 0:
+                        case 1:
+                        case 2:
+                        case 3:
+                        case 4:
+                        case 5:
+                        case 6:
+                        case 7:
+                        case 8:
+                        case 9:
+                        case 10:
+                            await Feeder.StartAction(index);
+                            break;
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder执行动作命令时出错!", ex);
+            }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 806 - 0
TeamAAS-VM/Controls/VibrationPara.xaml

@@ -0,0 +1,806 @@
+<UserControl x:Class="TeamAAS_VP.Controls.VibrationPara"
+             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.Controls"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:sys="clr-namespace:System;assembly=mscorlib"
+             xmlns:convert="clr-namespace:TeamAAS_VP.ValueConverter"
+             xmlns:fenum="clr-namespace:Team.FFFeederService.Enums;assembly=Team.FFFeederService"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:DesignHeight="600"
+             d:DesignWidth="700"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+
+    <UserControl.Resources>
+        <convert:NoneWaveConverter x:Key="NoneWaveConverter" />
+    </UserControl.Resources>
+    <Viewbox Stretch="Uniform">
+        <Grid>
+
+            <Grid.RowDefinitions>
+                <RowDefinition Height="Auto" />
+                <RowDefinition />
+                <RowDefinition Height="Auto" />
+            </Grid.RowDefinitions>
+            <StackPanel Grid.Column="0"
+                        Margin="4,0"
+                        Orientation="Horizontal">
+                <ComboBox x:Name="ComboBoxSequence"
+                          MinWidth="30"
+                          Margin="10,0"
+                          HorizontalContentAlignment="Center"
+                          materialDesign:HintAssist.Hint="{lex:Loc 选择振动集}"
+                          materialDesign:HintAssist.IsFloating="True"
+                          ItemsSource="{Binding ProgramCollection}"
+                          SelectedIndex="{Binding SelectProgram}">
+                    <b:Interaction.Triggers>
+                        <b:EventTrigger EventName="SelectionChanged">
+                            <b:InvokeCommandAction Command="{Binding SelectProgramCommand}" />
+                        </b:EventTrigger>
+                    </b:Interaction.Triggers>
+                </ComboBox>
+
+                <ComboBox x:Name="ComboBoxShakeMotions"
+                          MinWidth="30"
+                          Margin="10,0"
+                          HorizontalContentAlignment="Center"
+                          materialDesign:HintAssist.Hint="{lex:Loc 选择动作}"
+                          materialDesign:HintAssist.IsFloating="True"
+                          SelectedIndex="{Binding SelectedShakeMotionIndex}">
+                    <b:Interaction.Triggers>
+                        <b:EventTrigger EventName="SelectionChanged">
+                            <b:InvokeCommandAction Command="{Binding SelectActionCommand}"
+                                                   CommandParameter="{Binding ElementName=ComboBoxShakeMotions, Path=SelectedIndex}" />
+                        </b:EventTrigger>
+                    </b:Interaction.Triggers>
+                    <!--A-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="A"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowLeftBold"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--B-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="B"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowBottomLeftThick"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--C-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="C"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowTopLeftThick"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--D-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="D"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowDownBold"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--E-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="E"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowUpBold"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--F-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="F"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowRightBold"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--G-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="G"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowBottomRightThick"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--H-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="H"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowTopRightThick"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--I-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="I"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowExpandAll"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--J-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="J"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowCollapseHorizontal"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--K-->
+                    <ComboBoxItem>
+                        <StackPanel Orientation="Horizontal">
+                            <TextBlock Text="K"
+                                       VerticalAlignment="Center" />
+                            <materialDesign:PackIcon Kind="ArrowCollapseVertical"
+                                                     Margin="5,0" />
+                        </StackPanel>
+                    </ComboBoxItem>
+                    <!--L-->
+                    <ComboBoxItem>L</ComboBoxItem>
+                    <!--M-->
+                    <ComboBoxItem>M</ComboBoxItem>
+                    <!--N-->
+                    <ComboBoxItem>N</ComboBoxItem>
+                    <!--O-->
+                    <ComboBoxItem>O</ComboBoxItem>
+                    <!--P-->
+                    <ComboBoxItem>P</ComboBoxItem>
+                    <!--Q-->
+                    <ComboBoxItem>Q</ComboBoxItem>
+                    <!--R-->
+                    <ComboBoxItem>R</ComboBoxItem>
+                    <!--S-->
+                    <ComboBoxItem>S</ComboBoxItem>
+                    <!--T-->
+                    <ComboBoxItem>T</ComboBoxItem>
+                    <!--U-->
+                    <ComboBoxItem>U</ComboBoxItem>
+                    <!--V-->
+                    <ComboBoxItem>V</ComboBoxItem>
+                    <!--W-->
+                    <ComboBoxItem>W</ComboBoxItem>
+                    <!--X-->
+                    <ComboBoxItem>X</ComboBoxItem>
+                    <!--Y-->
+                    <ComboBoxItem>Y</ComboBoxItem>
+                    <!--Z-->
+                    <ComboBoxItem>Z</ComboBoxItem>
+                </ComboBox>
+
+                <local:myNumericUpDowm x:Name="nud_duration"
+                                       MinWidth="100"
+                                       Margin="5,0"
+                                       VerticalAlignment="Center"
+                                       materialDesign:HintAssist.Foreground="BlueViolet"
+                                       materialDesign:HintAssist.Hint="{lex:Loc 持续时间,Converter={StaticResource StringFormatConverter},ConverterParameter='{}{0}(ms)'}"
+                                       materialDesign:HintAssist.IsFloating="True"
+                                       Minimum="0"
+                                       Maximum="20000"
+                                       Interval="100"
+                                       StringFormat="{}{0:N0} ms"
+                                       Value="{Binding Duration,Mode=TwoWay}">
+                    <b:Interaction.Triggers>
+                        <b:EventTrigger EventName="ValueChanged">
+                            <b:InvokeCommandAction Command="{Binding DurationChangedCommand}"
+                                                   CommandParameter="{Binding ElementName=nud_duration, Path=Value}" />
+                        </b:EventTrigger>
+                    </b:Interaction.Triggers>
+                </local:myNumericUpDowm>
+                <Popup x:Name="SliderPopup"
+                       Width="150"
+                       Height="{Binding ElementName=nud_duration, Path=Height}"
+                       PlacementTarget="{Binding ElementName=nud_duration}"
+                       Placement="Bottom"
+                       AllowsTransparency="True"
+                       StaysOpen="False">
+                    <Grid Background="Transparent">
+                        <Border Background="#575757"
+                                CornerRadius="0,0,3,3">
+                            <Slider x:Name="slider2"
+                                    Margin="5,2,5,2"
+                                    Foreground="#2196f3"
+                                    Maximum="{Binding ElementName=nud_duration, Path=Maximum}"
+                                    Minimum="{Binding ElementName=nud_duration, Path=Minimum}"
+                                    Value="{Binding ElementName=nud_duration,Path=Value,Mode=TwoWay}" />
+                        </Border>
+                    </Grid>
+
+                </Popup>
+                <Button Margin="4,5"
+                        Command="{Binding ExecuteFromSelected}"
+                        Content="{lex:Loc 执行}"
+                        materialDesign:ButtonAssist.CornerRadius="5"
+                        Cursor="Hand" />
+                <Button Margin="4,5"
+                        materialDesign:ButtonAssist.CornerRadius="5"
+                        Command="{Binding ExecuteStopCommand}"
+                        Content="{lex:Loc 停止}" />
+                <Button Margin="5,0"
+                        materialDesign:ButtonAssist.CornerRadius="5"
+                        Command="{Binding SaveParamCommand}"
+                        Content="{lex:Loc 下载参数}"
+                        Cursor="Hand" />
+            </StackPanel>
+            <UniformGrid Grid.Row="1">
+                <GroupBox Margin="4,4"
+                          Header="Motor1">
+                    <UniformGrid Columns="2">
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 振幅}" />
+                        <local:myNumericUpDowm x:Name="MotorAmplitudeNumeric1"
+                                               Margin="4,0"
+                                               Minimum="0"
+                                               Maximum="100"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} %"
+                                               Value="{Binding Motor1.Amplitude,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="1-1" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+                        <!--<mah:NumericUpDown x:Name="MotorAmplitudeNumeric1"
+                               Margin="4,0"
+                               StringFormat="{}{0:N0} %"
+                               Value="{Binding VoiceMotorParam1.Amplitude}" />-->
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 频率}" />
+                        <local:myNumericUpDowm Margin="4,0"
+                                               Minimum="0"
+                                               Maximum="250"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} Hz"
+                                               Value="{Binding Motor1.Frequency,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="1-2" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 相位}" />
+                        <local:myNumericUpDowm Margin="4,0"
+                                               Interval="1"
+                                               Maximum="359"
+                                               Minimum="0"
+                                               StringFormat="{}{0:N0} °"
+                                               Value="{Binding Motor1.Phase,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="1-3" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 波形}" />
+                        <StackPanel Margin="0,5,0,0"
+                                    HorizontalAlignment="Center"
+                                    Orientation="Horizontal">
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          Content="None"
+                                          IsChecked="{Binding Motor1.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=0, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="1-1" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor1.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=1, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="SineWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="1-2" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor1.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=2, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="SawtoothWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="1-3" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor1.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=3, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="TriangleWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="1-4" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                        </StackPanel>
+
+                    </UniformGrid>
+                </GroupBox>
+                <GroupBox Margin="4,4"
+                          Header="Motor3">
+                    <UniformGrid Columns="2">
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 振幅}" />
+                        <local:myNumericUpDowm x:Name="MotorAmplitudeNumeric3"
+                                               Margin="4,0"
+                                               Minimum="0"
+                                               Maximum="100"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} %"
+                                               Value="{Binding Motor3.Amplitude,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="3-1" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 频率}" />
+                        <local:myNumericUpDowm Margin="4,0"
+                                               Minimum="0"
+                                               Maximum="250"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} Hz"
+                                               Value="{Binding Motor3.Frequency,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="3-2" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 相位}" />
+                        <local:myNumericUpDowm Margin="4,0"
+                                               Interval="1"
+                                               Maximum="359"
+                                               Minimum="0"
+                                               StringFormat="{}{0:N0} °"
+                                               Value="{Binding Motor3.Phase,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="3-3" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 波形}" />
+                        <StackPanel Margin="0,5,0,0"
+                                    HorizontalAlignment="Center"
+                                    Orientation="Horizontal">
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          Content="None"
+                                          IsChecked="{Binding Motor3.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=0, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="3-1" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor3.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=1, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="SineWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="3-2" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="32"
+                                          Height="32"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor3.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=2, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="SawtoothWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="3-3" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor3.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=3, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="TriangleWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="3-4" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                        </StackPanel>
+
+                    </UniformGrid>
+                </GroupBox>
+                <GroupBox Margin="4,4"
+                          Header="Motor2">
+                    <UniformGrid Columns="2">
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 振幅}" />
+                        <local:myNumericUpDowm x:Name="MotorAmplitudeNumeric2"
+                                               Margin="4,0"
+                                               Minimum="0"
+                                               Maximum="100"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} %"
+                                               Value="{Binding Motor2.Amplitude,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="2-1" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 频率}" />
+                        <local:myNumericUpDowm Margin="4,0"
+                                               Minimum="0"
+                                               Maximum="250"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} Hz"
+                                               Value="{Binding Motor2.Frequency,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="2-2" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 相位}" />
+                        <local:myNumericUpDowm Margin="4,0"
+                                               Maximum="359"
+                                               Minimum="0"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} °"
+                                               Value="{Binding Motor2.Phase,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="2-3" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 波形}" />
+                        <StackPanel Margin="0,5,0,0"
+                                    HorizontalAlignment="Center"
+                                    Orientation="Horizontal">
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          Content="None"
+                                          IsChecked="{Binding Motor2.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=0, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="2-1" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor2.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=1, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="SineWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="2-2" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor2.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=2, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="SawtoothWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="2-3" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor2.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=3, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="TriangleWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="2-4" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                        </StackPanel>
+                    </UniformGrid>
+                </GroupBox>
+                <GroupBox Margin="4,4"
+                          Header="Motor4">
+                    <UniformGrid Columns="2">
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 振幅}" />
+                        <local:myNumericUpDowm x:Name="MotorAmplitudeNumeric4"
+                                               Margin="4,0"
+                                               Minimum="0"
+                                               Maximum="100"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} %"
+                                               Value="{Binding Motor4.Amplitude,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="4-1" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 频率}" />
+                        <local:myNumericUpDowm Margin="4,0"
+                                               Minimum="0"
+                                               Maximum="250"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} Hz"
+                                               Value="{Binding Motor4.Frequency,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="4-2" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 相位}" />
+                        <local:myNumericUpDowm Margin="4,0"
+                                               Maximum="359"
+                                               Minimum="0"
+                                               Interval="1"
+                                               StringFormat="{}{0:N0} °"
+                                               Value="{Binding Motor4.Phase,Mode=TwoWay}">
+                            <b:Interaction.Triggers>
+                                <b:EventTrigger EventName="ValueChanged">
+                                    <b:InvokeCommandAction Command="{Binding VoiceMotorParamChangedCommand}"
+                                                           CommandParameter="4-3" />
+                                </b:EventTrigger>
+                            </b:Interaction.Triggers>
+                        </local:myNumericUpDowm>
+                        <TextBlock Margin="4,0"
+                                   VerticalAlignment="Center"
+                                   Text="{lex:Loc 波形}" />
+                        <StackPanel Margin="0,5,0,0"
+                                    HorizontalAlignment="Center"
+                                    Orientation="Horizontal">
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          Content="None"
+                                          IsChecked="{Binding Motor4.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=0, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="4-1" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor4.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=1, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="SineWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="4-2" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor4.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=2, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="SawtoothWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="4-3" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                            <ToggleButton Width="30"
+                                          Height="30"
+                                          Margin="2,0"
+                                          IsChecked="{Binding Motor4.WaveShape, Converter={StaticResource NoneWaveConverter}, ConverterParameter=3, Mode=TwoWay, NotifyOnTargetUpdated=True}"
+                                          Style="{DynamicResource MahApps.Styles.ToggleButton.Circle}">
+                                <materialDesign:PackIcon Width="18"
+                                                         Height="18"
+                                                         Kind="TriangleWave" />
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="Click">
+                                        <b:InvokeCommandAction Command="{Binding WaveShapeChangedCommand}"
+                                                               CommandParameter="4-4" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </ToggleButton>
+                        </StackPanel>
+                    </UniformGrid>
+                </GroupBox>
+            </UniformGrid>
+
+            <GroupBox Grid.Row="2"
+                      Margin="4,0"
+                      Header="{lex:Loc 关于}">
+                <Grid>
+                    <Grid.ColumnDefinitions>
+                        <ColumnDefinition Width="120" />
+                        <ColumnDefinition />
+                    </Grid.ColumnDefinitions>
+                    <mah:ToggleSwitch Width="100"
+                                      Margin="4,0"
+                                      IsOn="{Binding IsSyncChanging}"
+                                      OffContent="{lex:Loc 不同步}"
+                                      OnContent="{lex:Loc 同步}" />
+                    <StackPanel Grid.Column="1">
+                        <StackPanel Margin="0,0"
+                                    HorizontalAlignment="Center"
+                                    Orientation="Horizontal">
+                            <TextBlock Margin="0,0,8,0"
+                                       VerticalAlignment="Center"
+                                       Text="{lex:Loc 振幅}" />
+                            <Slider x:Name="AmplitudeSlider"
+                                    MinWidth="400"
+                                    Margin="0,0"
+                                    Maximum="100"
+                                    Minimum="0"
+                                    TickPlacement="BottomRight"
+                                    Value="{Binding CurrentAmplitude}">
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="ValueChanged">
+                                        <b:InvokeCommandAction Command="{Binding AmplitudeChangedCommand}" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </Slider>
+                        </StackPanel>
+                        <StackPanel Margin="0,0"
+                                    HorizontalAlignment="Center"
+                                    Orientation="Horizontal">
+                            <TextBlock Margin="0,0,8,0"
+                                       VerticalAlignment="Center"
+                                       Text="{lex:Loc 频率}" />
+                            <Slider x:Name="FrequencySlider"
+                                    MinWidth="400"
+                                    Margin="0,0"
+                                    FontSize="10"
+                                    Maximum="100"
+                                    Minimum="0"
+                                    SmallChange="1"
+                                    TickPlacement="TopLeft"
+                                    ToolTip="MaterialDesignDiscreteSlider"
+                                    Value="{Binding CurrentFrequency}">
+                                <b:Interaction.Triggers>
+                                    <b:EventTrigger EventName="ValueChanged">
+                                        <b:InvokeCommandAction Command="{Binding FrequencyChangedCommand}" />
+                                    </b:EventTrigger>
+                                </b:Interaction.Triggers>
+                            </Slider>
+
+                        </StackPanel>
+                    </StackPanel>
+                </Grid>
+
+            </GroupBox>
+
+        </Grid>
+    </Viewbox>
+    
+</UserControl>

+ 896 - 0
TeamAAS-VM/Controls/VibrationPara.xaml.cs

@@ -0,0 +1,896 @@
+using Prism.Commands;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Data.SqlTypes;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.Remoting.Channels;
+using System.Security.Cryptography;
+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;
+using Team.FFFeederService.Enums;
+using Team.FFFeederService.Interfaces;
+using Team.FFFeederService.Models;
+using TeamAAS_VP;
+using TouchSocket.Core;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// VibrationPara.xaml 的交互逻辑
+    /// </summary>
+    public partial class VibrationPara : UserControl, INotifyPropertyChanged
+    {
+        private bool IsLoading = false;
+        public VibrationPara()
+        {
+            InitializeComponent();
+            this.DataContext = this;
+            this.Loaded += VibrationPara_Loaded;
+            ProgramCollection.Clear();
+            for (int i = 1; i <= 26; i++)
+            {
+                ProgramCollection.Add(i);
+                char chn = (char)('A' + i);
+            }
+        }
+
+
+
+        #region 属性
+        public IVoiceCoilMotorFeeder Feeder { get; set; }
+
+        private ObservableCollection<int> _ProgramCollection=new ObservableCollection<int>();
+        /// <summary>
+        /// 振动集
+        /// </summary>
+        public ObservableCollection<int> ProgramCollection
+        {
+            get { return _ProgramCollection; }
+            set { SetProperty(ref _ProgramCollection,value); }
+        }
+
+        private int _SelectProgram=-1;
+
+        /// <summary>
+        /// 当前选择的振动集编号
+        /// </summary>
+        public int SelectProgram
+        {
+            get { return _SelectProgram; }
+            set { SetProperty(ref _SelectProgram, value); }
+        }
+
+        private int _SelectedShakeMotionIndex=-1;
+
+        /// <summary>
+        /// 当前选择的动作
+        /// </summary>
+        public int SelectedShakeMotionIndex
+        {
+            get { return _SelectedShakeMotionIndex; }
+            set { SetProperty(ref _SelectedShakeMotionIndex, value); }
+        }
+
+        private double _Duration;
+        /// <summary>
+        /// 持续时间
+        /// </summary>
+        public double Duration
+        {
+            get { return _Duration; }
+            set { SetProperty(ref _Duration, value); }
+        }
+
+        private VoiceMotorParam _Motor1;
+
+        /// <summary>
+        /// 音圈电机1
+        /// </summary>
+        public VoiceMotorParam Motor1
+        {
+            get { return _Motor1; }
+            set { SetProperty(ref _Motor1, value); }
+        }
+
+        private VoiceMotorParam _Motor2;
+
+        /// <summary>
+        /// 音圈电机2
+        /// </summary>
+        public VoiceMotorParam Motor2
+        {
+            get { return _Motor2; }
+            set { SetProperty(ref _Motor2, value); }
+        }
+
+        private VoiceMotorParam _Motor3;
+
+        /// <summary>
+        /// 音圈电机3
+        /// </summary>
+        public VoiceMotorParam Motor3
+        {
+            get { return _Motor3; }
+            set { SetProperty(ref _Motor3, value); }
+        }
+
+        private VoiceMotorParam _Motor4;
+
+        /// <summary>
+        /// 音圈电机4
+        /// </summary>
+        public VoiceMotorParam Motor4
+        {
+            get { return _Motor4; }
+            set { SetProperty(ref _Motor4, value); }
+        }
+
+        private bool _IsSyncChanging;
+
+        /// <summary>
+        /// 同步
+        /// </summary>
+        public bool IsSyncChanging
+        {
+            get { return _IsSyncChanging; }
+            set { SetProperty(ref _IsSyncChanging, value); }
+        }
+
+        private ushort _CurrentAmplitude;
+        /// <summary>
+        /// 当前的振幅
+        /// </summary>
+        public ushort CurrentAmplitude
+        {
+            get { return _CurrentAmplitude; }
+            set { SetProperty(ref _CurrentAmplitude, value); }
+        }
+
+        private ushort _CurrentFrequency;
+        /// <summary>
+        /// 当前的频率
+        /// </summary>
+        public ushort CurrentFrequency
+        {
+            get { return _CurrentFrequency; }
+            set { SetProperty(ref _CurrentFrequency, value); }
+        }
+
+        private ushort _CurrentPhase;
+
+        /// <summary>
+        /// 当前相位
+        /// </summary>
+        public ushort CurrentPhase
+        {
+            get { return _CurrentPhase; }
+            set { _CurrentPhase = value; }
+        }
+
+        private WaveShape _CurrentWaveShape;
+
+        /// <summary>
+        /// 当前波形
+        /// </summary>
+        public WaveShape CurrentWaveShape
+        {
+            get { return _CurrentWaveShape; }
+            set { _CurrentWaveShape = value; }
+        }
+
+        #endregion
+
+        #region 命令
+        private DelegateCommand _SelectProgramCommand;
+        public DelegateCommand SelectProgramCommand =>
+            _SelectProgramCommand ?? (_SelectProgramCommand = new DelegateCommand(ExecuteSelectProgramCommand));
+
+        private DelegateCommand<int?> _SelectActionCommand;
+        public DelegateCommand<int?> SelectActionCommand =>
+            _SelectActionCommand ?? (_SelectActionCommand = new DelegateCommand<int?>(ExecuteSelectActionCommand));
+
+        private DelegateCommand<double?> _DurationChangedCommand;
+        public DelegateCommand<double?> DurationChangedCommand =>
+            _DurationChangedCommand ?? (_DurationChangedCommand = new DelegateCommand<double?>(ExecuteDurationChangedCommand));
+
+        private DelegateCommand _ExecuteFromSelected;
+        public DelegateCommand ExecuteFromSelected =>
+            _ExecuteFromSelected ?? (_ExecuteFromSelected = new DelegateCommand(ExecuteExecuteFromSelected));
+
+        private DelegateCommand _ExecuteStopCommand;
+        public DelegateCommand ExecuteStopCommand =>
+            _ExecuteStopCommand ?? (_ExecuteStopCommand = new DelegateCommand(ExecuteExecuteStopCommand));
+
+        private DelegateCommand _SaveParamCommand;
+        public DelegateCommand SaveParamCommand =>
+            _SaveParamCommand ?? (_SaveParamCommand = new DelegateCommand(ExecuteSaveParamCommand));
+
+        private DelegateCommand<string> _VoiceMotorParamChangedCommand;
+        public DelegateCommand<string> VoiceMotorParamChangedCommand =>
+            _VoiceMotorParamChangedCommand ?? (_VoiceMotorParamChangedCommand = new DelegateCommand<string>(MotorParamChangedCommand));
+
+        private DelegateCommand<string> _WaveShapeChangedCommand;
+        public DelegateCommand<string> WaveShapeChangedCommand =>
+            _WaveShapeChangedCommand ?? (_WaveShapeChangedCommand = new DelegateCommand<string>(ExecuteWaveShapeChangedCommand));
+
+        private DelegateCommand _AmplitudeChangedCommand;
+        public DelegateCommand AmplitudeChangedCommand =>
+            _AmplitudeChangedCommand ?? (_AmplitudeChangedCommand = new DelegateCommand(ExecuteAmplitudeChangedCommand));
+
+        private DelegateCommand _FrequencyChangedCommand;
+        public DelegateCommand FrequencyChangedCommand =>
+            _FrequencyChangedCommand ?? (_FrequencyChangedCommand = new DelegateCommand(ExecuteFrequencyChangedCommand));
+
+        #endregion
+
+        #region 事件
+
+        #endregion
+
+        #region 方法
+
+        private async void VibrationPara_Loaded(object sender, RoutedEventArgs e)
+        {
+            if (Feeder == null || !Feeder.IsConnected) return;
+            if (SelectProgram==-1)
+            {
+                try
+                {
+                    SelectProgram = 0;
+                    IsLoading = true;
+                    //选择振动集
+                    await Feeder.SelectShakeParamAsync(1);
+                    SelectedShakeMotionIndex = 0;
+
+                    //获取当前动作的4个电机的参数
+                    var paramCollection = await Feeder.GetShakeGroupValueAsync(0);
+                    Motor1 = paramCollection.Motor1;
+                    Motor2 = paramCollection.Motor2;
+                    Motor3 = paramCollection.Motor3;
+                    Motor4 = paramCollection.Motor4;
+                    Duration = (double)paramCollection.DurationValue;
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("Feeder参数加载时出错!", ex);
+                }
+                IsLoading = false;
+            }
+        }
+
+        /// <summary>
+        /// 选择振动集时触发
+        /// </summary>
+        async void ExecuteSelectProgramCommand()
+        {
+            if (SelectProgram == -1)
+            {
+                return;
+            }
+
+            if (Feeder == null)
+            {
+                SelectProgram = -1;
+                return;
+            }
+
+            var id = SelectProgram+1;
+            try
+            {
+                //选择振动集
+                await Feeder.SelectShakeParamAsync(id);
+                if (SelectedShakeMotionIndex == -1)
+                {
+                    SelectedShakeMotionIndex = await Feeder.GetSelectedSequenceAsync() - 1;
+                    if (SelectedShakeMotionIndex < 0 || SelectedShakeMotionIndex > 25)
+                    {
+                        SelectedShakeMotionIndex = 0;
+                    }
+                }
+
+                await Task.Delay(100);
+                var selectedActionId = SelectedShakeMotionIndex;
+                IsLoading = true;
+                //获取当前动作的4个电机的参数
+                var paramCollection = await Feeder.GetShakeGroupValueAsync(selectedActionId);
+                Motor1 = paramCollection.Motor1;
+                Motor2 = paramCollection.Motor2;
+                Motor3 = paramCollection.Motor3;
+                Motor4 = paramCollection.Motor4;
+                Duration= (double)paramCollection.DurationValue;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder选择振动集时触发时出错!", ex);
+            }
+            IsLoading = false;
+        }
+
+        /// <summary>
+        /// 选择动作时触发
+        /// </summary>
+        /// <param name="index"></param>
+        async void ExecuteSelectActionCommand(int? index)
+        {
+            if (SelectedShakeMotionIndex == -1)
+            {
+                return;
+            }
+            if (Feeder == null)
+            {
+                SelectedShakeMotionIndex = -1;
+                return;
+            }
+            if (!Feeder.IsConnected)
+            {
+                SelectedShakeMotionIndex = -1;
+                return;
+            }
+            try
+            {
+                var selectedActionId = SelectedShakeMotionIndex;
+                //获取当前动作的4个电机的参数
+                IsLoading=true;
+                var paramCollection = await Feeder.GetShakeGroupValueAsync(selectedActionId);
+                Motor1 = paramCollection.Motor1;
+                Motor2 = paramCollection.Motor2;
+                Motor3 = paramCollection.Motor3;
+                Motor4 = paramCollection.Motor4;
+                Duration = (double)paramCollection.DurationValue;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder选择动作时触发时出错!", ex);
+            }
+            IsLoading = false;
+        }
+
+        /// <summary>
+        /// 持续时间更改时
+        /// </summary>
+        /// <param name="duration"></param>
+        async void ExecuteDurationChangedCommand(double? duration)
+        {
+            try
+            {
+                if (SelectedShakeMotionIndex >= 0 && Feeder != null && Feeder.IsConnected && !IsLoading)
+                {
+                    await Feeder.SetShakeParametersAsync(SelectedShakeMotionIndex, 16, ((int)Duration).ToString());
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder持续时间更改时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 执行动作
+        /// </summary>
+        async void ExecuteExecuteFromSelected()
+        {
+            if (SelectedShakeMotionIndex == -1)
+            {
+                return;
+            }
+            if (Feeder == null)
+            {
+                return;
+            }
+
+            if (!Feeder.IsConnected)
+            {
+                return;
+            }
+            try
+            {
+                //加载平台振动参数
+                await Feeder.GetShakeParametersAsync(SelectedShakeMotionIndex);
+                //执行平台动作
+                await Feeder.StartAction(SelectedShakeMotionIndex, (int)Duration);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder执行动作时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 停止动作
+        /// </summary>
+        async void ExecuteExecuteStopCommand()
+        {
+            if (Feeder == null)
+            {
+                return;
+            }
+            if (!Feeder.IsConnected)
+            {
+                return;
+            }
+            try
+            {
+                await Feeder.StopAsync();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder停止动作时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存参数
+        /// </summary>
+        async void ExecuteSaveParamCommand()
+        {
+            try
+            {
+                if (Motor1 == null || Motor2 == null || Motor3 == null || Motor4 == null) return;
+                var motionId = SelectedShakeMotionIndex;
+                SingleActionParam singleActionParam = new SingleActionParam()
+                {
+                    Motor1=Motor1,
+                    Motor2=Motor2,
+                    Motor3=Motor3,
+                    Motor4=Motor4,
+                    DurationValue=(int)Duration,
+                };
+
+                await Feeder.SetShakeParametersAsync(motionId, singleActionParam);
+                await Feeder.SaveShakeSetAsync();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder保存参数时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 电机参数变更
+        /// </summary>
+        /// <param name="param"></param>
+        async void MotorParamChangedCommand(string param)
+        {
+            try
+            {
+                if (Motor1 == null || Motor2 == null || Motor3 == null || Motor4 == null) return;
+                if (IsSyncChanging)     //同步时
+                {
+                    if (IsLoading)
+                        return;
+                    IsLoading = true;
+                    string[] item = param.Split('-');
+                    if (Convert.ToInt16(item[1]) == 1)
+                    {
+                        //振幅
+                        if (Convert.ToInt16(item[0]) == 1)
+                        {
+                            CurrentAmplitude = Motor1.Amplitude;
+                            Motor2.Amplitude = CurrentAmplitude;
+                            Motor3.Amplitude = CurrentAmplitude;
+                            Motor4.Amplitude = CurrentAmplitude;
+                        }
+                        else if (Convert.ToInt16(item[0]) == 2)
+                        {
+                            CurrentAmplitude = Motor2.Amplitude;
+                            Motor1.Amplitude = CurrentAmplitude;
+                            Motor3.Amplitude = CurrentAmplitude;
+                            Motor4.Amplitude = CurrentAmplitude;
+                        }
+                        else if (Convert.ToInt16(item[0]) == 3)
+                        {
+                            CurrentAmplitude = Motor3.Amplitude;
+                            Motor1.Amplitude = CurrentAmplitude;
+                            Motor2.Amplitude = CurrentAmplitude;
+                            Motor4.Amplitude = CurrentAmplitude;
+                            
+                        }
+                        else if (Convert.ToInt16(item[0]) == 4)
+                        {
+                            CurrentAmplitude = Motor4.Amplitude;
+                            Motor2.Amplitude = CurrentAmplitude;
+                            Motor3.Amplitude = CurrentAmplitude;
+                            Motor1.Amplitude = CurrentAmplitude;
+                        }
+                    }
+                    else if (Convert.ToInt16(item[1]) == 2)
+                    {
+                        //频率
+                        if (Convert.ToInt16(item[0]) == 1)
+                        {
+                            CurrentFrequency = Motor1.Frequency;
+                            Motor2.Frequency = CurrentFrequency;
+                            Motor3.Frequency = CurrentFrequency;
+                            Motor4.Frequency = CurrentFrequency;
+                        }
+                        else if (Convert.ToInt16(item[0]) == 2)
+                        {
+                            CurrentFrequency = Motor2.Frequency;
+                            Motor1.Frequency = CurrentFrequency;
+                            Motor3.Frequency = CurrentFrequency;
+                            Motor4.Frequency = CurrentFrequency;
+                        }
+                        else if (Convert.ToInt16(item[0]) == 3)
+                        {
+                            CurrentFrequency = Motor3.Frequency;
+                            Motor2.Frequency = CurrentFrequency;
+                            Motor1.Frequency = CurrentFrequency;
+                            Motor4.Frequency = CurrentFrequency;
+                        }
+                        else if (Convert.ToInt16(item[0]) == 4)
+                        {
+                            CurrentFrequency = Motor4.Frequency;
+                            Motor2.Frequency = CurrentFrequency;
+                            Motor3.Frequency = CurrentFrequency;
+                            Motor1.Frequency = CurrentFrequency;
+                        }
+                    }
+                    IsLoading = false;
+                    var motionId = SelectedShakeMotionIndex;
+                    SingleActionParam singleActionParam = new SingleActionParam()
+                    {
+                        Motor1 = Motor1,
+                        Motor2 = Motor2,
+                        Motor3 = Motor3,
+                        Motor4 = Motor4,
+                        DurationValue = (int)Duration,
+                    };
+                    await Feeder.SetShakeParametersAsync(motionId, singleActionParam);
+                }
+                else    //不同步时
+                {
+                    if (SelectedShakeMotionIndex == -1)
+                    {
+                        return;
+                    }
+                    if (Feeder == null || !Feeder.IsConnected)
+                    {
+                        return;
+                    }
+                    if (IsLoading)
+                        return;
+                    var motionId = SelectedShakeMotionIndex;
+
+                    string[] item = param.Split('-');
+                    if (Convert.ToInt16(item[1]) == 1)
+                    {
+                        //振幅
+                        if (Convert.ToInt16(item[0]) == 1)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 0, Motor1.Amplitude.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 2)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 4, Motor2.Amplitude.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 3)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 8, Motor3.Amplitude.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 4)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 12, Motor4.Amplitude.ToString());
+                        }
+                    }
+                    else if (Convert.ToInt16(item[1]) == 2)
+                    {
+                        //频率
+                        if (Convert.ToInt16(item[0]) == 1)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 1, Motor1.Frequency.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 2)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 5, Motor2.Frequency.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 3)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 9, Motor3.Frequency.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 4)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 13, Motor4.Frequency.ToString());
+                        }
+                    }
+                    else if (Convert.ToInt16(item[1]) == 3)
+                    {
+                        //相位
+                        if (Convert.ToInt16(item[0]) == 1)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 2, Motor1.Phase.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 2)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 6, Motor2.Phase.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 3)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 10, Motor3.Phase.ToString());
+                        }
+                        else if (Convert.ToInt16(item[0]) == 4)
+                        {
+                            await Feeder.SetShakeParametersAsync(motionId, 14, Motor4.Phase.ToString());
+                        }
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder电机参数变更时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 电机波形变更
+        /// </summary>
+        /// <param name="param"></param>
+        async void ExecuteWaveShapeChangedCommand(string param)
+        {
+            if (Motor1 == null || Motor2 == null || Motor3 == null || Motor4 == null) return;
+            if (SelectedShakeMotionIndex == -1)
+            {
+                return;
+            }
+            if (Feeder == null || !Feeder.IsConnected)
+            {
+                return;
+            }
+            if (IsLoading)
+                return;
+            IsLoading = true;
+            try
+            {
+                string[] item = param.Split('-');
+                switch (Convert.ToInt16(item[0]))
+                {
+                    case 1:
+                        if (Motor1 != null)
+                        {
+                            Motor1.WaveShape = (WaveShape)(Convert.ToInt16(item[1]) - 1);
+                            if (Motor1.WaveShape == WaveShape.None)
+                            {
+                                Motor1.Amplitude = 0;
+                                Motor1.Frequency = 0;
+                                Motor1.Phase = 0;
+                            }
+                        }
+                        break;
+                    case 2:
+                        if (Motor2 != null)
+                        {
+                            Motor2.WaveShape = (WaveShape)(Convert.ToInt16(item[1]) - 1);
+                            if (Motor2.WaveShape == WaveShape.None)
+                            {
+                                Motor2.Amplitude = 0;
+                                Motor2.Frequency = 0;
+                                Motor2.Phase = 0;
+                            }
+                        }
+                        break;
+                    case 3:
+                        if (Motor3 != null)
+                        {
+                            Motor3.WaveShape = (WaveShape)(Convert.ToInt16(item[1]) - 1);
+                            if (Motor3.WaveShape == WaveShape.None)
+                            {
+                                Motor3.Amplitude = 0;
+                                Motor3.Frequency = 0;
+                                Motor3.Phase = 0;
+                            }
+                        }
+                        break;
+                    case 4:
+                        if (Motor4 != null)
+                        {
+                            Motor4.WaveShape = (WaveShape)(Convert.ToInt16(item[1]) - 1);
+                            if (Motor4.WaveShape == WaveShape.None)
+                            {
+                                Motor4.Amplitude = 0;
+                                Motor4.Frequency = 0;
+                                Motor4.Phase = 0;
+                            }
+                        }
+                        break;
+                    default:
+                        break;
+                }
+                var motionId = SelectedShakeMotionIndex;
+                SingleActionParam singleActionParam = new SingleActionParam()
+                {
+                    Motor1 = Motor1,
+                    Motor2 = Motor2,
+                    Motor3 = Motor3,
+                    Motor4 = Motor4,
+                    DurationValue = (int)Duration,
+                };
+                await Feeder.SetShakeParametersAsync(motionId, singleActionParam);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder电机波形变更时出错!", ex);
+            }
+            IsLoading = false;
+        }
+
+        /// <summary>
+        /// 同步栏振幅更改事件
+        /// </summary>
+        async void ExecuteAmplitudeChangedCommand()
+        {
+            try
+            {
+                if (!IsSyncChanging) return;
+                if (IsLoading) return;
+                if (Motor1 == null || Motor2 == null || Motor3 == null || Motor4 == null) return;
+
+                IsLoading = true;
+                if (Motor1.WaveShape != WaveShape.None)
+                {
+                    Motor1.Amplitude = CurrentAmplitude;
+                }
+                if (Motor2.WaveShape != WaveShape.None)
+                {
+                    Motor2.Amplitude = CurrentAmplitude;
+                }
+                if (Motor3.WaveShape != WaveShape.None)
+                {
+                    Motor3.Amplitude = CurrentAmplitude;
+                }
+                if (Motor4.WaveShape != WaveShape.None)
+                {
+                    Motor4.Amplitude = CurrentAmplitude;
+                }
+                IsLoading = false;
+                var motionId = SelectedShakeMotionIndex;
+                SingleActionParam singleActionParam = new SingleActionParam()
+                {
+                    Motor1 = Motor1,
+                    Motor2 = Motor2,
+                    Motor3 = Motor3,
+                    Motor4 = Motor4,
+                    DurationValue = (int)Duration,
+                };
+
+                await Feeder.SetShakeParametersAsync(motionId, singleActionParam);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder同步栏振幅更改事件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 同步栏频率更改事件
+        /// </summary>
+        async void ExecuteFrequencyChangedCommand()
+        {
+            try
+            {
+                if (!IsSyncChanging) return;
+                if (IsLoading) return;
+                if (Motor1 == null || Motor2 == null || Motor3 == null || Motor4 == null) return;
+
+                IsLoading = true;
+                if (Motor1.WaveShape != WaveShape.None)
+                {
+                    Motor1.Frequency = CurrentFrequency;
+                }
+                if (Motor2.WaveShape != WaveShape.None)
+                {
+                    Motor2.Frequency = CurrentFrequency;
+                }
+                if (Motor3.WaveShape != WaveShape.None)
+                {
+                    Motor3.Frequency = CurrentFrequency;
+                }
+                if (Motor4.WaveShape != WaveShape.None)
+                {
+                    Motor4.Frequency = CurrentFrequency;
+                }
+                IsLoading = false;
+                var motionId = SelectedShakeMotionIndex;
+                SingleActionParam singleActionParam = new SingleActionParam()
+                {
+                    Motor1 = Motor1,
+                    Motor2 = Motor2,
+                    Motor3 = Motor3,
+                    Motor4 = Motor4,
+                    DurationValue = (int)Duration,
+                };
+
+                await Feeder.SetShakeParametersAsync(motionId, singleActionParam);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("Feeder同步栏频率更改事件时出错!", ex);
+            }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 30 - 0
TeamAAS-VM/Controls/WaitingPage.xaml

@@ -0,0 +1,30 @@
+<UserControl x:Class="TeamAAS_VP.Controls.WaitingPage"
+             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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
+             xmlns:local="clr-namespace:TeamAAS_VP.Controls"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             mc:Ignorable="d"
+             d:Background="White"
+             FontFamily="{DynamicResource DefaultFont}">
+    <Grid>
+        <StackPanel Margin="16">
+            <ProgressBar Margin="16"
+                         HorizontalAlignment="Center"
+                         IsIndeterminate="True"
+                         Style="{StaticResource MaterialDesignCircularProgressBar}"
+                         Value="0" />
+            <Button HorizontalAlignment="Center"
+                    Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
+                    CommandParameter="Cancel"
+                    Content="{lex:Loc 取消}"
+                    IsCancel="True"
+                    Style="{StaticResource MaterialDesignFlatButton}" />
+        </StackPanel>
+    </Grid>
+</UserControl>

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

+ 67 - 0
TeamAAS-VM/Controls/myNumericUpDowm.xaml

@@ -0,0 +1,67 @@
+<UserControl x:Class="TeamAAS_VP.Controls.myNumericUpDowm"
+             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.Controls"
+             xmlns:icon="http://metro.mahapps.com/winfx/xaml/iconpacks"
+             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
+             xmlns:lex="http://wpflocalizeextension.codeplex.com"
+             lex:LocalizeDictionary.DesignCulture="zh-CN"
+             lex:ResxLocalizationProvider.DefaultAssembly="TeamAAS-VP"
+             lex:ResxLocalizationProvider.DefaultDictionary="Lang"
+             FontFamily="{DynamicResource DefaultFont}">
+    <UserControl.Triggers>
+        <EventTrigger RoutedEvent="GotFocus">
+            <BeginStoryboard>
+                <Storyboard>
+                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="SliderPopup"
+                                                    Storyboard.TargetProperty="IsOpen">
+                        <DiscreteBooleanKeyFrame KeyTime="0"
+                                                 Value="True" />
+                    </BooleanAnimationUsingKeyFrames>
+                </Storyboard>
+            </BeginStoryboard>
+        </EventTrigger>
+        <EventTrigger RoutedEvent="LostFocus">
+            <BeginStoryboard>
+                <Storyboard>
+                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="SliderPopup"
+                                                    Storyboard.TargetProperty="IsOpen">
+                        <DiscreteBooleanKeyFrame KeyTime="0"
+                                                 Value="False" />
+                    </BooleanAnimationUsingKeyFrames>
+                </Storyboard>
+            </BeginStoryboard>
+        </EventTrigger>
+    </UserControl.Triggers>
+    <!--<Viewbox Stretch="Fill">
+        
+    </Viewbox>-->
+    <Grid>
+        <mah:NumericUpDown x:Name="MotorAmplitudeNumeric1"
+                           Style="{StaticResource MahApps.Styles.NumericUpDown.DataGrid.Editing}"
+                           BorderThickness="0,0,0,1"
+                           FontSize="{Binding FontSize, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
+        <Popup x:Name="SliderPopup"
+               Height="{Binding ElementName=MotorAmplitudeNumeric1, Path=Height}"
+               PlacementTarget="{Binding ElementName=MotorAmplitudeNumeric1}"
+               Placement="Bottom"
+               AllowsTransparency="True"
+               StaysOpen="False"
+               Width="150">
+            <Grid Background="Transparent">
+                <Border Background="#575757"
+                        CornerRadius="0,0,3,3">
+                    <Slider x:Name="slider2"
+                            Margin="5,2,5,2"
+                            Foreground="#2196f3"
+                            IsSnapToTickEnabled="True"
+                            Maximum="{Binding ElementName=MotorAmplitudeNumeric1, Path=Maximum}"
+                            Minimum="{Binding ElementName=MotorAmplitudeNumeric1, Path=Minimum}"
+                            Value="{Binding ElementName=MotorAmplitudeNumeric1,Path=Value,Mode=TwoWay}" />
+                </Border>
+            </Grid>
+        </Popup>
+    </Grid>
+</UserControl>

+ 159 - 0
TeamAAS-VM/Controls/myNumericUpDowm.xaml.cs

@@ -0,0 +1,159 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+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.Controls
+{
+    /// <summary>
+    /// myNumericUpDowm.xaml 的交互逻辑
+    /// </summary>
+    public partial class myNumericUpDowm : UserControl, INotifyPropertyChanged
+    {
+        //
+        // 摘要:
+        //     Identifies the MahApps.Metro.Controls.NumericUpDown.ValueChanged routed event.
+        public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent(
+            "ValueChanged",
+            RoutingStrategy.Bubble,
+            typeof(RoutedEventHandler),
+            typeof(myNumericUpDowm));
+
+        //
+        // 摘要:
+        //     Add / Remove ValueChangedEvent handler Event which will be fired from this NumericUpDown
+        //     when its value has been changed.
+        public event RoutedEventHandler ValueChanged
+        {
+            add
+            {
+                AddHandler(ValueChangedEvent, value);
+            }
+            remove
+            {
+                RemoveHandler(ValueChangedEvent, value);
+            }
+        }
+
+
+        public myNumericUpDowm()
+        {
+            InitializeComponent();
+            this.MotorAmplitudeNumeric1.ValueChanged += MotorAmplitudeNumeric1_ValueChanged;
+        }
+
+        private void MotorAmplitudeNumeric1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double?> e)
+        {
+            Value = e.NewValue;
+        }
+
+        [Bindable(true)]
+        [Category("Common")]
+        [DefaultValue(null)]
+        public double? Value
+        {
+            get { return (double?)GetValue(ValueProperty); }
+            set { SetValue(ValueProperty, value); NotifyValueChanged(value); }
+        }
+
+        // Using a DependencyProperty as the backing store for Value.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty ValueProperty =
+            DependencyProperty.Register("Value", typeof(double?), typeof(myNumericUpDowm), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(PropertyValueChanged)));
+
+        [Bindable(true)]
+        [Category("Common")]
+        [DefaultValue("")]
+        public string StringFormat
+        {
+            get { return (string)GetValue(StringFormatProperty); }
+            set { SetValue(StringFormatProperty, value); }
+        }
+
+        // Using a DependencyProperty as the backing store for StringFormat.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty StringFormatProperty =
+            DependencyProperty.Register("StringFormat", typeof(string), typeof(myNumericUpDowm), new PropertyMetadata("", new PropertyChangedCallback(PropertyValueChanged)));
+
+        [Bindable(true)]
+        [Category("Common")]
+        [DefaultValue(double.MinValue)]
+        public double Minimum
+        {
+            get { return (double)GetValue(MinimumProperty); }
+            set { SetValue(MinimumProperty, value); }
+        }
+
+        // Using a DependencyProperty as the backing store for Minimum.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty MinimumProperty =
+            DependencyProperty.Register("Minimum", typeof(double), typeof(myNumericUpDowm), new PropertyMetadata(double.MinValue, new PropertyChangedCallback(PropertyValueChanged)));
+
+        [Bindable(true)]
+        [Category("Common")]
+        [DefaultValue(double.MaxValue)]
+        public double Maximum
+        {
+            get { return (double)GetValue(MaximumProperty); }
+            set { SetValue(MaximumProperty, value); }
+        }
+
+        // Using a DependencyProperty as the backing store for Maximum.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty MaximumProperty =
+            DependencyProperty.Register("Maximum", typeof(double), typeof(myNumericUpDowm), new PropertyMetadata(double.MaxValue, new PropertyChangedCallback(PropertyValueChanged)));
+
+
+        [Bindable(true)]
+        [Category("Common")]
+        [DefaultValue(1.0)]
+        public double Interval
+        {
+            get { return (double)GetValue(IntervalProperty); }
+            set { SetValue(IntervalProperty, value); }
+        }
+
+        // Using a DependencyProperty as the backing store for Interval.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty IntervalProperty =
+            DependencyProperty.Register("Interval", typeof(double), typeof(myNumericUpDowm), new PropertyMetadata(1.0, new PropertyChangedCallback(PropertyValueChanged)));
+
+        public event PropertyChangedEventHandler PropertyChanged;
+
+        private static void PropertyValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        {
+            (d as myNumericUpDowm).Update();
+
+        }
+
+        private void Update()
+        {
+            this.MotorAmplitudeNumeric1.Value = Value;
+            this.MotorAmplitudeNumeric1.StringFormat = StringFormat;
+            this.MotorAmplitudeNumeric1.Minimum = Minimum;
+            this.MotorAmplitudeNumeric1.Maximum = Maximum;
+            this.MotorAmplitudeNumeric1.Interval = Interval;
+            this.slider2.SmallChange = Interval;
+            this.slider2.TickFrequency= Interval;
+        }
+
+        // 触发 ValueChanged 事件的方法
+        protected virtual void OnValueChanged(double? newValue)
+        {
+            RoutedEventArgs args = new RoutedEventArgs(ValueChangedEvent, newValue);
+            RaiseEvent(args);
+        }
+
+        // 用户控件的值发生变化时调用此方法
+        private void NotifyValueChanged(double? newValue)
+        {
+            OnValueChanged(newValue);
+        }
+    }
+}

+ 403 - 0
TeamAAS-VM/Core/BgCommunicate.cs

@@ -0,0 +1,403 @@
+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.Core;
+using TouchSocket.Sockets;
+
+namespace TeamAAS_VP.Core
+{
+    public class BgCommunicate
+    {
+        private IWaitingClient<ITcpSessionClient, IReceiverResult> WaitClientServer;
+        public TcpService TcpService { get; private set; }
+
+        BgTcpIP Config;
+
+        public event Action<ITcpSessionClient, ConnectedEventArgs> ConnectedEvent;
+        public event Action<ITcpSessionClient, ClosedEventArgs> DisconnectedEvent;
+        public event Action<ITcpSessionClient, string> ReceivedEvent;
+        public event Action<ITcpSessionClient, string> SendEvent;
+
+        public int Port { get => Config.Port; }
+
+        public Terminator Terminator { get => Config.Terminator; }
+
+        public DataEncoding DataEncoding { get => Config.DataEncoding; }
+
+        public int ClientCount { get => TcpService.Count; }
+
+        public BgCommunicate(BgTcpIP _Config) 
+        {
+            Config= _Config;
+            TcpService = new TcpService();
+
+            var config = new TouchSocketConfig();
+            config.SetListenIPHosts(new IPHost[] { new IPHost(Config.Port) }); //同时监听两个地址
+                                                                                                                       ////设置结束符
+            if (Config.Terminator == Terminator.None)
+            {
+                config.SetTcpDataHandlingAdapter(() => { return new NormalDataHandlingAdapter(); });       ////亦或者省略\r\n,但此时调用方不能高速调用,会粘包
+            }
+            else if (Config.Terminator == Terminator.CR)
+            {
+                config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r"); });       //命令行中使用\r结尾 
+            }
+            else if (Config.Terminator == Terminator.LF)
+            {
+                config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\n"); });       //命令行中使用\n结尾 
+            }
+            else if (Config.Terminator == Terminator.CRLF)
+            {
+                config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r\n"); });       //命令行中使用\r\n结尾 
+            }
+            //载入配置
+            TcpService.Setup(config);
+
+            /////有客户端成功连接
+            TcpService.Connected = ConnectedVoid;
+            //有客户端断开连接
+            TcpService.Closed = DisconnectedVoid;
+            //从客户端收到信息
+            TcpService.Received = ReceivedVoid;
+        }
+
+        /// <summary>
+        /// 启动监听
+        /// </summary>
+        public void StartListening()
+        {
+            TcpService.Start();
+        }
+
+        /// <summary>
+        /// 停止监听
+        /// </summary>
+        public void StopListening() 
+        { 
+            TcpService.Stop(); 
+        }
+
+        public void Dispose()
+        {
+            TcpService.Stop();
+            TcpService.Dispose();
+        }
+
+        #region 事件接收
+        /// <summary>
+        /// 有客户端成功连接
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ConnectedVoid(ITcpSessionClient client, ConnectedEventArgs e)
+        {
+            //调用CreateWaitingClient获取到IWaitingClient的对象。
+            WaitClientServer = client.CreateWaitingClient(new WaitingOptions()
+            {
+                FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                {
+                    return true;
+
+                    //if (response.Data.Length == 1)
+                    //{
+                    //    return true;
+                    //}
+                    //return false;
+                }
+            });
+            ConnectedEvent?.Invoke(client, e);
+            return EasyTask.CompletedTask;
+        }
+        /// <summary>
+        /// 有客户端断开连接
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task DisconnectedVoid(ITcpSessionClient client, ClosedEventArgs e)
+        {
+            DisconnectedEvent?.Invoke(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)
+        {
+            Encoding encoding = GetEncoding();
+            ReceivedEvent?.Invoke(client, e.ByteBlock.Span.ToString(encoding));
+            //调用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;
+        }
+        #endregion
+
+        #region 发送数据
+        /// <summary>
+        /// 发送信息给特定ID的客户端
+        /// </summary>
+        /// <param name="ID"></param>
+        /// <param name="msg"></param>
+        public void Send(string ID, string mes)
+        {
+            Encoding encoding = GetEncoding();
+            var client = TcpService.Clients.FirstOrDefault(cl => cl.Id == ID);
+            if (client!=null)
+            {
+                client.Send(encoding.GetBytes(mes));
+                SendEvent?.Invoke(client,mes);
+            }
+        }
+
+        /// <summary>
+        /// 发送信息给特定ID的客户端
+        /// </summary>
+        /// <param name="ID"></param>
+        /// <param name="mes"></param>
+        public async Task SendAsync(string ID, string mes)
+        {
+            Encoding encoding = GetEncoding();
+            var client = TcpService.Clients.FirstOrDefault(cl => cl.Id == ID);
+            if (client != null)
+            {
+                await client.SendAsync(encoding.GetBytes(mes));
+                SendEvent?.Invoke(client, mes);
+            }
+        }
+
+        /// <summary>
+        /// 发送信息给在线的所有客户端
+        /// </summary>
+        /// <param name="ID"></param>
+        /// <param name="msg"></param>
+        public void Send(string mes)
+        {
+            Encoding encoding = GetEncoding();
+            foreach (var client in TcpService.Clients)
+            {
+                client.Send(encoding.GetBytes(mes));
+                SendEvent?.Invoke(client, mes);
+            }
+        }
+
+        /// <summary>
+        /// 发送信息给在线的所有客户端
+        /// </summary>
+        /// <param name="mes"></param>
+        public async Task SendAsync(string mes)
+        {
+            Encoding encoding = GetEncoding();
+            foreach (var client in TcpService.Clients)
+            {
+                await client.SendAsync(encoding.GetBytes(mes));
+                SendEvent?.Invoke(client, mes);
+            }
+        }
+
+        /// <summary>
+        /// 发送信息给客户端
+        /// </summary>
+        /// <param name="client">客户端</param>
+        /// <param name="mes"></param>
+        public void Send(ITcpSessionClient client, string mes)
+        {
+            Encoding encoding = GetEncoding();
+            client.Send(encoding.GetBytes(mes));
+            SendEvent?.Invoke(client, mes);
+        }
+
+        /// <summary>
+        /// 发送信息给客户端
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="mes"></param>
+        public async Task SendAsync(ITcpSessionClient client, string mes)
+        {
+            Encoding encoding = GetEncoding();
+            await client.SendAsync(encoding.GetBytes(mes));
+            SendEvent?.Invoke(client, mes);
+        }
+
+        /// <summary>
+        /// 发送并接收数据(最后一次活动的客户端)
+        /// </summary>
+        /// <param name="mes"></param>
+        /// <param name="millisecondsTimeout"></param>
+        /// <returns></returns>
+        public string SendThenReturn(string mes, int millisecondsTimeout = 5000)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(WaitClientServer.Client, mes);
+            var returnData= WaitClientServer.SendThenReturn(encoding.GetBytes(mes), millisecondsTimeout);
+            ReceivedEvent?.Invoke(WaitClientServer.Client, encoding.GetString(returnData));
+            return encoding.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 发送并接收数据(最后一次活动的客户端)
+        /// </summary>
+        /// <param name="mes"></param>
+        /// <param name="millisecondsTimeout"></param>
+        /// <returns></returns>
+        public async Task<string> SendThenReturnAsync(string mes, int millisecondsTimeout = 5000)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(WaitClientServer.Client, mes);
+            var returnData = await WaitClientServer.SendThenReturnAsync(encoding.GetBytes(mes), millisecondsTimeout);
+            ReceivedEvent?.Invoke(WaitClientServer.Client, encoding.GetString(returnData));
+            return encoding.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="mes"></param>
+        /// <param name="millisecondsTimeout"></param>
+        /// <returns></returns>
+        public string SendThenReturn(ITcpSessionClient client,string mes, int millisecondsTimeout = 5000)
+        {
+            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(WaitClientServer.Client, mes);
+            var returnData = WaitClientServer.SendThenReturn(encoding.GetBytes(mes), millisecondsTimeout);
+            ReceivedEvent?.Invoke(WaitClientServer.Client, encoding.GetString(returnData));
+            return encoding.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="mes"></param>
+        /// <param name="millisecondsTimeout"></param>
+        /// <returns></returns>
+        public async Task<string> SendThenReturnAsync(ITcpSessionClient client,string mes, int millisecondsTimeout = 5000)
+        {
+            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(WaitClientServer.Client, mes);
+            var returnData = await WaitClientServer.SendThenReturnAsync(encoding.GetBytes(mes), millisecondsTimeout);
+            ReceivedEvent?.Invoke(WaitClientServer.Client, encoding.GetString(returnData));
+            return encoding.GetString(returnData);
+        }
+        #endregion
+
+        #region 编码
+        /// <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
+    }
+}

+ 329 - 0
TeamAAS-VM/Core/BgModbusTcpCommunicate.cs

@@ -0,0 +1,329 @@
+using Modbus.Data;
+using Modbus.Device;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using TeamAAS_VP.Models;
+using TeamAAS_VP;
+
+namespace TeamAAS_VP.Core
+{
+    /// <summary>
+    /// 后台Modbus TCP 通讯
+    /// </summary>
+    public class BgModbusTcpCommunicate
+    {
+        public TcpListener TcpListener { get;private set; }
+        public ModbusSlave Slave { get; private set; }
+        BgModbusTcp Config;
+
+        public string IP { get => Config.IP; }
+        public int Port { get => Config.Port; }
+        public byte SlaveID { get => Config.SlaveID; }
+        public bool IsEnabled { get => Config.IsEnabled; }
+
+        public BgModbusTcpCommunicate(BgModbusTcp _Config)
+        {
+            Config = _Config;
+            if (!Config.IsEnabled)
+            {
+                return;
+            }
+            if (TcpListener == null)
+            {
+                TcpListener = new TcpListener(IPAddress.Parse(Config.IP), Config.Port);
+                TcpListener.Start();
+            }
+            Slave = ModbusTcpSlave.CreateTcp(Config.SlaveID, TcpListener);
+            Slave.DataStore = Modbus.Data.DataStoreFactory.CreateDefaultDataStore();
+            Slave.ModbusSlaveRequestReceived += Slave_ModbusSlaveRequestReceived;
+            Slave.DataStore.DataStoreWrittenTo += DataStore_DataStoreWrittenTo;
+            Slave.DataStore.DataStoreReadFrom += DataStore_DataStoreReadFrom;
+            
+        }
+
+        public void Listen()
+        {
+            Slave.Listen();
+        }
+
+        private void Slave_ModbusSlaveRequestReceived(object sender, ModbusSlaveRequestEventArgs e)
+        {
+            try
+            {
+                switch (e.Message.FunctionCode)
+                {
+                    case 2:
+                        break;
+                    case 4:
+                        break;
+                    default:
+                        break;
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"后台Modbus tcp读取{e.Message.FunctionCode}", ex);
+            }
+        }
+
+        /// <summary>
+        /// 当通过Modbus命令读取数据存储时发生
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void DataStore_DataStoreReadFrom(object sender, Modbus.Data.DataStoreEventArgs e)
+        {
+            try
+            {
+                switch (e.ModbusDataType)
+                {
+                    case ModbusDataType.HoldingRegister:
+                        break;
+                    case ModbusDataType.InputRegister:
+                        break;
+                    case ModbusDataType.Coil:
+                        break;
+                    case ModbusDataType.Input:
+                        break;
+                    default:
+                        break;
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"后台Modbus tcp读取{e.ModbusDataType.ToString()}", ex);
+            }
+        }
+
+        /// <summary>
+        /// 当slave 收到 master 的命令 写入 DO 值或 AO 值到 DataStore 时触发事件。
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void DataStore_DataStoreWrittenTo(object sender, Modbus.Data.DataStoreEventArgs e)
+        {
+            switch (e.ModbusDataType)
+            {
+                case ModbusDataType.Coil:   //code 5            //写入单个线圈
+                    //ModbusDataCollection<bool> discretes = slave.DataStore.CoilDiscretes;       //获取线圈离散
+                    break;
+                case ModbusDataType.HoldingRegister:   //code 15
+                    //ModbusDataCollection<ushort> holdingRegisters = slave.DataStore.HoldingRegisters;   //获取保存寄存器。
+                    break;
+            }
+        }
+
+        /// <summary>
+        /// 将接收到的ushort[]转换为float类型
+        /// </summary>
+        /// <param name="val"></param>
+        /// <returns></returns>
+        public float GetFloatFormUshortArray(ushort[] val)
+        {
+            if (val != null && val.Length == 2)
+            {
+                List<byte> result = new List<byte>();
+                result.AddRange(BitConverter.GetBytes(val[0]));
+                result.AddRange(BitConverter.GetBytes(val[1]));
+                return BitConverter.ToSingle(result.ToArray(), 0);
+            }
+            else
+            {
+                return 0.0f;
+            }
+        }
+
+        /// <summary>
+        /// 将float类型分解成两个ushort类型
+        /// </summary>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        public ushort[] GetUshortArrayFormFloat(float value)
+        {
+            ushort lowOrderValue = BitConverter.ToUInt16(BitConverter.GetBytes(value), 2);
+            ushort highOrderValue = BitConverter.ToUInt16(BitConverter.GetBytes(value), 0);
+            return new ushort[2] { lowOrderValue, highOrderValue };
+        }
+
+        /// <summary>
+        /// 获取输入位状态
+        /// </summary>
+        /// <param name="index"></param>
+        /// <returns></returns>
+        public bool SW(int index)
+        {
+            try
+            {
+                return Slave.DataStore.CoilDiscretes[index];
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"获取输入位状态时出错", ex);
+                return false;
+            }
+
+        }
+
+        /// <summary>
+        /// 获取输出位状态
+        /// </summary>
+        /// <param name="index"></param>
+        /// <returns></returns>
+        public bool Oport(int index)
+        {
+            try
+            {
+                return Slave.DataStore.InputDiscretes[index];
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"获取输出位状态时出错", ex);
+                return false;
+            }
+
+        }
+
+        /// <summary>
+        /// 输出位操作
+        /// </summary>
+        /// <param name="index">地址</param>
+        /// <param name="state">状态</param>
+        /// <param name="time">脉冲时间</param>
+        /// <param name="_async">是否异步执行</param>
+        public void BitOperate(int index, bool state)
+        {
+            try
+            {
+                Slave.DataStore.InputDiscretes[index] = state;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"输出位操作时出错", ex);
+            }
+
+        }
+
+        /// <summary>
+        /// 输出字操作
+        /// </summary>
+        /// <param name="index">字编号</param>
+        /// <param name="value">输出值</param>
+        /// <param name="time">脉冲时长</param>
+        /// <param name="_async">是否异步</param>
+        public void OutW(int index, ushort value)
+        {
+            try
+            {
+                Slave.DataStore.InputRegisters[index] = value;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"输出字操作时出错", ex);
+            }
+
+        }
+
+        /// <summary>
+        /// 获取输出字值
+        /// </summary>
+        /// <param name="index"></param>
+        /// <returns></returns>
+        public ushort ReadOutW(int index)
+        {
+            try
+            {
+                return Slave.DataStore.InputRegisters[index];
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"获取输出字值时出错", ex);
+                return 0;
+            }
+
+        }
+
+        /// <summary>
+        /// 获取输入字值
+        /// </summary>
+        /// <param name="index"></param>
+        /// <returns></returns>
+        public ushort InW(int index)
+        {
+            try
+            {
+                return Slave.DataStore.HoldingRegisters[index];
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"获取输入字值时出错", ex);
+                return 0;
+            }
+        }
+
+        /// <summary>
+        /// 输出浮点数
+        /// </summary>
+        /// <param name="index">字编号</param>
+        /// <param name="value">值</param>
+        /// <param name="time">脉冲时长</param>
+        /// <param name="_async">是否异步</param>
+        public void OutReal(int index, float value)
+        {
+            try
+            {
+                ushort[] data = GetUshortArrayFormFloat(value);
+                Slave.DataStore.InputRegisters[index] = data[0];
+                Slave.DataStore.InputRegisters[index + 1] = data[1];
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"输出浮点数时出错", ex);
+            }
+        }
+
+        /// <summary>
+        /// 获取输出浮点数
+        /// </summary>
+        /// <param name="index"></param>
+        /// <returns></returns>
+        public float ReadOutReal(int index)
+        {
+            try
+            {
+                return GetFloatFormUshortArray(new ushort[] { Slave.DataStore.InputRegisters[index], Slave.DataStore.InputRegisters[index + 1] });
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"获取输出浮点数时出错", ex);
+                return 0.0f;
+            }
+
+        }
+
+        /// <summary>
+        /// 获取输入浮点数
+        /// </summary>
+        /// <param name="index"></param>
+        /// <returns></returns>
+        public float InReal(int index)
+        {
+            try
+            {
+                return GetFloatFormUshortArray(new ushort[] { Slave.DataStore.HoldingRegisters[index + 1], Slave.DataStore.HoldingRegisters[index + 0] });
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError($"获取输入浮点数时出错", ex);
+                return 0.0f;
+            }
+
+        }
+    }
+}

+ 100 - 0
TeamAAS-VM/Core/BraceFoldingStrategy.cs

@@ -0,0 +1,100 @@
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Folding;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core
+{
+    /// <summary>
+	/// Allows producing foldings from a document based on braces.
+	/// </summary>
+	public class BraceFoldingStrategy
+    {
+        /// <summary>
+        /// Gets/Sets the opening brace. The default value is '{'.
+        /// </summary>
+        public char OpeningBrace { get; set; }
+
+        /// <summary>
+        /// Gets/Sets the closing brace. The default value is '}'.
+        /// </summary>
+        public char ClosingBrace { get; set; }
+
+        /// <summary>
+        /// Creates a new BraceFoldingStrategy.
+        /// </summary>
+        public BraceFoldingStrategy()
+        {
+            this.OpeningBrace = '{';
+            this.ClosingBrace = '}';
+        }
+
+        public void UpdateFoldings(FoldingManager manager, TextDocument document)
+        {
+            int firstErrorOffset;
+            IEnumerable<NewFolding> newFoldings = CreateNewFoldings(document, out firstErrorOffset);
+            manager.UpdateFoldings(newFoldings, firstErrorOffset);
+        }
+
+        /// <summary>
+        /// Create <see cref="NewFolding"/>s for the specified document.
+        /// </summary>
+        public IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
+        {
+            firstErrorOffset = -1;
+            return CreateNewFoldings(document);
+        }
+
+        /// <summary>
+        /// Create <see cref="NewFolding"/>s for the specified document.
+        /// </summary>
+        public IEnumerable<NewFolding> CreateNewFoldings(ITextSource document)
+        {
+            List<NewFolding> newFoldings = new List<NewFolding>();
+
+            Stack<int> startOffsets = new Stack<int>();
+            int lastNewLineOffset = 0;
+            char openingBrace = this.OpeningBrace;
+            char closingBrace = this.ClosingBrace;
+            for (int i = 0; i < document.TextLength; i++)
+            {
+                char c = document.GetCharAt(i);
+                if (c == openingBrace)
+                {
+                    startOffsets.Push(i);
+                }
+                else if (c == closingBrace && startOffsets.Count > 0)
+                {
+                    int startOffset = startOffsets.Pop();
+                    // don't fold if opening and closing brace are on the same line
+                    if (startOffset < lastNewLineOffset)
+                    {
+                        newFoldings.Add(new NewFolding(startOffset, i + 1));
+                    }
+                }
+                else if (c=='#' && i+6< document.TextLength && document.GetCharAt(i+1)== 'r' && document.GetCharAt(i + 2) == 'e' && document.GetCharAt(i + 3) == 'g' && document.GetCharAt(i + 4) == 'i' && document.GetCharAt(i + 5) == 'o' && document.GetCharAt(i + 6) == 'n')
+                {
+                    startOffsets.Push(i);
+                }
+                else if (c == '#' && i + 6 < document.TextLength && document.GetCharAt(i + 1) == 'e' && document.GetCharAt(i + 2) == 'n' && document.GetCharAt(i + 3) == 'd' && document.GetCharAt(i + 1) == 'r' && document.GetCharAt(i + 2) == 'e' && document.GetCharAt(i + 3) == 'g' && document.GetCharAt(i + 4) == 'i' && document.GetCharAt(i + 5) == 'o' && document.GetCharAt(i + 6) == 'n' && startOffsets.Count > 0)
+                {
+                    int startOffset = startOffsets.Pop();
+                    // don't fold if opening and closing brace are on the same line
+                    if (startOffset < lastNewLineOffset)
+                    {
+                        newFoldings.Add(new NewFolding(startOffset, i + 1));
+                    }
+                }
+                else if (c == '\n' || c == '\r')
+                {
+                    lastNewLineOffset = i + 1;
+                }
+            }
+            newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
+            return newFoldings;
+        }
+    }
+}

+ 894 - 0
TeamAAS-VM/Core/Cameras/AHuaCamera.cs

@@ -0,0 +1,894 @@
+using Cognex.VisionPro;
+using CSScripting;
+using Microsoft.Win32;
+using MVSDK_Net;
+using NPOI.Util;
+using NPOI.XSSF.Model;
+using OpenCvSharp.Dnn;
+using Org.BouncyCastle.Asn1.Tsp;
+using OxyPlot;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Data.SqlTypes;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Media.Media3D;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP;
+using static MVSDK_Net.IMVDefine;
+
+namespace TeamAAS_VP.Core.Cameras
+{
+    public class AHuaCamera : ICamera, INotifyPropertyChanged
+    {
+        #region 字段
+        private Thread m_hReceiveThread;
+        #endregion
+
+        #region 属性
+
+        public CameraBrand CameraBrand { get => CameraBrand.IRayple; }
+
+        public string Name { get; private set; }
+        public Guid ID { get; private set; }
+        public string ManufacturerName { get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public CameraType CameraType { get; private set; }
+
+        MVSDK_Net.MyCamera mvCameraAcq;
+
+        public UInt32 ImageWidth { get; private set; }
+
+        public UInt32 ImageHeight { get; private set; }
+
+        private bool _IsGrabbing;
+
+        /// <summary>
+        /// 正在采集
+        /// </summary>
+        public bool IsGrabbing
+        {
+            get { return _IsGrabbing; }
+            private set { SetProperty(ref _IsGrabbing, value); }
+        }
+
+        private ICogImage _Image;
+
+        public ICogImage Image
+        {
+            get { return _Image; }
+            private set { SetProperty(ref _Image, value); }
+        }
+
+        public bool IsConnected { get; private set; }
+
+        /// <summary>
+        /// 采集用时
+        /// </summary>
+        public TimeSpan TotalTime { get; private set; }
+
+        /// <summary>
+        /// 错误信息
+        /// </summary>
+        public string ErrorMessage { get; private set; }
+
+        private bool IsHaveCamera = false;
+        #endregion
+
+        #region 事件
+        public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
+        public event Action<Guid, bool> CameraConnectChangedEvent;
+        #endregion
+
+        public AHuaCamera(Guid _ID, string _Name, string _SerialNumber)
+        {
+            ID = _ID;
+            Name = _Name;
+            SerialNumber = _SerialNumber;
+            mvCameraAcq = new MVSDK_Net.MyCamera();
+            var list = GetDevices();
+            foreach (var device in list)
+            {
+                if (device.SerialNumber == _SerialNumber)
+                {
+                    IsHaveCamera = true;
+                    ManufacturerName = device.ManufacturerName;
+                    ModelName = device.Model;
+                    SerialNumber = device.SerialNumber;
+                    CameraType = CameraType.USB;
+                    int res = mvCameraAcq.IMV_CreateHandle(IMVDefine.IMV_ECreateHandleMode.modeByCameraKey, 0, _SerialNumber);
+                    if (res == IMVDefine.IMV_OK)
+                    {
+
+                    }
+                    break;
+                }
+            }
+
+            IsConnected = false;
+        }
+
+        #region 方法
+
+        /// <summary>
+        /// 获取设备
+        /// </summary>
+        /// <returns></returns>
+        public static CameraInfo[] GetDevices()
+        {
+            List<CameraInfo> cameras = new List<CameraInfo>();
+            if (!CheckSoftwareInstalled().isInstalled)
+            {
+                LogHelper.WriteLogInfo("未安装MV Viewer");
+                return cameras.ToArray();
+            }
+            // 设备搜索 
+            // device search 
+            IMVDefine.IMV_DeviceList deviceList = new IMVDefine.IMV_DeviceList();
+            IMVDefine.IMV_EInterfaceType interfaceTp = IMVDefine.IMV_EInterfaceType.interfaceTypeAll;
+            int res = MyCamera.IMV_EnumDevices(ref deviceList, (uint)interfaceTp);
+
+            // 添加设备信息
+            // Add device info
+            if (res == IMVDefine.IMV_OK && deviceList.nDevNum > 0)
+            {
+                for (int i = 0; i < deviceList.nDevNum; i++)
+                {
+                    IMVDefine.IMV_DeviceInfo deviceInfo =
+                        (IMVDefine.IMV_DeviceInfo)
+                            Marshal.PtrToStructure(
+                                deviceList.pDevInfo + Marshal.SizeOf(typeof(IMVDefine.IMV_DeviceInfo)) * i,
+                                typeof(IMVDefine.IMV_DeviceInfo));
+                    if (deviceInfo.nCameraType == IMV_ECameraType.typeGigeCamera)
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.IRayple,
+                            CameraType = CameraType.GIGE,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = deviceInfo.manufactureInfo,
+                            Model = deviceInfo.modelName,
+                            SerialNumber = deviceInfo.serialNumber,
+                            CameraIp = deviceInfo.cameraKey,
+                        });
+                    }
+                    else if (deviceInfo.nCameraType == IMV_ECameraType.typeU3vCamera)
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.IRayple,
+                            CameraType = CameraType.USB,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = deviceInfo.cameraName,
+                            Model = deviceInfo.modelName,
+                            SerialNumber = deviceInfo.serialNumber,
+                            CameraIp = deviceInfo.cameraKey,
+                        });
+                    }
+                    else if (deviceInfo.nCameraType == IMV_ECameraType.typeCLCamera)
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.IRayple,
+                            CameraType = CameraType.Link,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = deviceInfo.cameraName,
+                            Model = deviceInfo.modelName,
+                            SerialNumber = deviceInfo.serialNumber,
+                            CameraIp = deviceInfo.cameraKey,
+                        });
+                    }
+                    else
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.IRayple,
+                            CameraType = CameraType.Unknown,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = deviceInfo.cameraName,
+                            Model = deviceInfo.modelName,
+                            SerialNumber = deviceInfo.serialNumber,
+                            CameraIp = deviceInfo.cameraKey,
+                        });
+                    }
+                }
+            }
+            return cameras.ToArray();
+        }
+
+        /// <summary>
+        /// 检查相机软件是否安装
+        /// </summary>
+        /// <returns></returns>
+        public static (bool isInstalled, string version) CheckSoftwareInstalled()
+        {
+            string softwareName = "MV Viewer";
+            string softwareVersion = "2.5.1.1";
+            string[] registryPaths = new[]
+            {
+                @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
+                @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
+            };
+            foreach (var path in registryPaths)
+            {
+                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
+                {
+                    if (key == null) continue;
+
+                    foreach (string subKeyName in key.GetSubKeyNames())
+                    {
+                        using (RegistryKey subKey = key.OpenSubKey(subKeyName))
+                        {
+                            string displayName = subKey.GetValue("DisplayName")?.ToString();
+                            if (displayName != null && displayName.Contains(softwareName))
+                            {
+                                string version = subKey.GetValue("DisplayVersion")?.ToString();
+                                var match = Regex.Match(version, @"^(\d+\.\d+\.\d+\.\d+)");
+                                if (match.Success)
+                                {
+                                    version = match.Groups[1].Value;
+                                }
+                                else
+                                {
+                                    continue;
+                                }
+                                Version v1 = new Version(version);
+                                Version v2 = new Version(softwareVersion);
+                                if (v1 >= v2)
+                                {
+                                    return (true, version);
+                                }
+                                else
+                                {
+                                    return (false, version);
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            return (false, "");
+        }
+
+        /// <summary>
+        /// 打开相机
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public bool OpenDevice()
+        {
+            IsConnected = false;
+            //if (!IsHaveCamera)
+            //{
+            var list = GetDevices();
+            foreach (var device in list)
+            {
+                if (device.SerialNumber == SerialNumber)
+                {
+                    IsHaveCamera = true;
+                    ManufacturerName = device.ManufacturerName;
+                    ModelName = device.Model;
+                    CameraType = CameraType.USB;
+                    int res = mvCameraAcq.IMV_CreateHandle(IMVDefine.IMV_ECreateHandleMode.modeByCameraKey, 0, device.CameraIp);
+                    if (res == IMVDefine.IMV_OK)
+                    {
+
+                    }
+                    break;
+                }
+            }
+            if (!IsHaveCamera)
+            {
+                //throw new Exception("没有发现相机");
+                return false;
+            }
+            //}
+
+            // 打开设备 
+            // open device 
+            int res1 = mvCameraAcq.IMV_Open();
+            if (res1 != IMVDefine.IMV_OK)
+            {
+                return IsConnected;
+            }
+            if (!IsConnected)
+            {
+                CameraConnectChangedEvent?.Invoke(ID, true);
+            }
+
+            long width = 0;
+            long height = 0;
+
+            // 获取宽
+            // Get Width
+            res1 = mvCameraAcq.IMV_GetIntFeatureValue("Width", ref width);
+            if (res1 != IMVDefine.IMV_OK)
+            {
+                //MessageBox.Show("Get Width failed");
+            }
+
+            // 获取高
+            // Get Height
+            res1 = mvCameraAcq.IMV_GetIntFeatureValue("Height", ref height);
+            if (res1 != IMVDefine.IMV_OK)
+            {
+                //MessageBox.Show("Get Height failed");
+            }
+            ImageWidth = (uint)width;
+            ImageHeight = (uint)height;
+            m_picSize = width * height;
+
+            res1 = mvCameraAcq.IMV_SetEnumFeatureSymbol("AcquisitionMode", "Continuous");
+            if (res1 != IMVDefine.IMV_OK)
+            {
+                //MessageBox.Show("Set AcquisitionMode failed");
+            }
+
+            // 关闭触发模式
+            // set trigger mode as off     
+            res1 = mvCameraAcq.IMV_SetEnumFeatureSymbol("TriggerMode", "Off");
+            if (res1 != IMVDefine.IMV_OK)
+            {
+                //MessageBox.Show("Set TriggerMode failed");
+            }
+
+            // 开启码流 
+            // start grabbing 
+            res1 = mvCameraAcq.IMV_StartGrabbing();
+            if (res1 != IMVDefine.IMV_OK)
+            {
+                //MessageBox.Show("Start grabbing failed!");
+            }
+
+            IsConnected = mvCameraAcq.IMV_IsOpen();
+            return IsConnected;
+        }
+
+        /// <summary>
+        /// 关闭相机
+        /// </summary>
+        public void CloseDevice()
+        {
+            if (mvCameraAcq.IMV_IsOpen())
+            {
+                // ch:关闭设备 | en:Close Device
+                mvCameraAcq.IMV_Close();
+                mvCameraAcq.IMV_DestroyHandle();
+            }
+        }
+
+        private long m_picSize = 0;
+        IMVDefine.IMV_Frame frame = new IMVDefine.IMV_Frame();
+
+        IntPtr pTemp = IntPtr.Zero;
+        IntPtr pConvertDstBuffer = IntPtr.Zero;
+        int nConvertBufSize = 0;
+        private IMVDefine.IMV_PixelConvertParam stPixelConvertParam = new IMVDefine.IMV_PixelConvertParam();
+        private IMVDefine.IMV_EPixelType type = IMVDefine.IMV_EPixelType.gvspPixelMono8;
+        /// <summary>
+        /// 采集图像
+        /// </summary>
+        /// <returns></returns>
+        public ICogImage Grab()
+        {
+            Byte[] byteArrImageData = new Byte[m_picSize * 3];
+            Stopwatch sw = Stopwatch.StartNew();
+            int res = IMVDefine.IMV_OK;
+            for (int i = 0; i < 5; i++)
+            {
+                try
+                {
+                    if (!mvCameraAcq.IMV_IsOpen())
+                    {
+                        OpenDevice();
+                    }
+                    mvCameraAcq.IMV_ClearFrameBuffer();
+                    res = mvCameraAcq.IMV_GetFrame(ref frame, 1000);
+                    if (res == IMVDefine.IMV_OK)
+                    {
+                        try
+                        {
+                            // Mono图像处理
+                            if (IsMonoPixelFormat(frame.frameInfo.pixelFormat))
+                            {
+                                type = IMVDefine.IMV_EPixelType.gvspPixelMono8;
+                                if (frame.frameInfo.pixelFormat == IMVDefine.IMV_EPixelType.gvspPixelMono8)
+                                {
+                                    pTemp = frame.pData;
+                                }
+                                else
+                                {
+                                    if (pConvertDstBuffer == IntPtr.Zero || nConvertBufSize < (frame.frameInfo.width * frame.frameInfo.height))
+                                    {
+                                        if (pConvertDstBuffer != IntPtr.Zero)
+                                        {
+                                            Marshal.FreeHGlobal(pConvertDstBuffer);
+                                            pConvertDstBuffer = IntPtr.Zero;
+                                        }
+
+                                        pConvertDstBuffer = Marshal.AllocHGlobal((int)(frame.frameInfo.width * frame.frameInfo.height));
+                                        if (pConvertDstBuffer == IntPtr.Zero)
+                                        {
+                                            break;
+                                        }
+                                        nConvertBufSize = (int)(frame.frameInfo.width * frame.frameInfo.height);
+                                    }
+                                    // 其他格式Mono转为Mono8
+                                    stPixelConvertParam.nWidth = frame.frameInfo.width;
+                                    stPixelConvertParam.nHeight = frame.frameInfo.height;
+                                    stPixelConvertParam.ePixelFormat = frame.frameInfo.pixelFormat;
+                                    stPixelConvertParam.pSrcData = frame.pData;
+                                    stPixelConvertParam.nSrcDataLen = frame.frameInfo.size;
+                                    stPixelConvertParam.nPaddingX = frame.frameInfo.paddingX;
+                                    stPixelConvertParam.nPaddingY = frame.frameInfo.paddingY;
+                                    stPixelConvertParam.eBayerDemosaic = IMVDefine.IMV_EBayerDemosaic.demosaicNearestNeighbor;
+                                    stPixelConvertParam.eDstPixelFormat = IMVDefine.IMV_EPixelType.gvspPixelMono8;
+                                    stPixelConvertParam.pDstBuf = pConvertDstBuffer;
+                                    stPixelConvertParam.nDstBufSize = frame.frameInfo.width * frame.frameInfo.height;
+
+                                    res = mvCameraAcq.IMV_PixelConvert(ref stPixelConvertParam);
+                                    if (res != IMVDefine.IMV_OK)
+                                    {
+                                        break;
+                                    }
+                                    pTemp = pConvertDstBuffer;
+                                }
+                            }
+                            // 彩色图像处理
+                            else if (IsColorPixelFormat(frame.frameInfo.pixelFormat))
+                            {
+                                type = IMVDefine.IMV_EPixelType.gvspPixelRGB8;
+                                if (frame.frameInfo.pixelFormat == IMVDefine.IMV_EPixelType.gvspPixelRGB8)
+                                {
+                                    pTemp = frame.pData;
+                                }
+                                else
+                                {
+                                    if (pConvertDstBuffer == IntPtr.Zero || nConvertBufSize < (frame.frameInfo.width * frame.frameInfo.height * 3))
+                                    {
+                                        if (pConvertDstBuffer != IntPtr.Zero)
+                                        {
+                                            Marshal.FreeHGlobal(pConvertDstBuffer);
+                                            pConvertDstBuffer = IntPtr.Zero;
+                                        }
+
+                                        pConvertDstBuffer = Marshal.AllocHGlobal((int)(frame.frameInfo.width * frame.frameInfo.height * 3));
+                                        if (pConvertDstBuffer == IntPtr.Zero)
+                                        {
+                                            break;
+                                        }
+                                        nConvertBufSize = (int)(frame.frameInfo.width * frame.frameInfo.height * 3);
+                                    }
+
+                                    // 其他格式彩色图像转为RGB
+                                    stPixelConvertParam.nWidth = frame.frameInfo.width;
+                                    stPixelConvertParam.nHeight = frame.frameInfo.height;
+                                    stPixelConvertParam.ePixelFormat = frame.frameInfo.pixelFormat;
+                                    stPixelConvertParam.pSrcData = frame.pData;
+                                    stPixelConvertParam.nSrcDataLen = frame.frameInfo.size;
+                                    stPixelConvertParam.nPaddingX = frame.frameInfo.paddingX;
+                                    stPixelConvertParam.nPaddingY = frame.frameInfo.paddingY;
+                                    stPixelConvertParam.eBayerDemosaic = IMVDefine.IMV_EBayerDemosaic.demosaicNearestNeighbor;
+                                    stPixelConvertParam.eDstPixelFormat = IMVDefine.IMV_EPixelType.gvspPixelRGB8;
+                                    stPixelConvertParam.pDstBuf = pConvertDstBuffer;
+                                    stPixelConvertParam.nDstBufSize = frame.frameInfo.width * frame.frameInfo.height * 3;
+
+                                    res = mvCameraAcq.IMV_PixelConvert(ref stPixelConvertParam);
+                                    if (res != IMVDefine.IMV_OK)
+                                    {
+                                        break;
+                                    }
+                                    pTemp = pConvertDstBuffer;
+                                }
+
+                                unsafe
+                                {
+                                    byte* pBufForSaveImage = (byte*)pTemp;
+
+                                    UInt32 nSupWidth = (uint)((frame.frameInfo.width + (UInt32)3) & 0xfffffffc);
+
+                                    for (int nRow = 0; nRow < frame.frameInfo.height; nRow++)
+                                    {
+                                        for (int col = 0; col < frame.frameInfo.width; col++)
+                                        {
+                                            byteArrImageData[nRow * nSupWidth + col] = pBufForSaveImage[nRow * frame.frameInfo.width * 3 + (3 * col)];
+                                            byteArrImageData[frame.frameInfo.width * frame.frameInfo.height + nRow * nSupWidth + col] = pBufForSaveImage[nRow * frame.frameInfo.width * 3 + (3 * col + 1)];
+                                            byteArrImageData[frame.frameInfo.width * frame.frameInfo.height * 2 + nRow * nSupWidth + col] = pBufForSaveImage[nRow * frame.frameInfo.width * 3 + (3 * col + 2)];
+                                        }
+                                    }
+                                    pTemp = Marshal.UnsafeAddrOfPinnedArrayElement(byteArrImageData, 0);
+                                }
+                            }
+                            else
+                            {
+                                continue;
+                            }
+
+                            Image = ConvertImage(frame.frameInfo.width, frame.frameInfo.height, pTemp, type);
+                            if (Image != null)
+                            {
+                                ErrorMessage = "";
+                                TotalTime = sw.Elapsed;
+                                return Image;
+                            }
+                        }
+                        catch (Exception)
+                        {
+
+                        }
+                        finally
+                        {
+                            // 释放帧数据
+                            // release frame
+                            mvCameraAcq.IMV_ReleaseFrame(ref frame);
+                        }
+                    }
+                    else
+                    {
+                        ErrorMessage = res.ToString();
+                        CloseDevice();
+                        OpenDevice();
+                    }
+                }
+                catch (Exception ex)
+                {
+                    CloseDevice();
+                    OpenDevice();
+                    ErrorMessage = ex.Message;
+                }
+            }
+            if (IsConnected)
+            {
+                IsConnected = false;
+                CameraConnectChangedEvent?.Invoke(ID, false);
+            }
+            return null;
+        }
+
+        /// <summary>
+        /// 开始采集图像
+        /// </summary>
+        public void StartGrabbing()
+        {
+            if (IsGrabbing)
+                return;
+            IsGrabbing = true;
+            m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
+            m_hReceiveThread.Start();
+        }
+
+        /// <summary>
+        /// 停止采集图像
+        /// </summary>
+        public void StopGrabbing()
+        {
+            try
+            {
+                IsGrabbing = false;
+                Thread.Sleep(1000);
+                if (m_hReceiveThread != null)
+                {
+                    m_hReceiveThread.Abort();
+                    m_hReceiveThread = null;
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 设置曝光时间
+        /// </summary>
+        /// <param name="ExposureTime"></param>
+        /// <returns></returns>
+        public bool SetExposureTime(float ExposureTime)
+        {
+            if (!mvCameraAcq.IMV_IsOpen())
+                return false;
+            if (GetExposureTime()!= ExposureTime)
+            {
+                bool success = false;
+                for (int i = 0; i < 5; i++)
+                {
+                    int res = mvCameraAcq.IMV_SetDoubleFeatureValue("ExposureTime", (double)ExposureTime);
+                    if (IMVDefine.IMV_OK == res)
+                    {
+                        success = true;
+                        Thread.Sleep(100);
+                        break;
+                    }
+                }
+                return success;
+            }
+            return true;
+        }
+
+        /// <summary>
+        /// 获取曝光时间
+        /// </summary>
+        /// <returns></returns>
+        public float GetExposureTime()
+        {
+            if (!mvCameraAcq.IMV_IsOpen())
+                return 0;
+            // 获取曝光值
+            // set ExposureTime 
+            double exposureTime = 0;
+            int res = mvCameraAcq.IMV_GetDoubleFeatureValue("ExposureTime", ref exposureTime);
+            if (IMVDefine.IMV_OK != res)
+            {
+                return 0;
+            }
+            return (float)exposureTime;
+        }
+
+        /// <summary>
+        /// 设置增益
+        /// </summary>
+        /// <param name="Gain"></param>
+        /// <returns></returns>
+        public bool SetGain(float Gain)
+        {
+            if (!mvCameraAcq.IMV_IsOpen())
+                return false;
+            if (GetGain()!=Gain)
+            {
+                // 设置增益 
+                // set Gain 
+                bool success = false;
+                for (int i = 0; i < 5; i++)
+                {
+                    int res = mvCameraAcq.IMV_SetDoubleFeatureValue("GainRaw", (double)Gain);
+                    if (IMVDefine.IMV_OK == res)
+                    {
+                        success = true;
+                        break;
+                    }
+                }
+                return success;
+            }
+            return true;
+        }
+
+        /// <summary>
+        /// 获取增益
+        /// </summary>
+        /// <returns></returns>
+        public float GetGain()
+        {
+            if (!mvCameraAcq.IMV_IsOpen())
+                return 0;
+            // 获取增益
+            double gain = 0;
+            int res = mvCameraAcq.IMV_GetDoubleFeatureValue("GainRaw", ref gain);
+            if (IMVDefine.IMV_OK != res)
+            {
+                return 0;
+            }
+            return (float)gain;
+        }
+
+        private void GetStreamThreadProc()
+        {
+            while (IsGrabbing)
+            {
+                try
+                {
+                    Grab();
+                    ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+                }
+                catch (Exception)
+                {
+
+                }
+                Thread.Sleep(10);
+            }
+            IsGrabbing = false;
+        }
+
+        /// <summary>
+        /// 图像是否为Mono格式
+        /// </summary>
+        /// <param name="enType"></param>
+        /// <returns></returns>
+        private bool IsMonoPixelFormat(IMVDefine.IMV_EPixelType enType)
+        {
+            switch (enType)
+            {
+                case IMVDefine.IMV_EPixelType.gvspPixelMono8:
+                case IMVDefine.IMV_EPixelType.gvspPixelMono10:
+                case IMVDefine.IMV_EPixelType.gvspPixelMono10Packed:
+                case IMVDefine.IMV_EPixelType.gvspPixelMono12:
+                case IMVDefine.IMV_EPixelType.gvspPixelMono12Packed:
+                    return true;
+                default:
+                    return false;
+            }
+        }
+
+        /// <summary>
+        /// 图像是否为彩色
+        /// </summary>
+        /// <param name="enType"></param>
+        /// <returns></returns>
+        private bool IsColorPixelFormat(IMVDefine.IMV_EPixelType enType)
+        {
+            switch (enType)
+            {
+                case IMVDefine.IMV_EPixelType.gvspPixelRGB8:
+                case IMVDefine.IMV_EPixelType.gvspPixelBGR8:
+                case IMVDefine.IMV_EPixelType.gvspPixelRGBA8:
+                case IMVDefine.IMV_EPixelType.gvspPixelBGRA8:
+                case IMVDefine.IMV_EPixelType.gvspPixelYUV422_8:
+                case IMVDefine.IMV_EPixelType.gvspPixelYUV422_8_UYVY:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGR8:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayRG8:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGB8:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayBG8:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGB10:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGB10Packed:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayBG10:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayBG10Packed:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayRG10:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayRG10Packed:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGR10:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGR10Packed:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGB12:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGB12Packed:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayBG12:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayBG12Packed:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayRG12:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayRG12Packed:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGR12:
+                case IMVDefine.IMV_EPixelType.gvspPixelBayGR12Packed:
+                    return true;
+                default:
+                    return false;
+            }
+        }
+
+        /// <summary>
+        /// 转换图片
+        /// </summary>
+        /// <param name="nHeight">高</param>
+        /// <param name="nWidth">宽</param>
+        /// <param name="pImageBuf">图片数据</param>
+        /// <param name="enPixelType">像素格式</param>
+        public ICogImage ConvertImage(UInt32 nWidth, UInt32 nHeight, IntPtr pImageBuf, IMVDefine.IMV_EPixelType enPixelType)
+        {
+            try
+            {
+                if (enPixelType == IMVDefine.IMV_EPixelType.gvspPixelMono8)
+                {
+                    CogImage8Root cogImage8Root = new CogImage8Root();
+                    cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
+
+                    CogImage8Grey cogImage8Grey = new CogImage8Grey();
+                    cogImage8Grey.SetRoot(cogImage8Root);
+                    var image = cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
+                    System.GC.Collect();
+                    return image;
+                }
+                else
+                {
+                    CogImage8Root image0 = new CogImage8Root();
+                    IntPtr ptr0 = new IntPtr(pImageBuf.ToInt64());
+                    image0.Initialize((int)nWidth, (int)nHeight, ptr0, (int)nWidth, null);
+
+                    CogImage8Root image1 = new CogImage8Root();
+                    IntPtr ptr1 = new IntPtr(pImageBuf.ToInt64() + m_picSize);
+                    image1.Initialize((int)nWidth, (int)nHeight, ptr1, (int)nWidth, null);
+
+                    CogImage8Root image2 = new CogImage8Root();
+                    IntPtr ptr2 = new IntPtr(pImageBuf.ToInt64() + m_picSize * 2);
+                    image2.Initialize((int)nWidth, (int)nHeight, ptr2, (int)nWidth, null);
+
+                    CogImage24PlanarColor colorImage = new CogImage24PlanarColor();
+                    colorImage.SetRoots(image0, image1, image2);
+
+                    var image = colorImage.ScaleImage((int)nWidth, (int)nHeight);
+                    System.GC.Collect();
+                    return image;
+                }
+            }
+            catch (System.Exception ex)
+            {
+                return null;
+            }
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 958 - 0
TeamAAS-VM/Core/Cameras/BaslerCamera.cs

@@ -0,0 +1,958 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using Cognex.VisionPro;
+using Basler.Pylon;
+using System.IO;
+using System.Drawing.Imaging;
+using System.Drawing;
+using System.Diagnostics;
+using ControlzEx.Standard;
+using System.Windows.Media.Media3D;
+using MvCamCtrl.NET;
+using TeamAAS_VP.Models;
+using Microsoft.Win32;
+//using System.Drawing;
+//using System.Drawing.Imaging;
+
+namespace TeamAAS_VP.Core.Cameras
+{
+    public class BaslerCamera : Interfaces.ICamera, INotifyPropertyChanged
+    {
+        #region 字段
+        private Basler.Pylon.Camera m_MyCamera;
+        private Thread m_hReceiveThread;
+        UInt32 m_nRowStep = 0;
+        // The pixel data converter is used for converting grabbed images to a pixel format that can be displayed.
+        private PixelDataConverter converter = new PixelDataConverter();
+        #endregion
+
+        #region 属性
+
+        public CameraBrand CameraBrand { get => CameraBrand.Basler_Pylon; }
+
+        public string Name { get; private set; }
+        public Guid ID { get; private set; }
+        public string ManufacturerName { get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public CameraType CameraType { get; private set; }
+
+        public UInt32 ImageWidth { get; private set; }
+
+        public UInt32 ImageHeight { get; private set; }
+
+        private bool _IsGrabbing;
+
+        /// <summary>
+        /// 正在采集
+        /// </summary>
+        public bool IsGrabbing
+        {
+            get { return _IsGrabbing; }
+            private set { SetProperty(ref _IsGrabbing, value); }
+        }
+
+        private ICogImage _Image;
+
+        public ICogImage Image
+        {
+            get { return _Image; }
+            private set { SetProperty(ref _Image, value); }
+        }
+
+        public bool IsConnected { get; private set; }
+
+        public ICameraInfo CameraInfo { get; private set; }
+
+        /// <summary>
+        /// 采集用时
+        /// </summary>
+        public TimeSpan TotalTime { get; private set; }
+
+        /// <summary>
+        /// 错误信息
+        /// </summary>
+        public string ErrorMessage { get; private set; }
+
+        #endregion
+
+        #region 事件
+        public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
+        public event Action<Guid, bool> CameraConnectChangedEvent;
+        #endregion
+
+        public BaslerCamera(Guid _ID, string _Name, string _SerialNumber)
+        {
+            ID = _ID;
+            Name = _Name;
+            SerialNumber = _SerialNumber;
+            List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
+            foreach (ICameraInfo cameraInfo in allCameraInfos)
+            {
+                if (cameraInfo[CameraInfoKey.SerialNumber] == SerialNumber)
+                {
+                    CameraInfo = cameraInfo;
+                    m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
+                    ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
+                    ModelName = cameraInfo[CameraInfoKey.ModelName];
+                    SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
+                    if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
+                    {
+                        CameraType = CameraType.GIGE;
+                    }
+                    else
+                    {
+                        CameraType = CameraType.USB;
+                    }
+                    m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true);    // 激活相机事件
+                    m_MyCamera.CameraOpened += Configuration.AcquireContinuous;                   // 软触发打开
+                    m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
+                    m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
+                    //m_MyCamera.StreamGrabber.ImageGrabbed += StreamGrabber_ImageGrabbed;
+
+                    break;
+                }
+            }
+            IsConnected = false;
+        }
+
+        private void StreamGrabber_ImageGrabbed(object sender, ImageGrabbedEventArgs e)
+        {
+            Stopwatch sw = Stopwatch.StartNew();
+            // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
+            IGrabResult grabResult = e.GrabResult;
+
+            using (grabResult)
+            {
+                // Image grabbed successfully?
+                if (grabResult != null && grabResult.GrabSucceeded)
+                {
+                    ErrorMessage = "";
+                    byte[] pixelData = grabResult.PixelData as byte[];
+                    IntPtr pixelPointer = Marshal.UnsafeAddrOfPinnedArrayElement(pixelData, 0);
+
+                    IntPtr pTemp = IntPtr.Zero;
+                    Basler.Pylon.PixelType enDstPixelType = Basler.Pylon.PixelType.Undefined;
+                    UInt32 nSaveImageNeedSize = 0;
+                    if (IsColorPixelFormat(grabResult.PixelTypeValue))
+                    {
+                        Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
+                        // Lock the bits of the bitmap.
+                        BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
+                        converter.OutputPixelFormat = PixelType.BGRA8packed;
+                        // Place the pointer to the buffer of the bitmap.
+                        IntPtr ptrBmp = bmpData.Scan0;
+                        converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
+                        bitmap.UnlockBits(bmpData);
+                        CogImage24PlanarColor colorImage = new CogImage24PlanarColor(bitmap);
+
+                        Image = colorImage.ScaleImage((int)bitmap.Width, (int)bitmap.Height);
+                    }
+                    else if (IsMonoPixelFormat(grabResult.PixelTypeValue))
+                    {
+                        enDstPixelType = Basler.Pylon.PixelType.Mono8;
+                        nSaveImageNeedSize = (uint)grabResult.Width * (uint)grabResult.Height * 3;
+                        if (grabResult.PixelTypeValue == Basler.Pylon.PixelType.Mono8)
+                        {
+                            pTemp = pixelPointer;
+                        }
+                        else
+                        {
+                            // 其他格式Mono转为Mono8
+                            Basler.Pylon.PixelDataConverter converter = new PixelDataConverter();
+                            converter.OutputPixelFormat = Basler.Pylon.PixelType.RGB8packed;
+                            converter.Convert(pTemp, nSaveImageNeedSize, grabResult);
+                        }
+                        Image = ConvertToICogImage((uint)grabResult.Height, (uint)grabResult.Width, pTemp, enDstPixelType);
+                    }
+                    TotalTime = sw.Elapsed;
+                    ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+                }
+                else
+                {
+                    TotalTime = sw.Elapsed;
+                    ErrorMessage = grabResult.ErrorDescription;
+                    ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+
+                }
+            }
+        }
+
+        #region 方法
+
+        /// <summary>
+        /// 获取设备
+        /// </summary>
+        /// <returns></returns>
+        public static CameraInfo[] GetDevices()
+        {
+            List<CameraInfo> cameras = new List<CameraInfo>();
+            try
+            {
+                if (!CheckSoftwareInstalled().isInstalled)
+                {
+                    LogHelper.WriteLogInfo("未安装pylon 7");
+                    return cameras.ToArray();
+                }
+                List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
+                foreach (ICameraInfo cameraInfo in allCameraInfos)
+                {
+                    if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.Basler_Pylon,
+                            CameraType = CameraType.GIGE,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
+                            Model = cameraInfo[CameraInfoKey.ModelName],
+                            SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
+                            CameraIp = "",
+                        });
+                    }
+                    else if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("usb"))
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.Basler_Pylon,
+                            CameraType = CameraType.USB,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
+                            Model = cameraInfo[CameraInfoKey.ModelName],
+                            SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
+                            CameraIp = "",
+                        });
+                    }
+                    else if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("link"))
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.Basler_Pylon,
+                            CameraType = CameraType.Link,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
+                            Model = cameraInfo[CameraInfoKey.ModelName],
+                            SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
+                            CameraIp = "",
+                        });
+                    }
+                    else
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.Basler_Pylon,
+                            CameraType = CameraType.Unknown,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
+                            Model = cameraInfo[CameraInfoKey.ModelName],
+                            SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
+                            CameraIp = "",
+                        });
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("搜索巴斯勒相机列表时出错!", ex);
+            }
+
+            return cameras.ToArray();
+        }
+
+        /// <summary>
+        /// 检查相机软件是否安装
+        /// </summary>
+        /// <returns></returns>
+        public static (bool isInstalled, string version) CheckSoftwareInstalled()
+        {
+            string softwareName = "pylon 7 Camera Software";
+            string softwareVersion = "7.5.0.15658";
+            string[] registryPaths = new[]
+            {
+                @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
+                @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
+            };
+            foreach (var path in registryPaths)
+            {
+                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
+                {
+                    if (key == null) continue;
+
+                    foreach (string subKeyName in key.GetSubKeyNames())
+                    {
+                        using (RegistryKey subKey = key.OpenSubKey(subKeyName))
+                        {
+                            string displayName = subKey.GetValue("DisplayName")?.ToString();
+                            if (displayName != null && displayName.Contains(softwareName))
+                            {
+                                string version = subKey.GetValue("DisplayVersion")?.ToString();
+                                Version v1 = new Version(version);
+                                Version v2 = new Version(softwareVersion);
+                                if (v1 >= v2)
+                                {
+                                    return (true, version);
+                                }
+                                else
+                                {
+                                    return (false, version);
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            return (false, "");
+        }
+
+        /// <summary>
+        /// 打开相机
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public bool OpenDevice()
+        {
+            if (m_MyCamera == null)
+            {
+                List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
+                foreach (ICameraInfo cameraInfo in allCameraInfos)
+                {
+                    if (cameraInfo[CameraInfoKey.SerialNumber] == SerialNumber)
+                    {
+                        CameraInfo = cameraInfo;
+                        m_MyCamera = new Basler.Pylon.Camera(CameraInfo);
+                        ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
+                        ModelName = cameraInfo[CameraInfoKey.ModelName];
+                        SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
+                        if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
+                        {
+                            CameraType = CameraType.GIGE;
+                        }
+                        else
+                        {
+                            CameraType = CameraType.USB;
+                        }
+                        m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true);    // 激活相机事件
+                        m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
+                        m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
+                        m_MyCamera.CameraOpened += Configuration.AcquireContinuous;                   // 软触发打开
+
+                        break;
+                    }
+                }
+                if (m_MyCamera == null)
+                {
+                    throw new Exception("没有识别到相机");
+                }
+            }
+
+            if (!m_MyCamera.IsOpen)
+            {
+                m_MyCamera.Open();
+                m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
+                m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
+                m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
+            }
+            IsConnected = m_MyCamera.IsConnected;
+
+            return IsConnected;
+        }
+
+        private void M_MyCamera_CameraClosed(object sender, EventArgs e)
+        {
+            CameraConnectChangedEvent?.Invoke(ID, false);
+        }
+
+        private void M_MyCamera_CameraOpened(object sender, EventArgs e)
+        {
+            CameraConnectChangedEvent?.Invoke(ID, true);
+        }
+
+        /// <summary>
+        /// 关闭相机
+        /// </summary>
+        public void CloseDevice()
+        {
+            if (m_MyCamera != null)
+            {
+                if (m_MyCamera.IsOpen)
+                {
+                    m_MyCamera.Close();
+                    m_MyCamera.CameraOpened -= Configuration.AcquireContinuous;                   // 软触发打开
+                    m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
+                    m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
+                    IsConnected = m_MyCamera.IsConnected;
+                    m_MyCamera.Dispose();
+                }
+            }
+        }
+
+        /// <summary>
+        /// 采集图像
+        /// </summary>
+        /// <returns></returns>
+        public ICogImage Grab()
+        {
+            Stopwatch sw = Stopwatch.StartNew();
+            if (m_MyCamera == null)
+            {
+                throw new Exception("相机未连接");
+            }
+            if (!m_MyCamera.IsOpen)
+            {
+                m_MyCamera.Open();
+                m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
+                m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
+                m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
+
+            }
+            if (!m_MyCamera.StreamGrabber.IsGrabbing)
+            {
+                // Start grabbing.
+                m_MyCamera.StreamGrabber.Start();
+            }
+
+            bool Succeed = false;
+            IGrabResult grabResult = null;
+            for (int i = 0; i < 5; i++)
+            {
+                try
+                {
+                    m_MyCamera.ExecuteSoftwareTrigger();
+                    // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
+                    grabResult = m_MyCamera.StreamGrabber.RetrieveResult(1000, TimeoutHandling.ThrowException);
+                    if (grabResult != null && grabResult.GrabSucceeded)
+                    {
+                        ErrorMessage = "";
+                        Succeed = true;
+                        break;
+                    }
+                    else
+                    {
+                        ErrorMessage = grabResult.ErrorDescription;
+                    }
+                }
+                catch (Exception ex)
+                {
+                    ErrorMessage = ex.Message;
+                    m_MyCamera.Close();
+                    m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
+                    m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
+                    m_MyCamera.Open();
+                    m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
+                    m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
+                    m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
+                    IsConnected = m_MyCamera.IsConnected;
+                }
+                finally
+                {
+                    //m_MyCamera.StreamGrabber.Stop();
+                }
+            }
+
+            if (!Succeed)
+            {
+                if (IsConnected)
+                {
+                    IsConnected = false;
+                    CameraConnectChangedEvent?.Invoke(ID, false);
+                }
+                return null;
+            }
+            //m_MyCamera.StreamGrabber.Stop();
+
+            if (IsColorPixelFormat(grabResult.PixelTypeValue))
+            {
+                Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
+                // Lock the bits of the bitmap.
+                BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
+                converter.OutputPixelFormat = PixelType.BGRA8packed;
+                // Place the pointer to the buffer of the bitmap.
+                IntPtr ptrBmp = bmpData.Scan0;
+                converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
+                bitmap.UnlockBits(bmpData);
+                CogImage24PlanarColor colorImage = new CogImage24PlanarColor(bitmap);
+
+                Image = colorImage.ScaleImage((int)bitmap.Width, (int)bitmap.Height);
+            }
+            else if (IsMonoPixelFormat(grabResult.PixelTypeValue))
+            {
+                byte[] pixelData = grabResult.PixelData as byte[];
+                IntPtr pixelPointer = Marshal.UnsafeAddrOfPinnedArrayElement(pixelData, 0);
+
+                IntPtr pTemp = IntPtr.Zero;
+                Basler.Pylon.PixelType enDstPixelType = Basler.Pylon.PixelType.Undefined;
+                UInt32 nSaveImageNeedSize = 0;
+
+                enDstPixelType = Basler.Pylon.PixelType.Mono8;
+                nSaveImageNeedSize = (uint)grabResult.Width * (uint)grabResult.Height * 3;
+                if (grabResult.PixelTypeValue == Basler.Pylon.PixelType.Mono8)
+                {
+                    pTemp = pixelPointer;
+                }
+                else
+                {
+                    // 其他格式Mono转为Mono8
+                    Basler.Pylon.PixelDataConverter converter = new PixelDataConverter();
+                    converter.OutputPixelFormat = Basler.Pylon.PixelType.RGB8packed;
+                    converter.Convert(pTemp, nSaveImageNeedSize, grabResult);
+                }
+                Image = ConvertToICogImage((uint)grabResult.Height, (uint)grabResult.Width, pTemp, enDstPixelType);
+            }
+            GC.Collect();
+            grabResult.Dispose();
+            TotalTime = sw.Elapsed;
+            return Image;
+        }
+
+        private void InvertColors(IGrabResult result)
+        {
+            byte pixelSize = 255;
+            byte[] data = (byte[])result.PixelData;
+            for (long i = 0; i < data.Length; i++)
+            {
+                data[i] = (byte)((int)pixelSize - (int)data[i]);
+            }
+        }
+
+        /// <summary>
+        /// 转换成ICogImage图像
+        /// </summary>
+        /// <param name="nHeight"></param>
+        /// <param name="nWidth"></param>
+        /// <param name="pImageBuf"></param>
+        /// <param name="enPixelType"></param>
+        /// <returns></returns>
+        public ICogImage ConvertToICogImage(UInt32 nHeight, UInt32 nWidth, IntPtr pImageBuf, Basler.Pylon.PixelType enPixelType)
+        {
+            // ch: 显示 || display
+            try
+            {
+                if (enPixelType == Basler.Pylon.PixelType.Mono8)
+                {
+                    CogImage8Root cogImage8Root = new CogImage8Root();
+                    cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
+
+                    CogImage8Grey cogImage8Grey = new CogImage8Grey();
+                    cogImage8Grey.SetRoot(cogImage8Root);
+                    return cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
+                }
+                else
+                {
+                    CogImage8Root image0 = new CogImage8Root();
+                    IntPtr ptr0 = new IntPtr(pImageBuf.ToInt64());
+                    image0.Initialize((int)nWidth, (int)nHeight, ptr0, (int)nWidth, null);
+
+                    CogImage8Root image1 = new CogImage8Root();
+                    IntPtr ptr1 = new IntPtr(pImageBuf.ToInt64() + m_nRowStep);
+                    image1.Initialize((int)nWidth, (int)nHeight, ptr1, (int)nWidth, null);
+
+                    CogImage8Root image2 = new CogImage8Root();
+                    IntPtr ptr2 = new IntPtr(pImageBuf.ToInt64() + m_nRowStep * 2);
+                    image2.Initialize((int)nWidth, (int)nHeight, ptr2, (int)nWidth, null);
+
+                    CogImage24PlanarColor colorImage = new CogImage24PlanarColor();
+                    colorImage.SetRoots(image0, image1, image2);
+                    return colorImage.ScaleImage((int)nWidth, (int)nHeight);
+                }
+            }
+            catch (System.Exception)
+            {
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// 开始采集图像
+        /// </summary>
+        public void StartGrabbing()
+        {
+            if (m_MyCamera == null)
+            {
+                throw new Exception("相机未连接");
+            }
+            if (!m_MyCamera.IsOpen)
+            {
+                throw new Exception("相机未打开");
+            }
+
+            m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
+            //m_MyCamera.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
+            if (IsGrabbing)
+                return;
+
+            if (!m_MyCamera.StreamGrabber.IsGrabbing)
+            {
+                // Start grabbing.
+                m_MyCamera.StreamGrabber.Start();
+            }
+
+            IsGrabbing = true;
+            m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
+            m_hReceiveThread.Start();
+        }
+
+        /// <summary>
+        /// 停止采集图像
+        /// </summary>
+        public void StopGrabbing()
+        {
+            try
+            {
+                //m_MyCamera.StreamGrabber.Stop();
+                IsGrabbing = false;
+
+                Thread.Sleep(1000);
+                if (m_hReceiveThread != null)
+                {
+                    m_hReceiveThread.Abort();
+                    m_hReceiveThread = null;
+                }
+                if (m_MyCamera != null && m_MyCamera.StreamGrabber.IsGrabbing)
+                {
+                    m_MyCamera.StreamGrabber.Stop();
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 设置曝光时间
+        /// </summary>
+        /// <param name="ExposureTime"></param>
+        /// <returns></returns>
+        public bool SetExposureTime(float ExposureTime)
+        {
+            if (m_MyCamera == null)
+            {
+                return false;
+            }
+            if (m_MyCamera.Parameters.Contains(PLCamera.ExposureTimeAbs))
+            {
+                m_MyCamera.Parameters[PLCamera.ExposureTimeAbs].SetValue(ExposureTime);
+            }
+            else
+                m_MyCamera.Parameters[PLCamera.ExposureTime].SetValue(ExposureTime);
+            return true;
+        }
+
+        /// <summary>
+        /// 获取曝光时间
+        /// </summary>
+        /// <returns></returns>
+        public float GetExposureTime()
+        {
+            if (m_MyCamera == null)
+            {
+                return 0;
+            }
+            if (m_MyCamera.Parameters.Contains(PLCamera.ExposureTimeAbs))
+            {
+                return (float)m_MyCamera.Parameters[PLCamera.ExposureTimeAbs].GetValue();
+            }
+            else
+                return (float)m_MyCamera.Parameters[PLCamera.ExposureTime].GetValue();
+        }
+
+        /// <summary>
+        /// 设置增益
+        /// </summary>
+        /// <param name="Gain"></param>
+        /// <returns></returns>
+        public bool SetGain(float Gain)
+        {
+            if (m_MyCamera == null)
+            {
+                return false;
+            }
+            if (m_MyCamera.Parameters.Contains(PLCamera.Gain))
+            {
+                m_MyCamera.Parameters[PLCamera.Gain].SetValue(Gain);
+            }
+            else if (m_MyCamera.Parameters.Contains(PLCamera.GainRaw))
+            {
+                m_MyCamera.Parameters[PLCamera.GainRaw].SetValue((int)Gain);
+            }
+            else if (m_MyCamera.Parameters.Contains(PLCamera.GainAbs))
+            {
+                m_MyCamera.Parameters[PLCamera.GainAbs].SetValue(Gain);
+            }
+            return true;
+        }
+
+        /// <summary>
+        /// 获取增益
+        /// </summary>
+        /// <returns></returns>
+        public float GetGain()
+        {
+            if (m_MyCamera.Parameters.Contains(PLCamera.Gain))
+            {
+                return (float)m_MyCamera.Parameters[PLCamera.Gain].GetValue();
+            }
+            else
+                return (float)m_MyCamera.Parameters[PLCamera.GainAbs].GetValue();
+        }
+
+        private void GetStreamThreadProc()
+        {
+            while (IsGrabbing)
+            {
+                Stopwatch sw = Stopwatch.StartNew();
+                try
+                {
+                    if (!m_MyCamera.IsConnected)
+                    {
+                        m_MyCamera.Close();
+                        m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
+                        m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
+                        m_MyCamera = new Basler.Pylon.Camera(CameraInfo);
+                        m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
+                        m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
+                    }
+                    if (!m_MyCamera.IsOpen)
+                    {
+                        m_MyCamera.Open();
+                        IsConnected = m_MyCamera.IsConnected;
+                    }
+
+                    m_MyCamera.ExecuteSoftwareTrigger();
+                    // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
+                    IGrabResult grabResult = m_MyCamera.StreamGrabber.RetrieveResult(1000, TimeoutHandling.ThrowException);
+                    using (grabResult)
+                    {
+                        // Image grabbed successfully?
+                        if (grabResult != null && grabResult.GrabSucceeded)
+                        {
+                            ErrorMessage = "";
+                            byte[] pixelData = grabResult.PixelData as byte[];
+                            IntPtr pixelPointer = Marshal.UnsafeAddrOfPinnedArrayElement(pixelData, 0);
+
+                            IntPtr pTemp = IntPtr.Zero;
+                            Basler.Pylon.PixelType enDstPixelType = Basler.Pylon.PixelType.Undefined;
+                            UInt32 nSaveImageNeedSize = 0;
+                            if (IsColorPixelFormat(grabResult.PixelTypeValue))
+                            {
+                                Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
+                                // Lock the bits of the bitmap.
+                                BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
+                                converter.OutputPixelFormat = PixelType.BGRA8packed;
+                                // Place the pointer to the buffer of the bitmap.
+                                IntPtr ptrBmp = bmpData.Scan0;
+                                converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
+                                bitmap.UnlockBits(bmpData);
+                                CogImage24PlanarColor colorImage = new CogImage24PlanarColor(bitmap);
+
+                                Image = colorImage.ScaleImage((int)bitmap.Width, (int)bitmap.Height);
+                            }
+                            else if (IsMonoPixelFormat(grabResult.PixelTypeValue))
+                            {
+                                enDstPixelType = Basler.Pylon.PixelType.Mono8;
+                                nSaveImageNeedSize = (uint)grabResult.Width * (uint)grabResult.Height * 3;
+                                if (grabResult.PixelTypeValue == Basler.Pylon.PixelType.Mono8)
+                                {
+                                    pTemp = pixelPointer;
+                                }
+                                else
+                                {
+                                    // 其他格式Mono转为Mono8
+                                    Basler.Pylon.PixelDataConverter converter = new PixelDataConverter();
+                                    converter.OutputPixelFormat = Basler.Pylon.PixelType.RGB8packed;
+                                    converter.Convert(pTemp, nSaveImageNeedSize, grabResult);
+                                }
+                                Image = ConvertToICogImage((uint)grabResult.Height, (uint)grabResult.Width, pTemp, enDstPixelType);
+                            }
+                            TotalTime = sw.Elapsed;
+                            ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+                        }
+                        else
+                        {
+                            TotalTime = sw.Elapsed;
+                            ErrorMessage = grabResult.ErrorDescription;
+                            ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+
+                        }
+                    }
+                }
+                catch (Exception ex)
+                {
+                    TotalTime = sw.Elapsed;
+                    ImageCallbackEvent?.Invoke(Image, TotalTime, ex.Message);
+                }
+                Thread.Sleep(10);
+                GC.Collect();
+            }
+            IsGrabbing = false;
+        }
+
+        /// <summary>
+        /// 图像是否为彩色
+        /// </summary>
+        /// <param name="enType"></param>
+        /// <returns></returns>
+        private bool IsColorPixelFormat(Basler.Pylon.PixelType enType)
+        {
+            switch (enType)
+            {
+                case Basler.Pylon.PixelType.RGB8packed:
+                case Basler.Pylon.PixelType.BGR8packed:
+                case Basler.Pylon.PixelType.RGBA8packed:
+                case Basler.Pylon.PixelType.BGRA8packed:
+                case Basler.Pylon.PixelType.YUV422packed:
+                case Basler.Pylon.PixelType.YUV422_YUYV_Packed:
+                case Basler.Pylon.PixelType.BayerGR8:
+                case Basler.Pylon.PixelType.BayerRG8:
+                case Basler.Pylon.PixelType.BayerGB8:
+                case Basler.Pylon.PixelType.BayerBG8:
+                case Basler.Pylon.PixelType.BayerGB10:
+                case Basler.Pylon.PixelType.BayerGB10pp:
+                case Basler.Pylon.PixelType.BayerBG10:
+                case Basler.Pylon.PixelType.BayerBG10pp:
+                case Basler.Pylon.PixelType.BayerRG10:
+                case Basler.Pylon.PixelType.BayerRG10pp:
+                case Basler.Pylon.PixelType.BayerGR10:
+                case Basler.Pylon.PixelType.BayerGR10pp:
+                case Basler.Pylon.PixelType.BayerGB12:
+                case Basler.Pylon.PixelType.BayerGB12p:
+                case Basler.Pylon.PixelType.BayerBG12:
+                case Basler.Pylon.PixelType.BayerBG12Packed:
+                case Basler.Pylon.PixelType.BayerRG12:
+                case Basler.Pylon.PixelType.BayerRG12Packed:
+                case Basler.Pylon.PixelType.BayerGR12:
+                case Basler.Pylon.PixelType.BayerGR12Packed:
+                    return true;
+                default:
+                    return false;
+            }
+        }
+
+        /// <summary>
+        /// 图像是否为Mono格式
+        /// </summary>
+        /// <param name="enType"></param>
+        /// <returns></returns>
+        private bool IsMonoPixelFormat(Basler.Pylon.PixelType enType)
+        {
+            switch (enType)
+            {
+                case Basler.Pylon.PixelType.Mono8:
+                case Basler.Pylon.PixelType.Mono10:
+                case Basler.Pylon.PixelType.Mono10packed:
+                case Basler.Pylon.PixelType.Mono12:
+                case Basler.Pylon.PixelType.Mono12packed:
+                    return true;
+                default:
+                    return false;
+            }
+        }
+
+        /// <summary>
+        /// 将相机抓取到的图像转换成Bitmap位图
+        /// </summary>
+        /// <param name="grabResult"></param>
+        /// <returns></returns>
+        //Bitmap GrabResult2Bmp(IGrabResult grabResult)
+        //{
+        //    Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);  // 转bit图
+        //    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);            
+        //    PixelDataConverter converter = new PixelDataConverter();            
+        //    converter.OutputPixelFormat = PixelType.BGRA8packed;            
+        //    IntPtr ptrBmp = bmpData.Scan0;            
+        //    converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);            
+        //    bitmap.UnlockBits(bmpData);            
+        //    return (Bitmap)bitmap.Clone();        
+        //}
+        #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);
+        }
+        #endregion
+    }
+}

+ 145 - 0
TeamAAS-VM/Core/Cameras/CameraService.cs

@@ -0,0 +1,145 @@
+using MvCamCtrl.NET;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Core.Cameras;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.Core
+{
+    public class CameraService
+    {
+        private readonly Dictionary<Guid, ICamera> _CameraCollection;
+
+        public CameraService()
+        {
+            _CameraCollection = new Dictionary<Guid, ICamera>();
+        }
+        public bool CreateCamera(Guid id, CameraInfo cameraInfo)
+        {
+            ICamera camera;
+            if (cameraInfo.CameraBrand== Enums.CameraBrand.Basler_Pylon)
+            {
+                camera = new BaslerCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else if (cameraInfo.CameraBrand == Enums.CameraBrand.HikRobot_MVS)
+            {
+                camera = new MvCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else if (cameraInfo.CameraBrand == Enums.CameraBrand.IRayple)
+            {
+                camera = new AHuaCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else if (cameraInfo.CameraBrand == Enums.CameraBrand.Cognex)
+            {
+                camera = new CognexCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else if (cameraInfo.CameraBrand == Enums.CameraBrand.Galaxy)
+            {
+                camera = new GalaxyCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else
+            {
+                camera = new MvCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+
+            if (_CameraCollection.ContainsKey(id))
+            {
+                var currenCamera = _CameraCollection[id];
+                currenCamera.CloseDevice();
+            }
+            else
+            {
+                _CameraCollection.Add(id, camera);
+            }
+            return true;
+        }
+
+        public Task<bool> CreateCameraAsync(Guid id, CameraInfo cameraInfo)
+        {
+            ICamera camera;
+            if (cameraInfo.CameraBrand == Enums.CameraBrand.Basler_Pylon)
+            {
+                camera = new BaslerCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else if (cameraInfo.CameraBrand == Enums.CameraBrand.HikRobot_MVS)
+            {
+                camera = new MvCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else if (cameraInfo.CameraBrand == Enums.CameraBrand.IRayple)
+            {
+                camera = new AHuaCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else if (cameraInfo.CameraBrand == Enums.CameraBrand.Cognex)
+            {
+                camera = new CognexCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else if (cameraInfo.CameraBrand == Enums.CameraBrand.Galaxy)
+            {
+                camera = new GalaxyCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+            else
+            {
+                camera = new MvCamera(id, cameraInfo.CameraName, cameraInfo.SerialNumber);
+            }
+
+            if (_CameraCollection.ContainsKey(id))
+            {
+                var currenCamera = _CameraCollection[id];
+                currenCamera.CloseDevice();
+            }
+            else
+            {
+                _CameraCollection.Add(id, camera);
+            }
+            return Task.FromResult(true);
+        }
+
+        public ICamera GetCamera(Guid id)
+        {
+            return _CameraCollection[id];
+        }
+
+        public Task<ICamera> GetCameraAsync(Guid id)
+        {
+            return Task.FromResult(_CameraCollection[id]);
+        }
+
+        public void UnRegisterCamera(Guid id)
+        {
+            if (_CameraCollection.ContainsKey(id))
+            {
+                var camera = _CameraCollection[id];
+                camera.CloseDevice();
+            }
+        }
+
+        public Task UnRegisterCameraAsync(Guid id)
+        {
+            if (_CameraCollection.ContainsKey(id))
+            {
+                var camera = _CameraCollection[id];
+                camera.CloseDevice();
+            }
+            return Task.CompletedTask;
+        }
+
+        public void Dispose()
+        {
+            foreach (var camera in _CameraCollection) 
+            {
+                try
+                {
+                    camera.Value.CloseDevice();
+                }
+                catch (Exception)
+                {
+
+                }
+            }
+        }
+    }
+}

+ 539 - 0
TeamAAS-VM/Core/Cameras/CognexCamera.cs

@@ -0,0 +1,539 @@
+using Cognex.VisionPro;
+using MaterialDesignThemes.Wpf;
+using Microsoft.Win32;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP;
+
+namespace TeamAAS_VP.Core.Cameras
+{
+    public class CognexCamera : ICamera, INotifyPropertyChanged
+    {
+        #region 字段
+        private Thread m_hReceiveThread;
+        #endregion
+
+        #region 属性
+
+        public CameraBrand CameraBrand { get => CameraBrand.Cognex; }
+
+        public string Name { get; private set; }
+        public Guid ID { get; private set; }
+        public string ManufacturerName { get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public CameraType CameraType { get; private set; }
+
+        ICogAcqFifo CameraAcq;
+
+        public UInt32 ImageWidth { get; private set; }
+
+        public UInt32 ImageHeight { get; private set; }
+
+        private bool _IsGrabbing;
+
+        /// <summary>
+        /// 正在采集
+        /// </summary>
+        public bool IsGrabbing
+        {
+            get { return _IsGrabbing; }
+            private set { SetProperty(ref _IsGrabbing, value); }
+        }
+
+        private ICogImage _Image;
+
+        public ICogImage Image
+        {
+            get { return _Image; }
+            private set { SetProperty(ref _Image, value); }
+        }
+
+        public bool IsConnected { get; private set; }
+
+        /// <summary>
+        /// 采集用时
+        /// </summary>
+        public TimeSpan TotalTime { get; private set; }
+
+        /// <summary>
+        /// 错误信息
+        /// </summary>
+        public string ErrorMessage { get; private set; }
+
+        private bool IsHaveCamera = false;
+        #endregion
+
+        #region 事件
+        public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
+        public event Action<Guid, bool> CameraConnectChangedEvent;
+        #endregion
+
+        public CognexCamera(Guid _ID, string _Name, string _SerialNumber)
+        {
+            ID = _ID;
+            Name = _Name;
+            SerialNumber = _SerialNumber;
+            //using (CogFrameGrabbers mFrameGrabbers = new CogFrameGrabbers())//识别已安装的帧抓取器的类//帧抓取器:相机
+            //{
+            //    foreach (ICogFrameGrabber item in mFrameGrabbers)
+            //    {
+            //        if (item.SerialNumber == SerialNumber)
+            //        {
+            //            var videoFormat = item.AvailableVideoFormats[0];
+
+            //            foreach (string format in item.AvailableVideoFormats)
+            //            {
+            //                if (format == "Generic GigEVision (Mono)")
+            //                {
+            //                    videoFormat = format;
+            //                    break;
+            //                }
+
+            //                if (format != "Generic GigEVision (Bayer Color)") continue;
+            //                videoFormat = format;
+            //                break;
+            //            }
+            //            CameraAcq = item.CreateAcqFifo(videoFormat, CogAcqFifoPixelFormatConstants.Format8Grey, 0,
+            //            true);
+            //            //CameraAcq.OwnedExposureParams.Exposure = exposure;
+            //            //CameraAcq.OwnedBrightnessParams.Brightness = brightness;
+            //            //CameraAcq.OwnedContrastParams.Contrast = contrast;
+            //            //
+            //            CameraAcq.OwnedTriggerParams.TriggerEnabled = true;
+            //            CameraAcq.OwnedTriggerParams.TriggerModel = CogAcqTriggerModelConstants.FreeRun;
+            //            IsHaveCamera = true;
+            //            break;
+            //        }
+
+            //    }
+            //}
+
+            IsConnected = false;
+        }
+
+        #region 方法
+
+        /// <summary>
+        /// 获取设备
+        /// </summary>
+        /// <returns></returns>
+        public static CameraInfo[] GetDevices()
+        {
+            List<CameraInfo> cameras = new List<CameraInfo>();
+            if (!CheckSoftwareInstalled().isInstalled)
+            {
+                LogHelper.WriteLogInfo("未安装Cognex VisionPro");
+                return cameras.ToArray();
+            }
+            using (CogFrameGrabbers mFrameGrabbers = new CogFrameGrabbers())//识别已安装的帧抓取器的类//帧抓取器:相机
+            {
+                foreach (ICogFrameGrabber item in mFrameGrabbers)
+                {
+                    string[] bf1 = item.Name.Split(':');
+                    string manufacturerName=item.Name;
+                    string model = item.Name;
+                    CameraType type = CameraType.GIGE;
+                    if (bf1.Length==3)
+                    {
+                        manufacturerName = bf1[1].Trim();
+                        model = bf1[2].Trim();
+                        if (bf1[0].ToLower().Trim().Contains("gige"))
+                        {
+                            type = CameraType.GIGE;
+                        }
+                        else if (bf1[0].ToLower().Trim().Contains("usb"))
+                        {
+                            type = CameraType.USB;
+                        }
+                        else
+                        {
+                            type = CameraType.Unknown;
+                        }
+                    }
+                    cameras.Add(new Models.CameraInfo()
+                    {
+                        CameraName = "",
+                        CameraBrand = CameraBrand.Cognex,
+                        CameraType = type,
+                        Id = Guid.NewGuid(),
+                        ManufacturerName = manufacturerName,
+                        Model = model,
+                        SerialNumber = item.SerialNumber,
+                        CameraIp = "",
+                    });
+                }
+            }
+            return cameras.ToArray();
+        }
+
+        /// <summary>
+        /// 检查相机软件是否安装
+        /// </summary>
+        /// <returns></returns>
+        public static (bool isInstalled, string version) CheckSoftwareInstalled()
+        {
+            string softwareName = "Cognex VisionPro";
+            string softwareVersion = "90.0.5";
+            string[] registryPaths = new[]
+            {
+                @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
+                @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
+            };
+            foreach (var path in registryPaths)
+            {
+                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
+                {
+                    if (key == null) continue;
+
+                    foreach (string subKeyName in key.GetSubKeyNames())
+                    {
+                        using (RegistryKey subKey = key.OpenSubKey(subKeyName))
+                        {
+                            string displayName = subKey.GetValue("DisplayName")?.ToString();
+                            if (displayName != null && displayName.Contains(softwareName))
+                            {
+                                string version = subKey.GetValue("DisplayVersion")?.ToString();
+                                Version v1 = new Version(version);
+                                Version v2 = new Version(softwareVersion);
+                                if (v1 >= v2)
+                                {
+                                    return (true, version);
+                                }
+                                else
+                                {
+                                    return (false, version);
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            return (false, "");
+        }
+
+        /// <summary>
+        /// 打开相机
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public bool OpenDevice()
+        {
+            IsConnected = false;
+            if (!IsHaveCamera || CameraAcq==null)
+            {
+                using (CogFrameGrabbers mFrameGrabbers = new CogFrameGrabbers())//识别已安装的帧抓取器的类//帧抓取器:相机
+                {
+                    foreach (ICogFrameGrabber item in mFrameGrabbers)
+                    {
+                        if (item.SerialNumber== SerialNumber)
+                        {
+                            var videoFormat = item.AvailableVideoFormats[0];
+
+                            foreach (string format in item.AvailableVideoFormats)
+                            {
+                                if (format == "Generic GigEVision (Mono)")
+                                {
+                                    videoFormat = format;
+                                    break;
+                                }
+
+                                if (format != "Generic GigEVision (Bayer Color)") continue;
+                                videoFormat = format;
+                                break;
+                            }
+                            CameraAcq = item.CreateAcqFifo(videoFormat, CogAcqFifoPixelFormatConstants.Format8Grey, 0,
+                            true);
+                            //CameraAcq.OwnedExposureParams.Exposure = exposure;
+                            //CameraAcq.OwnedBrightnessParams.Brightness = brightness;
+                            //CameraAcq.OwnedContrastParams.Contrast = contrast;
+                            //
+                            CameraAcq.OwnedTriggerParams.TriggerEnabled = true;
+                            CameraAcq.OwnedTriggerParams.TriggerModel = CogAcqTriggerModelConstants.FreeRun;
+                            string[] bf1 = item.Name.Split(':');
+                            string manufacturerName = item.Name;
+                            string model = item.Name;
+                            CameraType type = CameraType.GIGE;
+                            if (bf1.Length == 3)
+                            {
+                                manufacturerName = bf1[1].Trim();
+                                model = bf1[2].Trim();
+                                if (bf1[0].ToLower().Trim().Contains("gige"))
+                                {
+                                    type = CameraType.GIGE;
+                                }
+                                else if (bf1[0].ToLower().Trim().Contains("usb"))
+                                {
+                                    type = CameraType.USB;
+                                }
+                                else
+                                {
+                                    type = CameraType.Unknown;
+                                }
+                            }
+                            ManufacturerName = manufacturerName;
+                            ModelName = model;
+                            IsHaveCamera = true;
+                            break;
+                        }
+                        
+                    }
+                }
+                if (!IsHaveCamera)
+                {
+                    return false;
+                }
+            }
+            if (!IsConnected)
+            {
+                CameraConnectChangedEvent?.Invoke(ID, true);
+            }
+
+            IsConnected = true;
+            return IsConnected;
+        }
+
+        /// <summary>
+        /// 关闭相机
+        /// </summary>
+        public void CloseDevice()
+        {
+            if (CameraAcq!=null)
+            {
+                CameraAcq = null;
+
+            }
+            IsConnected = false;
+        }
+
+        /// <summary>
+        /// 采集图像
+        /// </summary>
+        /// <returns></returns>
+        public ICogImage Grab()
+        {
+            Stopwatch sw = Stopwatch.StartNew();
+            for (int i = 0; i < 5; i++)
+            {
+                try
+                {
+                    if (CameraAcq == null)
+                    {
+                        OpenDevice();
+                    }
+
+                    CameraAcq.Flush();
+                    Image= CameraAcq.CompleteAcquireEx(new CogAcqInfo());
+                    ImageWidth = (uint)Image.Width;
+                    ImageHeight = (uint)Image.Height;
+                    TotalTime = sw.Elapsed;
+                    ErrorMessage = "";
+                    return Image;
+                }
+                catch (Exception ex)
+                {
+                    ErrorMessage = ex.Message;
+                    CloseDevice();
+                    Thread.Sleep(100);
+                    OpenDevice();
+                }
+            }
+            if (IsConnected)
+            {
+                IsConnected = false;
+                CameraConnectChangedEvent?.Invoke(ID, false);
+            }
+            return null;
+        }
+
+        /// <summary>
+        /// 开始采集图像
+        /// </summary>
+        public void StartGrabbing()
+        {
+            if (IsGrabbing)
+                return;
+            IsGrabbing = true;
+            m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
+            m_hReceiveThread.Start();
+        }
+
+        /// <summary>
+        /// 停止采集图像
+        /// </summary>
+        public void StopGrabbing()
+        {
+            try
+            {
+                IsGrabbing = false;
+                Thread.Sleep(1000);
+                if (m_hReceiveThread != null)
+                {
+                    m_hReceiveThread.Abort();
+                    m_hReceiveThread = null;
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 设置曝光时间
+        /// </summary>
+        /// <param name="ExposureTime"></param>
+        /// <returns></returns>
+        public bool SetExposureTime(float ExposureTime)
+        {
+            if (CameraAcq==null)
+                return false;
+            CameraAcq.OwnedExposureParams.Exposure = (double)ExposureTime;
+            return true;
+        }
+
+        /// <summary>
+        /// 获取曝光时间
+        /// </summary>
+        /// <returns></returns>
+        public float GetExposureTime()
+        {
+            if (CameraAcq == null)
+                return 0;
+            return (float)CameraAcq.OwnedExposureParams.Exposure;
+        }
+
+        /// <summary>
+        /// 设置增益
+        /// </summary>
+        /// <param name="Gain"></param>
+        /// <returns></returns>
+        public bool SetGain(float Gain)
+        {
+            if (CameraAcq==null)
+                return false;
+            // 设置增益 
+            CameraAcq.OwnedBrightnessParams.Brightness = (double)Gain;
+            return true;
+        }
+
+        /// <summary>
+        /// 获取增益
+        /// </summary>
+        /// <returns></returns>
+        public float GetGain()
+        {
+            if (CameraAcq == null)
+                return 0;
+            return (float)(CameraAcq.OwnedBrightnessParams.Brightness);
+        }
+
+        private void GetStreamThreadProc()
+        {
+            while (IsGrabbing)
+            {
+                try
+                {
+                    Grab();
+                    
+                }
+                catch (Exception)
+                {
+
+                }
+                ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+                Thread.Sleep(10);
+            }
+            IsGrabbing = false;
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 931 - 0
TeamAAS-VM/Core/Cameras/GalaxyCamera.cs

@@ -0,0 +1,931 @@
+using Cognex.VisionPro;
+using GxIAPINET;
+using MathNet.Numerics.LinearAlgebra;
+using Microsoft.Win32;
+using NPOI.Util;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text.RegularExpressions;
+using System.Threading;
+using TeamAAS_VP.Core.GalaxyMethod;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.Core.Cameras
+{
+    public class GalaxyCamera : ICamera, INotifyPropertyChanged
+    {
+        #region 字段
+        private Thread m_hReceiveThread;
+        static IGXFactory m_objIGXFactory = null; //Factory对像
+        IGXDevice m_objIGXDevice = null; //设备对像
+        IGXStream m_objIGXStream = null; //流对像
+        static List<IGXDeviceInfo> m_listIGXDeviceInfo = new List<IGXDeviceInfo>(); //设备信息列表
+        IGXFeatureControl m_objIGXFeatureControl = null; //远端设备属性控制器对像
+        IGXFeatureControl m_objIGXStreamFeatureControl = null; //流层属性控制器对象
+        IntPtr m_pOutBuffer = IntPtr.Zero;  //图像质量提升或图像格式转换输出Buffer
+        IntPtr m_pBitmapInfo = IntPtr.Zero;
+        bool m_bIsColor = false;               ///<是否支持彩色相机
+        byte[] m_byMonoBuffer = null;                ///<黑白相机buffer
+        byte[] m_byColorBuffer = null;                ///<彩色相机buffer
+        int m_nWidth = 0;                   ///<图像宽度
+        int m_nHeight = 0;                   ///<图像高度
+        IGXImageFormatConvert m_objImageFormatConvert = null;   ///<IGXImageFormatConvert对象,仅供图像格式转换使用
+        CWin32Bitmaps.BITMAPINFO m_objBitmapInfo = new CWin32Bitmaps.BITMAPINFO();
+        #endregion
+
+        #region 属性
+        public string Name { get; private set; }
+
+        public Guid ID { get; private set; }
+
+        public CameraBrand CameraBrand { get => CameraBrand.Galaxy; }
+
+        public string ManufacturerName { get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public CameraType CameraType { get; private set; }
+
+        private bool _IsGrabbing;
+        /// <summary>
+        /// 正在采集
+        /// </summary>
+        public bool IsGrabbing
+        {
+            get { return _IsGrabbing; }
+            private set { SetProperty(ref _IsGrabbing, value); }
+        }
+
+        private ICogImage _Image;
+        public ICogImage Image
+        {
+            get { return _Image; }
+            private set { SetProperty(ref _Image, value); }
+        }
+
+        public bool IsConnected { get; private set; }
+
+        public TimeSpan TotalTime { get; private set; }
+
+        public string ErrorMessage { get; private set; }
+
+        public uint ImageWidth { get; private set; }
+
+        public uint ImageHeight { get; private set; }
+        private bool IsHaveCamera = false;
+        #endregion
+
+        #region 事件
+        public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
+        public event Action<Guid, bool> CameraConnectChangedEvent;
+        #endregion
+
+        public GalaxyCamera(Guid _ID, string _Name, string _SerialNumber)
+        {
+            ID = _ID;
+            Name = _Name;
+            SerialNumber = _SerialNumber;
+
+            var list = GetDevices();
+            foreach (var device in list)
+            {
+                if (device.SerialNumber == _SerialNumber)
+                {
+                    IsHaveCamera = true;
+                    ManufacturerName = device.ManufacturerName;
+                    ModelName = device.Model;
+                    SerialNumber = device.SerialNumber;
+                    CameraType = CameraType.GIGE;
+                    break;
+                }
+            }
+            IsConnected = false;
+        }
+
+        #region 方法
+        /// <summary>
+        /// 获取设备
+        /// </summary>
+        /// <returns></returns>
+        public static CameraInfo[] GetDevices()
+        {
+            m_objIGXFactory = IGXFactory.GetInstance();
+            m_objIGXFactory.Init();//相机初始化
+            List<CameraInfo> cameras = new List<CameraInfo>();
+            if (!CheckSoftwareInstalled().isInstalled)
+            {
+                LogHelper.WriteLogInfo("未安装Galaxy Viewer");
+                return cameras.ToArray();
+            }
+            m_listIGXDeviceInfo.Clear();
+            if (null != m_objIGXFactory)
+            {
+                m_objIGXFactory.UpdateAllDeviceList(200, m_listIGXDeviceInfo);
+            }
+            // 判断当前连接设备个数
+            if (m_listIGXDeviceInfo.Count <= 0)
+            {
+                LogHelper.WriteLogInfo("未检测到设备,请确保设备正常连接然后重启程序!");
+                return cameras.ToArray();
+            }
+            for (int i = 0; i < m_listIGXDeviceInfo.Count; i++)
+            {
+                var deviceType = m_listIGXDeviceInfo[i].GetDeviceClass();
+                if (deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_GEV)
+                {
+                    cameras.Add(new Models.CameraInfo()
+                    {
+                        CameraName = "",
+                        CameraBrand = CameraBrand.Galaxy,
+                        CameraType = CameraType.GIGE,
+                        Id = Guid.NewGuid(),
+                        ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
+                        Model = m_listIGXDeviceInfo[i].GetModelName(),
+                        SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
+                        CameraIp = m_listIGXDeviceInfo[i].GetIP(),
+                    });
+                }
+                else if (deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_USB2 || deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_U3V)
+                {
+                    cameras.Add(new Models.CameraInfo()
+                    {
+                        CameraName = "",
+                        CameraBrand = CameraBrand.Galaxy,
+                        CameraType = CameraType.USB,
+                        Id = Guid.NewGuid(),
+                        ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
+                        Model = m_listIGXDeviceInfo[i].GetModelName(),
+                        SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
+                        CameraIp = m_listIGXDeviceInfo[i].GetIP(),
+                    });
+                }
+                else if (deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_UNKNOWN)
+                {
+                    cameras.Add(new Models.CameraInfo()
+                    {
+                        CameraName = "",
+                        CameraBrand = CameraBrand.Galaxy,
+                        CameraType = CameraType.Unknown,
+                        Id = Guid.NewGuid(),
+                        ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
+                        Model = m_listIGXDeviceInfo[i].GetModelName(),
+                        SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
+                        CameraIp = m_listIGXDeviceInfo[i].GetIP(),
+                    });
+                }
+            }
+            return cameras.ToArray();
+        }
+        /// <summary>
+        /// 检查相机软件是否安装
+        /// </summary>
+        /// <returns></returns>
+        public static (bool isInstalled, string version) CheckSoftwareInstalled()
+        {
+            string softwareName = "Galaxy";
+            string softwareVersion = "2.4.2504";
+            string[] registryPaths = new[]
+            {
+                @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
+                @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
+            };
+            foreach (var path in registryPaths)
+            {
+                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
+                {
+                    if (key == null) continue;
+
+                    foreach (string subKeyName in key.GetSubKeyNames())
+                    {
+                        using (RegistryKey subKey = key.OpenSubKey(subKeyName))
+                        {
+                            string displayName = subKey.GetValue("DisplayName")?.ToString();
+                            if (displayName != null && displayName.Contains(softwareName))
+                            {
+                                string version = subKey.GetValue("DisplayName")?.ToString();
+                                var match = Regex.Match(version, @"\d+(?:\.\d+)+");
+                                if (match.Success)
+                                {
+                                    version = match.Value;
+                                }
+                                else
+                                {
+                                    continue;
+                                }
+                                Version v1 = new Version(version);
+                                Version v2 = new Version(softwareVersion);
+                                if (v1 >= v2)
+                                {
+                                    return (true, version);
+                                }
+                                else
+                                {
+                                    return (false, version);
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            return (false, "");
+        }
+        public void CloseDevice()
+        {
+            try
+            {
+                if (null != m_objIGXFeatureControl)
+                {
+                    m_objIGXFeatureControl.GetCommandFeature("AcquisitionStop").Execute();
+                    m_objIGXFeatureControl = null;
+                }
+                //停止流通道、注销采集回调和关闭流
+                if (null != m_objIGXStream)
+                {
+                    m_objIGXStream.StopGrab();
+                    //注销采集回调函数
+                    m_objIGXStream.UnregisterCaptureCallback();
+                    m_objIGXStream.Close();
+                    m_objIGXStream = null;
+                    m_objIGXStreamFeatureControl = null;
+                }
+                //关闭设备
+                if (null != m_objIGXDevice)
+                {
+                    m_objIGXDevice.Close();
+                    m_objIGXDevice = null;
+                }
+
+                //反初始化
+                if (null != m_objIGXFactory)
+                {
+                    m_objIGXFactory.Uninit();
+                }
+            }
+            catch (Exception ex)
+            {
+            }
+
+            ReleaseBuffer();
+        }
+        public float GetExposureTime()
+        {
+            if (null != m_objIGXFeatureControl)
+            {
+                double dCurShuter = m_objIGXFeatureControl.GetFloatFeature("ExposureTime").GetValue();
+                return (float)dCurShuter;
+            }
+            else
+            { return 0; }
+        }
+        public float GetGain()
+        {
+            if (null != m_objIGXFeatureControl)
+            {
+                double dCurGain = m_objIGXFeatureControl.GetFloatFeature("Gain").GetValue();
+                return (float)dCurGain;
+            }
+            else
+            { return 0; }
+        }
+        public ICogImage Grab()
+        {
+            IImageData objIImageData = null;
+            Stopwatch sw = Stopwatch.StartNew();
+            for (int j = 0; j < 5; j++)
+            {
+                try
+                {
+                    if (null == m_objIGXDevice)
+                    {
+                        OpenDevice();
+                    }
+                    //开启采集流通道
+                    if (null != m_objIGXStream)
+                    {
+                        m_objIGXStream.StartGrab();
+                    }
+                    //发送开采命令
+                    if (null != m_objIGXFeatureControl)
+                    {
+                        m_objIGXFeatureControl.GetCommandFeature("AcquisitionStart").Execute();
+                    }
+                    objIImageData = m_objIGXStream.GetImageNoThrow(500);
+
+                    //===================================
+                    GX_VALID_BIT_LIST emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
+                    if (null != objIImageData)
+                    {
+                        emValidBits = GetBestValudBit(objIImageData.GetPixelFormat());
+                        if (GX_FRAME_STATUS_LIST.GX_FRAME_STATUS_SUCCESS == objIImageData.GetStatus())
+                        {
+                            if (m_bIsColor)
+                            {
+                                IntPtr pRGB24Buffer = IntPtr.Zero;
+                                if (objIImageData.GetPixelFormat() == GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8)
+                                {
+                                    byte[] byColorBufferTmp = new byte[__GetStride(m_nWidth, m_bIsColor) * m_nHeight];
+                                    Marshal.Copy(objIImageData.GetBuffer(), byColorBufferTmp, 0, __GetStride(m_nWidth, m_bIsColor) * m_nHeight);
+                                    pRGB24Buffer = objIImageData.GetBuffer();
+                                    //BGR8格式需要翻转数据后显示
+                                    for (int i = 0; i < m_nHeight; i++)
+                                    {
+                                        Buffer.BlockCopy(byColorBufferTmp, (m_nHeight - i - 1) * m_nWidth * 3, m_byColorBuffer, i * m_nWidth * 3, m_nWidth * 3);
+                                    }
+                                }
+                                else
+                                {
+                                    // 设置目标像素格式
+                                    m_objImageFormatConvert.SetDstFormat(GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8);
+
+                                    // 获取目标像素格式Buffer大小
+                                    UInt64 i64DstBufferize = m_objImageFormatConvert.GetBufferSizeForConversion(objIImageData);
+
+                                    // 设置目标有效位数
+                                    m_objImageFormatConvert.SetValidBits(emValidBits);
+
+                                    // 进行图像格式转换
+                                    m_objImageFormatConvert.Convert(objIImageData, m_pOutBuffer, i64DstBufferize, true);
+                                    Marshal.Copy(m_pOutBuffer, m_byColorBuffer, 0, __GetStride(m_nWidth, m_bIsColor) * m_nHeight);
+                                    pRGB24Buffer = m_pOutBuffer;
+                                }
+                                Image = ConvertImage((uint)m_nWidth, (uint)m_nHeight, pRGB24Buffer, GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8);
+                            }
+                            else
+                            {
+                                IntPtr pRaw8Buffer = IntPtr.Zero;
+                                if (__IsPixelFormat8(objIImageData.GetPixelFormat()))
+                                {
+                                    byte[] byMonoBufferTmp = new byte[__GetStride(m_nWidth, m_bIsColor) * m_nHeight];
+                                    Marshal.Copy(objIImageData.GetBuffer(), byMonoBufferTmp, 0, __GetStride(m_nWidth, m_bIsColor) * m_nHeight);
+                                    pRaw8Buffer = objIImageData.GetBuffer();
+                                    // 黑白相机需要翻转数据后显示
+                                    for (int i = 0; i < m_nHeight; i++)
+                                    {
+                                        Buffer.BlockCopy(byMonoBufferTmp, (m_nHeight - i - 1) * m_nWidth, m_byMonoBuffer, i * m_nWidth, m_nWidth);
+                                    }
+                                }
+                                else
+                                {
+                                    // 设置目标像素格式
+                                    m_objImageFormatConvert.SetDstFormat(GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8);
+
+                                    // 获取目标像素格式Buffer大小
+                                    UInt64 i64DstBufferize = m_objImageFormatConvert.GetBufferSizeForConversion(objIImageData);
+
+                                    // 设置目标有效位数
+                                    m_objImageFormatConvert.SetValidBits(emValidBits);
+
+                                    // 进行图像格式转换
+                                    m_objImageFormatConvert.Convert(objIImageData, m_pOutBuffer, i64DstBufferize, true);
+                                    Marshal.Copy(m_pOutBuffer, m_byMonoBuffer, 0, __GetStride(m_nWidth, m_bIsColor) * m_nHeight);
+                                    pRaw8Buffer = m_pOutBuffer;
+                                }
+                                Image = ConvertImage((uint)m_nWidth, (uint)m_nHeight, pRaw8Buffer, GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8);
+                            }
+                        }
+                    }
+                    if (Image != null)
+                    {
+                        ErrorMessage = "";
+                        TotalTime = sw.Elapsed;
+                        return Image;
+                    }
+                }
+                catch (Exception ex)
+                {
+                    CloseDevice();
+                    OpenDevice();
+                    ErrorMessage = ex.Message;
+                }
+                finally
+                {
+                    if (null != objIImageData)
+                    {
+                        //用完之后释放资源
+                        objIImageData.Destroy();
+                    }
+                }
+            }
+            if (IsConnected)
+            {
+                IsConnected = false;
+                CameraConnectChangedEvent?.Invoke(ID, false);
+            }
+            return null;
+        }
+        public bool OpenDevice()
+        {
+            IsConnected = false;
+
+            var list = GetDevices();
+            foreach (var device in list)
+            {
+                if (device.SerialNumber == SerialNumber)
+                {
+                    IsHaveCamera = true;
+                    ManufacturerName = device.ManufacturerName;
+                    ModelName = device.Model;
+                    CameraType = CameraType.GIGE;
+                    break;
+                }
+            }
+            if (!IsHaveCamera)
+            {
+                //throw new Exception("没有发现相机");
+                return false;
+            }
+
+            // 如果设备已经打开则关闭,保证相机在初始化出错情况下能再次打开
+            if (null != m_objIGXDevice)
+            {
+                m_objIGXDevice.Close();
+                m_objIGXDevice = null;
+            }
+            //打开设备
+            m_objIGXDevice = m_objIGXFactory.OpenDeviceBySN(SerialNumber, GxIAPINET.GX_ACCESS_MODE.GX_ACCESS_EXCLUSIVE);
+            m_objIGXFeatureControl = m_objIGXDevice.GetRemoteFeatureControl();
+            //打开流
+            if (null != m_objIGXDevice)
+            {
+                m_objIGXStream = m_objIGXDevice.OpenStream(0);
+                m_objIGXStreamFeatureControl = m_objIGXStream.GetFeatureControl();
+            }
+            // 建议用户在打开网络相机之后,根据当前网络环境设置相机的流通道包长值,
+            // 以提高网络相机的采集性能,设置方法参考以下代码。
+            GX_DEVICE_CLASS_LIST objDeviceClass = m_objIGXDevice.GetDeviceInfo().GetDeviceClass();
+            if (GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_GEV == objDeviceClass)
+            {
+                // 判断设备是否支持流通道数据包功能
+                if (true == m_objIGXFeatureControl.IsImplemented("GevSCPSPacketSize"))
+                {
+                    // 获取当前网络环境的最优包长值
+                    uint nPacketSize = m_objIGXStream.GetOptimalPacketSize();
+                    // 将最优包长值设置为当前设备的流通道包长值
+                    m_objIGXFeatureControl.GetIntFeature("GevSCPSPacketSize").SetValue(nPacketSize);
+                }
+            }
+            //初始化相机参数
+            if (null != m_objIGXFeatureControl)
+            {
+                //设置采集模式连续采集
+                m_objIGXFeatureControl.GetEnumFeature("AcquisitionMode").SetValue("Continuous");
+                //设置触发模式为关
+                m_objIGXFeatureControl.GetEnumFeature("TriggerMode").SetValue("Off");
+            }
+
+            ReleaseBuffer();
+
+            GxBitmap();
+
+            if (null != m_objIGXStreamFeatureControl)
+            {
+                try
+                {
+                    //设置流层Buffer处理模式为OldestFirst
+                    m_objIGXStreamFeatureControl.GetEnumFeature("StreamBufferHandlingMode").SetValue("OldestFirst");
+                }
+                catch (Exception ex)
+                {
+                }
+            }
+
+            if (!IsConnected)
+            {
+                CameraConnectChangedEvent?.Invoke(ID, true);
+            }
+            IsConnected = true;
+            return IsConnected;
+        }
+        public bool SetExposureTime(float ExposureTime)
+        {
+            if (null == m_objIGXFeatureControl)
+                return false;
+            if (GetExposureTime() != ExposureTime)
+            {
+                bool success = false;
+                for (int i = 0; i < 5; i++)
+                {
+                    m_objIGXFeatureControl.GetFloatFeature("ExposureTime").SetValue(ExposureTime);
+                    success = true;
+                }
+                return success;
+            }
+            return true;
+        }
+        public bool SetGain(float Gain)
+        {
+            if (null == m_objIGXFeatureControl)
+                return false;
+            if (GetGain() != Gain)
+            {
+                bool success = false;
+                for (int i = 0; i < 5; i++)
+                {
+                    m_objIGXFeatureControl.GetFloatFeature("Gain").SetValue(Gain);
+                    success = true;
+                }
+                return success;
+            }
+            return true;
+        }
+        public void StartGrabbing()
+        {
+            if (IsGrabbing)
+                return;
+            IsGrabbing = true;
+            m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
+            m_hReceiveThread.Start();
+        }
+        public void StopGrabbing()
+        {
+            try
+            {
+                IsGrabbing = false;
+                Thread.Sleep(1000);
+                if (m_hReceiveThread != null)
+                {
+                    m_hReceiveThread.Abort();
+                    m_hReceiveThread = null;
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+        private void GetStreamThreadProc()
+        {
+            while (IsGrabbing)
+            {
+                try
+                {
+                    Grab();
+                    ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+                }
+                catch (Exception)
+                {
+
+                }
+                Thread.Sleep(10);
+            }
+            IsGrabbing = false;
+        }
+        #endregion
+
+        #region method
+        /// <summary>
+        /// 初始化设备对象
+        /// </summary>
+        /// <param name="objIGXDevice">设备对象</param>
+        public void GxBitmap()
+        {
+            // 初始化图像格式转换对象
+            m_objImageFormatConvert = m_objIGXFactory.CreateImageFormatConvert();
+            if (null != m_objIGXDevice)
+            {
+                m_nWidth = (int)m_objIGXDevice.GetRemoteFeatureControl().GetIntFeature("Width").GetValue();
+                m_nHeight = (int)m_objIGXDevice.GetRemoteFeatureControl().GetIntFeature("Height").GetValue();
+
+                ImageWidth = (uint)m_nWidth;
+                ImageHeight = (uint)m_nHeight;
+                //获取是否为彩色相机
+                IsSupportColor(ref m_bIsColor);
+            }
+
+            //申请用于缓存图像数据的buffer
+            m_byMonoBuffer = new byte[__GetStride(m_nWidth, m_bIsColor) * m_nHeight];
+            m_byColorBuffer = new byte[__GetStride(m_nWidth, m_bIsColor) * m_nHeight];
+            m_pOutBuffer = Marshal.AllocCoTaskMem(__GetStride(m_nWidth, m_bIsColor) * m_nHeight);
+
+            if (m_bIsColor)
+            {
+                m_objBitmapInfo.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(CWin32Bitmaps.BITMAPINFOHEADER));
+                m_objBitmapInfo.bmiHeader.biWidth = m_nWidth;
+                m_objBitmapInfo.bmiHeader.biHeight = m_nHeight;
+                m_objBitmapInfo.bmiHeader.biPlanes = 1;
+                m_objBitmapInfo.bmiHeader.biBitCount = 24;
+                m_objBitmapInfo.bmiHeader.biCompression = 0;
+                m_objBitmapInfo.bmiHeader.biSizeImage = 0;
+                m_objBitmapInfo.bmiHeader.biXPelsPerMeter = 0;
+                m_objBitmapInfo.bmiHeader.biYPelsPerMeter = 0;
+                m_objBitmapInfo.bmiHeader.biClrUsed = 0;
+                m_objBitmapInfo.bmiHeader.biClrImportant = 0;
+            }
+            else
+            {
+                m_objBitmapInfo.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(CWin32Bitmaps.BITMAPINFOHEADER));
+                m_objBitmapInfo.bmiHeader.biWidth = m_nWidth;
+                m_objBitmapInfo.bmiHeader.biHeight = m_nHeight;
+                m_objBitmapInfo.bmiHeader.biPlanes = 1;
+                m_objBitmapInfo.bmiHeader.biBitCount = 8;
+                m_objBitmapInfo.bmiHeader.biCompression = 0;
+                m_objBitmapInfo.bmiHeader.biSizeImage = 0;
+                m_objBitmapInfo.bmiHeader.biXPelsPerMeter = 0;
+                m_objBitmapInfo.bmiHeader.biYPelsPerMeter = 0;
+                m_objBitmapInfo.bmiHeader.biClrUsed = 0;
+                m_objBitmapInfo.bmiHeader.biClrImportant = 0;
+
+                m_objBitmapInfo.bmiColors = new CWin32Bitmaps.RGBQUAD[256];
+                // 黑白图像需要初始化调色板
+                for (int i = 0; i < 256; i++)
+                {
+                    m_objBitmapInfo.bmiColors[i].rgbBlue = (byte)i;
+                    m_objBitmapInfo.bmiColors[i].rgbGreen = (byte)i;
+                    m_objBitmapInfo.bmiColors[i].rgbRed = (byte)i;
+                    m_objBitmapInfo.bmiColors[i].rgbReserved = 0;
+                }
+            }
+            m_pBitmapInfo = Marshal.AllocHGlobal(2048);
+            Marshal.StructureToPtr(m_objBitmapInfo, m_pBitmapInfo, false);
+        }
+
+        /// <summary>
+        /// 释放buffer
+        /// </summary>
+        public void ReleaseBuffer()
+        {
+            // 释放输出Buffer内存
+            if (m_pOutBuffer != IntPtr.Zero)
+            {
+                Marshal.FreeCoTaskMem(m_pOutBuffer);
+                m_pOutBuffer = IntPtr.Zero;
+            }
+
+            if (m_pBitmapInfo != IntPtr.Zero)
+            {
+                Marshal.FreeHGlobal(m_pBitmapInfo);
+                m_pBitmapInfo = IntPtr.Zero;
+            }
+        }
+        /// <summary>
+        /// 是否支持彩色
+        /// </summary>
+        /// <param name="bIsColorFilter">是否支持彩色</param>
+        public void IsSupportColor(ref bool bIsColorFilter)
+        {
+            bool bIsImplemented = false;
+            bool bIsMono = false;
+            string strPixelFormat = "";
+            uint nPixelFormatValue = 0;
+
+            strPixelFormat = m_objIGXDevice.GetRemoteFeatureControl().GetEnumFeature("PixelFormat").GetValue();
+            if (0 == string.Compare(strPixelFormat, 0, "Mono", 0, 4))
+            {
+                bIsMono = true;
+            }
+            else
+            {
+                bIsMono = false;
+            }
+
+            // 通过当前像素格式判断是否为彩色相机
+            CDecide.GetConvertPixelFormat(strPixelFormat, ref nPixelFormatValue);
+            bIsImplemented = CDecide.GetIsGray(nPixelFormatValue);
+            if ((!bIsMono) && (!bIsImplemented))
+            {
+                bIsColorFilter = true;
+            }
+            else
+            {
+                bIsColorFilter = false;
+            }
+        }
+        /// <summary>
+        /// 计算宽度所占的字节数
+        /// </summary>
+        /// <param name="nWidth">图像宽度</param>
+        /// <param name="bIsColor">是否是彩色相机</param>
+        /// <returns>图像一行所占的字节数</returns>
+        private int __GetStride(int nWidth, bool bIsColor)
+        {
+            return bIsColor ? nWidth * 3 : nWidth;
+        }
+        /// <summary>
+        /// 通过GX_PIXEL_FORMAT_ENTRY获取最优Bit位
+        /// </summary>
+        /// <param name="em">图像数据格式</param>
+        /// <returns>最优Bit位</returns>
+        public GX_VALID_BIT_LIST GetBestValudBit(GX_PIXEL_FORMAT_ENTRY emPixelFormatEntry)
+        {
+            GX_VALID_BIT_LIST emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
+            switch (emPixelFormatEntry)
+            {
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_RGB8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_R8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_G8:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_B8:
+                    {
+                        emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
+                        break;
+                    }
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10_PACKED:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10_PACKED:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10_PACKED:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10_PACKED:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10_PACKED:
+                    {
+                        emValidBits = GX_VALID_BIT_LIST.GX_BIT_2_9;
+                        break;
+                    }
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12_PACKED:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12_PACKED:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12_PACKED:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12_PACKED:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12_PACKED:
+                    {
+                        emValidBits = GX_VALID_BIT_LIST.GX_BIT_4_11;
+                        break;
+                    }
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO14:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR14:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG14:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB14:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG14:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG14_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB14_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR14_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG14_P:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO14_P:
+                    {
+                        emValidBits = GX_VALID_BIT_LIST.GX_BIT_6_13;
+                        break;
+                    }
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO16:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR16:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG16:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB16:
+                case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG16:
+                    {
+                        emValidBits = GX_VALID_BIT_LIST.GX_BIT_8_15;
+                        break;
+                    }
+                default:
+                    break;
+            }
+            return emValidBits;
+        }
+        /// <summary>
+        /// 判断PixelFormat是否为8位
+        /// </summary>
+        /// <param name="emPixelFormatEntry">图像数据格式</param>
+        /// <returns>true为8为数据,false为非8位数据</returns>
+        private bool __IsPixelFormat8(GX_PIXEL_FORMAT_ENTRY emPixelFormatEntry)
+        {
+            const uint PIXEL_FORMATE_BIT = 0x00FF0000; //用于与当前的数据格式进行与运算得到当前的数据位数
+            const uint GX_PIXEL_8BIT = 0x00080000;  //8位数据图像格式
+            bool bIsPixelFormat8 = false;
+            uint uiPixelFormatEntry = (uint)emPixelFormatEntry;
+            if ((uiPixelFormatEntry & PIXEL_FORMATE_BIT) == GX_PIXEL_8BIT)
+            {
+                bIsPixelFormat8 = true;
+            }
+            return bIsPixelFormat8;
+        }
+
+        /// <summary>
+        /// 转换图片
+        /// </summary>
+        /// <param name="nHeight">高</param>
+        /// <param name="nWidth">宽</param>
+        /// <param name="pImageBuf">图片数据</param>
+        /// <param name="enPixelType">像素格式</param>
+        public ICogImage ConvertImage(UInt32 nWidth, UInt32 nHeight, IntPtr pImageBuf, GX_PIXEL_FORMAT_ENTRY enPixelType)
+        {
+            try
+            {
+                if (enPixelType == GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8)
+                {
+                    CogImage8Root cogImage8Root = new CogImage8Root();
+                    cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
+
+                    CogImage8Grey cogImage8Grey = new CogImage8Grey();
+                    cogImage8Grey.SetRoot(cogImage8Root);
+                    var image = cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
+                    System.GC.Collect();
+                    return image;
+                }
+                else
+                {
+                    int stride = (int)nWidth * 3;
+                    CogImage24PlanarColor cogImage24PlanarColor = new CogImage24PlanarColor(new Bitmap((int)nWidth, (int)nHeight, stride, PixelFormat.Format24bppRgb, pImageBuf));
+                    var m_InputImageRgb24 = cogImage24PlanarColor.Copy(CogImageCopyModeConstants.CopyPixels);
+                    return m_InputImageRgb24;
+                }
+            }
+            catch (System.Exception ex)
+            {
+                return null;
+            }
+        }
+
+        #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);
+        }
+        #endregion
+    }
+}

+ 566 - 0
TeamAAS-VM/Core/Cameras/MvCamera.cs

@@ -0,0 +1,566 @@
+using Cognex.VisionPro;
+using CSScripting;
+using Microsoft.Win32;
+using MvCamCtrl.NET;
+using MvCamCtrl.NET.CameraParams;
+using NPOI.SS.Formula.Functions;
+using NPOI.Util;
+using NPOI.XSSF.Model;
+using OpenCvSharp.Dnn;
+using Org.BouncyCastle.Asn1.Tsp;
+using OxyPlot;
+using Sdcb.OpenVINO;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Media.Media3D;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+using TeamAAS_VP;
+
+namespace TeamAAS_VP.Core.Cameras
+{
+    public class MvCamera : ICamera, INotifyPropertyChanged
+    {
+        #region 字段
+        private Thread m_hReceiveThread;
+        #endregion
+
+        #region 属性
+
+        public CameraBrand CameraBrand { get => CameraBrand.HikRobot_MVS; }
+
+        public string Name { get; private set; }
+        public Guid ID { get; private set; }
+        public string ManufacturerName { get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public CameraType CameraType { get; private set; }
+
+        MvCameraAcqTool.MvCameraAcqTool mvCameraAcq;
+
+        public MyCamera.MV_CC_DEVICE_INFO CameraInfo { get; private set; }
+
+        public UInt32 ImageWidth { get; private set; }
+
+        public UInt32 ImageHeight { get; private set; }
+
+        public MvGvspPixelType PixelType { get; private set; }
+
+        private bool _IsGrabbing;
+
+        /// <summary>
+        /// 正在采集
+        /// </summary>
+        public bool IsGrabbing
+        {
+            get { return _IsGrabbing; }
+            private set { SetProperty(ref _IsGrabbing, value); }
+        }
+
+        private ICogImage _Image;
+
+        public ICogImage Image
+        {
+            get { return _Image; }
+            private set { SetProperty(ref _Image, value); }
+        }
+
+        public bool IsConnected { get; private set; }
+
+        private bool IsHaveCamera = false;
+
+        /// <summary>
+        /// 采集用时
+        /// </summary>
+        public TimeSpan TotalTime { get; private set; }
+
+        /// <summary>
+        /// 错误信息
+        /// </summary>
+        public string ErrorMessage { get; private set; }
+        #endregion
+
+        #region 事件
+        public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
+        public event Action<Guid, bool> CameraConnectChangedEvent;
+        #endregion
+
+        public MvCamera(Guid _ID, string _Name, string _SerialNumber)
+        {
+            ID = _ID;
+            Name = _Name;
+            SerialNumber = _SerialNumber;
+            mvCameraAcq = new MvCameraAcqTool.MvCameraAcqTool();
+            MyCamera.MV_CC_DEVICE_INFO_LIST stDeviceList = default(MyCamera.MV_CC_DEVICE_INFO_LIST);
+            mvCameraAcq.EnumDeivce(ref stDeviceList);
+            MyCamera.MV_CC_DEVICE_INFO device = default(MyCamera.MV_CC_DEVICE_INFO);
+            for (int i = 0; i < stDeviceList.nDeviceNum; i++)
+            {
+                device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
+                if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
+                {
+                    MV_GIGE_DEVICE_INFO stGigEDeviceInfo = (MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MV_GIGE_DEVICE_INFO));
+                    if (string.Equals(stGigEDeviceInfo.chSerialNumber, _SerialNumber))
+                    {
+                        ManufacturerName = stGigEDeviceInfo.chManufacturerName;
+                        ModelName = stGigEDeviceInfo.chModelName;
+                        SerialNumber = stGigEDeviceInfo.chSerialNumber;
+                        CameraType = CameraType.GIGE;
+                        CameraInfo = device;
+                        IsHaveCamera = true;
+                        break;
+                    }
+                }
+                else if (device.nTLayerType == CSystem.MV_USB_DEVICE)
+                {
+                    MV_USB3_DEVICE_INFO usbInfo = (MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MV_USB3_DEVICE_INFO));
+                    if (string.Equals(usbInfo.chSerialNumber, _SerialNumber))
+                    {
+                        ManufacturerName = usbInfo.chManufacturerName;
+                        ModelName = usbInfo.chModelName;
+                        SerialNumber = usbInfo.chSerialNumber;
+                        CameraType = CameraType.USB;
+                        CameraInfo = device;
+                        IsHaveCamera = true;
+                        break;
+                    }
+                }
+            }
+            IsConnected = false;
+        }
+
+        #region 方法
+
+        /// <summary>
+        /// 获取设备
+        /// </summary>
+        /// <returns></returns>
+        public static CameraInfo[] GetDevices()
+        {
+            List<CameraInfo> cameras = new List<CameraInfo>();
+            try
+            {
+                if (!CheckSoftwareInstalled().isInstalled)
+                {
+                    LogHelper.WriteLogInfo("未安装MVS");
+                    return cameras.ToArray();
+                }
+                List<CCameraInfo> m_ltDeviceList = new List<CCameraInfo>();
+                int nRet = CSystem.EnumDevices(CSystem.MV_GIGE_DEVICE | CSystem.MV_USB_DEVICE, ref m_ltDeviceList);
+                if (0 != nRet)
+                {
+                    return cameras.ToArray();
+                }
+                for (int i = 0; i < m_ltDeviceList.Count; i++)
+                {
+                    if (m_ltDeviceList[i].nTLayerType == CSystem.MV_GIGE_DEVICE)
+                    {
+                        CGigECameraInfo gigeInfo = (CGigECameraInfo)m_ltDeviceList[i];
+                        cameras.Add(new CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.HikRobot_MVS,
+                            CameraType = CameraType.GIGE,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = gigeInfo.chManufacturerName,
+                            Model = gigeInfo.chModelName,
+                            SerialNumber = gigeInfo.chSerialNumber,
+                            CameraIp = "",
+                        });
+                    }
+                    else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_USB_DEVICE)
+                    {
+                        CUSBCameraInfo usbInfo = (CUSBCameraInfo)m_ltDeviceList[i];
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.HikRobot_MVS,
+                            CameraType = CameraType.USB,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = usbInfo.chManufacturerName,
+                            Model = usbInfo.chModelName,
+                            SerialNumber = usbInfo.chSerialNumber,
+                            CameraIp = "",
+                        });
+                    }
+                    else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_CAMERALINK_DEVICE)
+                    {
+                        CCamLCameraInfo Info = (CCamLCameraInfo)m_ltDeviceList[i];
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraName = "",
+                            CameraBrand = CameraBrand.HikRobot_MVS,
+                            CameraType = CameraType.USB,
+                            Id = Guid.NewGuid(),
+                            ManufacturerName = Info.chManufacturerName,
+                            Model = Info.chModelName,
+                            SerialNumber = Info.chSerialNumber,
+                            CameraIp = "",
+                        });
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("搜索海康相机列表时出错!", ex);
+            }
+
+            return cameras.ToArray();
+        }
+
+        /// <summary>
+        /// 检查相机软件是否安装
+        /// </summary>
+        /// <returns></returns>
+        public static (bool isInstalled, string version) CheckSoftwareInstalled()
+        {
+            string softwareName = "MVS";
+            string softwareVersion = "4.4.0";
+            string[] registryPaths = new[]
+            {
+                @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
+                @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
+            };
+            foreach (var path in registryPaths)
+            {
+                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
+                {
+                    if (key == null) continue;
+
+                    foreach (string subKeyName in key.GetSubKeyNames())
+                    {
+                        using (RegistryKey subKey = key.OpenSubKey(subKeyName))
+                        {
+                            string displayName = subKey.GetValue("DisplayName")?.ToString();
+                            if (displayName != null && displayName.ToUpper().Trim()==softwareName.ToUpper())
+                            {
+                                string version = subKey.GetValue("DisplayVersion")?.ToString();
+                                Version v1 = new Version(version);
+                                Version v2 = new Version(softwareVersion);
+                                if (v1 >= v2)
+                                {
+                                    return (true, version);
+                                }
+                                else
+                                {
+                                    return (false, version);
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            return (false, "");
+        }
+
+        /// <summary>
+        /// 打开相机
+        /// </summary>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public bool OpenDevice()
+        {
+            if (!IsHaveCamera)
+            {
+                mvCameraAcq = new MvCameraAcqTool.MvCameraAcqTool();
+                MyCamera.MV_CC_DEVICE_INFO_LIST stDeviceList = default(MyCamera.MV_CC_DEVICE_INFO_LIST);
+                mvCameraAcq.EnumDeivce(ref stDeviceList);
+                MyCamera.MV_CC_DEVICE_INFO device = default(MyCamera.MV_CC_DEVICE_INFO);
+                for (int i = 0; i < stDeviceList.nDeviceNum; i++)
+                {
+                    device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
+                    if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
+                    {
+                        MV_GIGE_DEVICE_INFO stGigEDeviceInfo = (MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MV_GIGE_DEVICE_INFO));
+                        if (string.Equals(stGigEDeviceInfo.chSerialNumber, SerialNumber))
+                        {
+                            ManufacturerName = stGigEDeviceInfo.chManufacturerName;
+                            ModelName = stGigEDeviceInfo.chModelName;
+                            SerialNumber = stGigEDeviceInfo.chSerialNumber;
+                            CameraType = CameraType.GIGE;
+                            CameraInfo = device;
+                            IsHaveCamera = true;
+                            break;
+                        }
+                    }
+                    else if (device.nTLayerType == CSystem.MV_USB_DEVICE)
+                    {
+                        MV_USB3_DEVICE_INFO usbInfo = (MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MV_USB3_DEVICE_INFO));
+                        if (string.Equals(usbInfo.chSerialNumber, SerialNumber))
+                        {
+                            ManufacturerName = usbInfo.chManufacturerName;
+                            ModelName = usbInfo.chModelName;
+                            SerialNumber = usbInfo.chSerialNumber;
+                            CameraType = CameraType.USB;
+                            CameraInfo = device;
+                            IsHaveCamera = true;
+                            break;
+                        }
+                    }
+                }
+                if (!IsHaveCamera)
+                {
+                    throw new Exception("没有发现相机");
+                }
+            }
+
+            mvCameraAcq.OpenDevice(CameraInfo);
+            mvCameraAcq.AutoExposure = false;
+            mvCameraAcq.TriggerMode = false;
+            if (!IsConnected)
+            {
+                CameraConnectChangedEvent?.Invoke(ID, true);
+            }
+            IsConnected = mvCameraAcq.bIsOpened;
+            return IsConnected;
+        }
+
+        /// <summary>
+        /// 关闭相机
+        /// </summary>
+        public void CloseDevice()
+        {
+            // ch:关闭设备 | en:Close Device
+            mvCameraAcq.CloseDevice();
+        }
+
+        
+
+        /// <summary>
+        /// 采集图像
+        /// </summary>
+        /// <returns></returns>
+        public ICogImage Grab()
+        {
+            Stopwatch sw = Stopwatch.StartNew();
+            for (int i = 0; i < 5; i++)
+            {
+                try
+                {
+                    if (!mvCameraAcq.bIsOpened)
+                    {
+                        OpenDevice();
+                    }
+                    mvCameraAcq.Run();
+                    if (mvCameraAcq.RunStatus.Result == CogToolResultConstants.Accept)
+                    {
+                        ErrorMessage = "";
+                        Image = mvCameraAcq.OutputImage;
+                        if (!IsConnected)
+                        {
+                            IsConnected = true;
+                            CameraConnectChangedEvent?.Invoke(ID, true);
+                        }
+                        TotalTime = sw.Elapsed;
+
+                        return Image;
+                    }
+                    else
+                    {
+                        ErrorMessage = mvCameraAcq.RunStatus.Message;
+                        CloseDevice();
+                        OpenDevice();
+                    }
+                }
+                catch (Exception ex)
+                {
+                    CloseDevice();
+                    OpenDevice();
+                    ErrorMessage = ex.Message;
+                }
+            }
+            if (IsConnected)
+            {
+                IsConnected = false;
+                CameraConnectChangedEvent?.Invoke(ID, false);
+            }
+            return null;
+        }
+
+        /// <summary>
+        /// 开始采集图像
+        /// </summary>
+        public void StartGrabbing()
+        {
+            if (IsGrabbing)
+                return;
+            IsGrabbing = true;
+            m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
+            m_hReceiveThread.Start();
+        }
+
+        /// <summary>
+        /// 停止采集图像
+        /// </summary>
+        public void StopGrabbing()
+        {
+            try
+            {
+                IsGrabbing = false;
+                Thread.Sleep(1000);
+                if (m_hReceiveThread != null)
+                {
+                    m_hReceiveThread.Abort();
+                    m_hReceiveThread = null;
+                }
+            }
+            catch (Exception)
+            {
+
+            }
+        }
+
+        /// <summary>
+        /// 设置曝光时间
+        /// </summary>
+        /// <param name="ExposureTime"></param>
+        /// <returns></returns>
+        public bool SetExposureTime(float ExposureTime)
+        {
+            if (!mvCameraAcq.bIsOpened)
+                return false;
+            mvCameraAcq.ExposureTime = (double)ExposureTime;
+            return true;
+        }
+
+        /// <summary>
+        /// 获取曝光时间
+        /// </summary>
+        /// <returns></returns>
+        public float GetExposureTime()
+        {
+            if (!mvCameraAcq.bIsOpened)
+                return 0;
+            return (float)mvCameraAcq.ExposureTime;
+        }
+
+        /// <summary>
+        /// 设置增益
+        /// </summary>
+        /// <param name="Gain"></param>
+        /// <returns></returns>
+        public bool SetGain(float Gain)
+        {
+            if (!mvCameraAcq.bIsOpened)
+                return false;
+            mvCameraAcq.AnalogGain = (double)Gain;
+            return true;
+        }
+
+        /// <summary>
+        /// 获取增益
+        /// </summary>
+        /// <returns></returns>
+        public float GetGain()
+        {
+            if (!mvCameraAcq.bIsOpened)
+                return 0;
+            return (float)mvCameraAcq.AnalogGain;
+        }
+
+        private void GetStreamThreadProc()
+        {
+            while (IsGrabbing)
+            {
+                try
+                {
+                    Grab();
+                    ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
+                }
+                catch (Exception)
+                {
+
+                }
+                Thread.Sleep(10);
+            }
+            IsGrabbing = false;
+        }
+        #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);
+        }
+        #endregion
+    }
+}

+ 79 - 0
TeamAAS-VM/Core/Common.cs

@@ -0,0 +1,79 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core
+{
+    public static class Common
+    {
+        /// <summary>
+        /// 解析带前导零的 IP 地址字符串
+        /// </summary>
+        /// <param name="ipString"></param>
+        /// <returns></returns>
+        /// <exception cref="FormatException"></exception>
+        public static IPAddress ParseIpWithLeadingZeros(string ipString)
+        {
+            // 分割 IP 地址的四个部分
+            string[] parts = ipString.Split('.');
+            if (parts.Length != 4)
+                throw new FormatException("Invalid IP address format.");
+
+            // 处理每个部分的前导零
+            for (int i = 0; i < parts.Length; i++)
+            {
+                string part = parts[i];
+                if (string.IsNullOrEmpty(part))
+                    throw new FormatException("IP part cannot be empty.");
+
+                // 去除前导零(保留纯 "0" 的情况)
+                if (part.Length > 1 && part.StartsWith("0"))
+                {
+                    part = part.TrimStart('0');
+                    // 如果去除后为空,说明原部分全为0,补回一个0
+                    if (string.IsNullOrEmpty(part))
+                        part = "0";
+                }
+
+                // 验证数值范围 0-255
+                if (!int.TryParse(part, out int value) || value < 0 || value > 255)
+                    return null;
+
+                parts[i] = value.ToString(); // 确保无前导零的字符串
+            }
+
+            // 重新组合为修正后的 IP 地址
+            string correctedIp = string.Join(".", parts);
+            return IPAddress.Parse(correctedIp);
+        }
+
+        /// <summary>
+        /// 将DataTable导出到csv文件中
+        /// </summary>
+        /// <param name="dataTable"></param>
+        /// <param name="filePath"></param>
+        public static void ExportToCsv(System.Data.DataTable dataTable, string filePath)
+        {
+            StringBuilder sb = new StringBuilder();
+            //添加列名
+            foreach (System.Data.DataColumn column in dataTable.Columns)
+            {
+                sb.Append(column.ColumnName + ",");
+            }
+            sb.AppendLine();
+            //添加数据
+            foreach (System.Data.DataRow row in dataTable.Rows)
+            {
+                foreach (var item in row.ItemArray)
+                {
+                    sb.Append(item.ToString() + ",");
+                }
+                sb.AppendLine();
+            }
+            System.IO.File.WriteAllText(filePath, sb.ToString());
+        }
+    }
+}

+ 196 - 0
TeamAAS-VM/Core/CoordinateTransformer.cs

@@ -0,0 +1,196 @@
+using MathNet.Numerics.LinearAlgebra;
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core
+{
+    /// <summary>
+    /// 三点建立坐标系(或者原点及角度),并实现Local与Word坐标系直接的坐标互转换
+    /// </summary>
+    public class CoordinateTransformer
+    {
+        /// <summary>
+        /// 三个点建立坐标系时确定是以X轴作为基准还是Y轴作为基准
+        /// </summary>
+        public enum Axis { X, Y };
+        /// <summary>
+        /// P1 作为新坐标系的原点
+        /// </summary>
+        public Vector<double> P1 { get; }
+        /// <summary>
+        /// 坐标系的基向量
+        /// </summary>
+        public Vector<double> E1 { get; }
+        /// <summary>
+        /// 坐标系的基向量
+        /// </summary>
+        public Vector<double> E2 { get; }
+        public Matrix<double> R { get; }
+        /// <summary>
+        /// 旋转矩阵
+        /// </summary>
+        public Matrix<double> InvR { get; }
+        /// <summary>
+        /// 平移矩阵
+        /// </summary>
+        public Matrix<double> T { get; }
+
+        /// <summary>
+        /// 坐标系的旋转角度
+        /// </summary>
+        public double Angle
+        {
+            get
+            {
+
+                //Vector2 e1 = new Vector2(Math.Cos(radians), Math.Sin(radians)); // 新x轴向量
+                //Vector2 e2 = new Vector2(-Math.Sin(radians), Math.Cos(radians)); // 新y轴向量
+                double thetaRand1 = Math.Asin(E1[1]);
+                double thetaDeg1 = thetaRand1 * 180 / Math.PI; // 将弧度值转换为角度值
+                return Math.Round(thetaDeg1, 3);
+            }
+        }
+
+        /// <summary>
+        /// 三点建立坐标系,并实现Local与Word坐标系直接的坐标互转换
+        /// </summary>
+        /// <param name="x1">原点X坐标</param>
+        /// <param name="y1">原点Y坐标</param>
+        /// <param name="x2">X轴上的点X坐标</param>
+        /// <param name="y2">X轴上的点Y坐标</param>
+        /// <param name="x3">Y轴上的点X坐标</param>
+        /// <param name="y3">Y轴上的点Y坐标</param>
+        /// <param name="axis">三个点建立坐标系时确定是以X轴作为基准还是Y轴作为基准</param>
+        public CoordinateTransformer(double x1, double y1, double x2, double y2, double x3, double y3, Axis axis = Axis.X)
+        {
+            //假设我们有三个点 P1(x1, y1), P2(x2, y2), P3(x3, y3),它们是笛卡尔坐标系的三个点。我们要基于这三个点创建一个经过旋转和平移的坐标系,并且要求两个坐标系中的点可以互相转换。
+            //1.新坐标系的原点:我们可以将 P1 作为新坐标系的原点。因此,新坐标系的原点坐标为 (x1, y1)。
+            P1 = Vector<double>.Build.Dense(new double[] { x1, y1 });
+
+            // Calculate basis vectors
+            Vector<double> p2 = Vector<double>.Build.Dense(new double[] { x2, y2 });
+            Vector<double> p3 = Vector<double>.Build.Dense(new double[] { x3, y3 });
+
+            //2.计算坐标系的基向量:
+            if (axis == Axis.X)
+            {
+                E1 = (p2 - P1) / (p2 - P1).L2Norm();
+                E2 = (p3 - P1 - E1.DotProduct(p3 - P1) * E1) / (p3 - P1 - E1.DotProduct(p3 - P1) * E1).L2Norm();
+            }
+            else
+            {
+                E2 = (p3 - P1) / (p3 - P1).L2Norm();
+                E1 = (p2 - P1 - E2.DotProduct(p2 - P1) * E2) / (p2 - P1 - E2.DotProduct(p2 - P1) * E2).L2Norm();
+            }
+
+            //3.计算旋转矩阵:我们可以使用基向量组成的矩阵作为旋转矩阵。具体地,我们可以将基向量 e1 和 e2 分别作为新坐标系下的 $x$ 和 $y$ 轴,然后组成一个矩阵,再对这个矩阵求逆即可得到旋转矩阵。代码实现:
+            // Compute rotation matrix
+            R = Matrix<double>.Build.DenseOfColumnVectors(E1, E2);
+            InvR = R.Inverse();
+
+            //4.平移矩阵:由于我们选择的原点是 P1,因此我们需要对所有点进行平移,使得新坐标系的原点与笛卡尔坐标系的原点重合。具体地,我们可以使用以下平移矩阵:
+            // Compute translation matrix
+            T = Matrix<double>.Build.DenseIdentity(3);
+            T[0, 2] = -P1[0];
+            T[1, 2] = -P1[1];
+        }
+
+        /// <summary>
+        /// 三点建立坐标系,并实现Local与Word坐标系直接的坐标互转换
+        /// </summary>
+        /// <param name="Po">原点坐标</param>
+        /// <param name="Px">X轴上的点坐标</param>
+        /// <param name="Py">Y轴上的点坐标</param>
+        /// <param name="axis">三个点建立坐标系时确定是以X轴作为基准还是Y轴作为基准</param>
+        public CoordinateTransformer(PointF Po, PointF Px, PointF Py, Axis axis = Axis.X)
+        {
+            //假设我们有三个点 P1(x1, y1), P2(x2, y2), P3(x3, y3),它们是笛卡尔坐标系的三个点。我们要基于这三个点创建一个经过旋转和平移的坐标系,并且要求两个坐标系中的点可以互相转换。
+            //1.新坐标系的原点:我们可以将 P1 作为新坐标系的原点。因此,新坐标系的原点坐标为 (x1, y1)。
+            P1 = Vector<double>.Build.Dense(new double[] { Po.X, Po.Y });
+
+            // Calculate basis vectors
+            Vector<double> p2 = Vector<double>.Build.Dense(new double[] { Px.X, Px.Y });
+            Vector<double> p3 = Vector<double>.Build.Dense(new double[] { Py.X, Py.Y });
+
+            //2.计算坐标系的基向量:
+            if (axis == Axis.X)
+            {
+                E1 = (p2 - P1) / (p2 - P1).L2Norm();
+                E2 = (p3 - P1 - E1.DotProduct(p3 - P1) * E1) / (p3 - P1 - E1.DotProduct(p3 - P1) * E1).L2Norm();
+            }
+            else
+            {
+                E2 = (p3 - P1) / (p3 - P1).L2Norm();
+                E1 = (p2 - P1 - E2.DotProduct(p2 - P1) * E2) / (p2 - P1 - E2.DotProduct(p2 - P1) * E2).L2Norm();
+            }
+
+            //3.计算旋转矩阵:我们可以使用基向量组成的矩阵作为旋转矩阵。具体地,我们可以将基向量 e1 和 e2 分别作为新坐标系下的 $x$ 和 $y$ 轴,然后组成一个矩阵,再对这个矩阵求逆即可得到旋转矩阵。代码实现:
+            // Compute rotation matrix
+            R = Matrix<double>.Build.DenseOfColumnVectors(E1, E2);
+            InvR = R.Inverse();
+
+            //4.平移矩阵:由于我们选择的原点是 P1,因此我们需要对所有点进行平移,使得新坐标系的原点与笛卡尔坐标系的原点重合。具体地,我们可以使用以下平移矩阵:
+            // Compute translation matrix
+            T = Matrix<double>.Build.DenseIdentity(3);
+            T[0, 2] = -P1[0];
+            T[1, 2] = -P1[1];
+        }
+
+        /// <summary>
+        /// 原点及角度建立坐标系
+        /// </summary>
+        /// <param name="Po">原点坐标</param>
+        /// <param name="Theta">角度</param>
+        public CoordinateTransformer(PointF Po, double theta)
+        {
+            double radians = theta * Math.PI / 180; // 将角度值转换为弧度值
+            //1.新坐标系的原点:我们可以将 P1 作为新坐标系的原点。因此,新坐标系的原点坐标为 (x1, y1)。
+            P1 = Vector<double>.Build.Dense(new double[] { Po.X, Po.Y });
+
+            //2.计算坐标系的基向量:
+            E1 = Vector<double>.Build.Dense(new double[] { Math.Cos(radians), Math.Sin(radians) }); // 新x轴向量
+            E2 = Vector<double>.Build.Dense(new double[] { -Math.Sin(radians), Math.Cos(radians) }); // 新y轴向量
+
+            //3.计算旋转矩阵:我们可以使用基向量组成的矩阵作为旋转矩阵。具体地,我们可以将基向量 e1 和 e2 分别作为新坐标系下的 $x$ 和 $y$ 轴,然后组成一个矩阵,再对这个矩阵求逆即可得到旋转矩阵。代码实现:
+            // Compute rotation matrix
+            R = Matrix<double>.Build.DenseOfColumnVectors(E1, E2);
+            InvR = R.Inverse();
+
+            //4.平移矩阵:由于我们选择的原点是 P1,因此我们需要对所有点进行平移,使得新坐标系的原点与笛卡尔坐标系的原点重合。具体地,我们可以使用以下平移矩阵:
+            // Compute translation matrix
+            T = Matrix<double>.Build.DenseIdentity(3);
+            T[0, 2] = -P1[0];
+            T[1, 2] = -P1[1];
+        }
+
+        /// <summary>
+        /// Word坐标系下的点转换成Local坐标系下的点
+        /// </summary>
+        /// <param name="x">Word坐标系下的点X坐标</param>
+        /// <param name="y">Word坐标系下的点Y坐标</param>
+        /// <returns>返回Local坐标系下的点</returns>
+        public Vector<double> ToNewCoord(double x, double y)
+        {
+            Vector<double> pOld = Vector<double>.Build.Dense(new double[] { x, y });
+            Vector<double> pNew = InvR * (pOld - P1);
+            return pNew;
+        }
+
+        /// <summary>
+        /// Local坐标系下的点转换成Word坐标系下的点
+        /// </summary>
+        /// <param name="x">Local坐标系下的点X坐标</param>
+        /// <param name="y">Local坐标系下的点Y坐标</param>
+        /// <returns>返回Word坐标系下的点</returns>
+        public Vector<double> ToOldCoord(double x, double y)
+        {
+            Vector<double> pNew = Vector<double>.Build.Dense(new double[] { x, y });
+            Vector<double> pOld = R * pNew + P1;
+            return pOld;
+        }
+    }
+}

+ 108 - 0
TeamAAS-VM/Core/DetectionResult.cs

@@ -0,0 +1,108 @@
+using OpenCvSharp.Dnn;
+using OpenCvSharp;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Sdcb.OpenVINO;
+
+namespace TeamAAS_VP.Core
+{
+    public class DetectionResult
+    {
+        public int ClassId { get; }
+        public string Class { get; }
+        public Rect Rect { get; }
+        public float Confidence { get; }
+
+        public DetectionResult(int classId, string @class, Rect rect, float confidence)
+        {
+            ClassId = classId;
+            Class = @class;
+            Rect = rect;
+            Confidence = confidence;
+        }
+
+        public static DetectionResult[] FromYolov8DetectionResult(ReadOnlySpan<float> tensorData, Shape shape, Size2f sizeRatio, string[] dicts)
+        {
+            // tensorData: 1x84x8400=705600xF32
+            // shape: 1x84x8400, 84=(x, y, width, height)+80 class confidences, 8400=possible object count(code should for loop 8400 first)
+            float[] t = Transpose(tensorData, shape[1], shape[2]);
+            List<DetectionResult> detResults = new List<DetectionResult>();
+
+            int objectCount = shape[2];
+            int clsRowCount = shape[1];
+            if (dicts.Length != clsRowCount - 4) throw new ArgumentException($"dicts length {dicts.Length} does not match shape cls row count{clsRowCount}.");
+            for (int i = 0; i < objectCount; i++)
+            {
+                int startIdx = i * clsRowCount;
+                ReadOnlySpan<float> rectData = t.AsSpan().Slice(startIdx, 4);
+                ReadOnlySpan<float> confidenceInfo = t.AsSpan().Slice(startIdx + 4, clsRowCount - 4);
+                int maxConfidenceClsId = IndexOfMax(confidenceInfo);
+                float confidence = confidenceInfo[maxConfidenceClsId];
+
+                int centerX = (int)(rectData[0] * sizeRatio.Width);
+                int centerY = (int)(rectData[1] * sizeRatio.Height);
+                int width = (int)(rectData[2] * sizeRatio.Width);
+                int height = (int)(rectData[3] * sizeRatio.Height);
+                detResults.Add(new DetectionResult(
+                    maxConfidenceClsId, dicts[maxConfidenceClsId],
+                    new Rect(centerX - width / 2, centerY - height / 2, width, height),
+                    confidence));
+            }
+
+            CvDnn.NMSBoxes(detResults.Select(x => x.Rect).ToList(), detResults.Select(x => x.Confidence).ToList(), scoreThreshold: 0.5f, nmsThreshold: 0.5f, out int[] indices);
+            return detResults.Where((x, i) => indices.Contains(i)).ToArray();
+        }
+
+        private static int IndexOfMax(ReadOnlySpan<float> data)
+        {
+            if (data.Length == 0) throw new ArgumentException("The provided data span is null or empty.");
+
+            // 初始化最大值及其索引
+            int maxIndex = 0;
+            float maxValue = data[0];
+
+            // 遍历跨度查找最大值及其索引
+            for (int i = 1; i < data.Length; i++)
+            {
+                if (data[i] > maxValue)
+                {
+                    maxValue = data[i];
+                    maxIndex = i;
+                }
+            }
+
+            // 返回最大值及其索引
+            return maxIndex;
+        }
+
+        private static unsafe float[] Transpose(ReadOnlySpan<float> tensorData, int rows, int cols)
+        {
+            float[] transposedTensorData = new float[tensorData.Length];
+
+            fixed (float* pTensorData = tensorData)
+            {
+                fixed (float* pTransposedData = transposedTensorData)
+                {
+                    for (int i = 0; i < rows; i++)
+                    {
+                        for (int j = 0; j < cols; j++)
+                        {
+                            // Index in the original tensor
+                            int index = i * cols + j;
+
+                            // Index in the transposed tensor
+                            int transposedIndex = j * rows + i;
+
+                            pTransposedData[transposedIndex] = pTensorData[index];
+                        }
+                    }
+                }
+            }
+
+            return transposedTensorData;
+        }
+    }
+}

+ 168 - 0
TeamAAS-VM/Core/FileHelper.cs

@@ -0,0 +1,168 @@
+using ControlzEx.Standard;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using TeamAAS_VP.Models;
+using TeamAAS_VP;
+using static Org.BouncyCastle.Math.EC.ECCurve;
+
+namespace TeamAAS_VP.Core
+{
+    public static class FileHelper
+    {
+        /// <summary>
+        /// 写入Json文件
+        /// </summary>
+        /// <param name="obj">对象</param>
+        /// <param name="path">文件路径</param>
+        public static void WriteJsonFile(object obj, string path)
+        {
+            if (!Directory.Exists(Path.GetDirectoryName(path)))
+            {
+                Directory.CreateDirectory(Path.GetDirectoryName(path));
+            }
+            using (StreamWriter sw = new StreamWriter(path))
+            {
+                string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
+                sw.Write(JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented));
+            }
+        }
+
+        /// <summary>
+        /// 读取Json文件
+        /// </summary>
+        /// <typeparam name="T">对象</typeparam>
+        /// <param name="path">文件路径</param>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public static T ReadJsonFile<T>(string path)
+        {
+            if (File.Exists(path))
+            {
+                string buffer;
+                using (StreamReader sr = new StreamReader(path))
+                {
+                    buffer = sr.ReadToEnd();
+                }
+                return JsonConvert.DeserializeObject<T>(buffer);
+            }
+            else
+            {
+                throw new Exception($"文件不存在:[{path}]");
+            }
+        }
+
+        /// <summary>
+        /// 写入文件
+        /// </summary>
+        /// <param name="content">对象</param>
+        /// <param name="path">文件路径</param>
+        public static void WriteFile(string content, string path)
+        {
+            if (!Directory.Exists(Path.GetDirectoryName(path)))
+            {
+                Directory.CreateDirectory(Path.GetDirectoryName(path));
+            }
+            using (StreamWriter sw = new StreamWriter(path))
+            {
+                sw.Write(content);
+            }
+        }
+
+        /// <summary>
+        /// 读取文件
+        /// </summary>
+        /// <param name="path"></param>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        public static string ReadFile(string path)
+        {
+            if (File.Exists(path))
+            {
+                string buffer;
+                using (StreamReader sr = new StreamReader(path))
+                {
+                    buffer = sr.ReadToEnd();
+                }
+                return buffer;
+            }
+            else
+            {
+                throw new Exception($"文件不存在:[{path}]");
+            }
+        }
+
+        /// <summary>
+        /// 读取软件设置参数
+        /// </summary>
+        /// <returns></returns>
+        public static CurentApplicationSettings ReadApplicationConfiguration()
+        {
+            try
+            {
+                if (File.Exists(FilePath.ApplicationConfigurationPath))
+                {
+                    var config = FileHelper.ReadJsonFile<CurentApplicationSettings>(FilePath.ApplicationConfigurationPath);
+                    return config;
+                }
+                else
+                {
+                    var config= new CurentApplicationSettings();
+                    FileHelper.WriteJsonFile(config, FilePath.ApplicationConfigurationPath);
+                    return config;
+                }
+            }
+            catch (Exception)
+            {
+                return new CurentApplicationSettings();
+            }
+        }
+
+        /// <summary>
+        /// 保存软件设置参数
+        /// </summary>
+        /// <param name="config"></param>
+        public static void SaveApplicationConfiguration(CurentApplicationSettings config)
+        {
+            try
+            {
+                config.DT=DateTime.Now;
+                FileHelper.WriteJsonFile(config, FilePath.ApplicationConfigurationPath);
+            }
+            catch (Exception)
+            {
+                
+            }
+        }
+
+        /// <summary>
+        /// 检测文件名是否合规
+        /// </summary>
+        /// <param name="filename"></param>
+        /// <returns></returns>
+        public static bool CheckFileName(string filename)
+        {
+            //
+            // 定义文件名合法性的正则表达式
+            string pattern = @"^[^-\\/:*?""<>|\x00-\x1F]*$"; // 匹配不包含非法字符的文件名
+
+            // 使用正则表达式进行匹配
+            if (Regex.IsMatch(filename, pattern))
+            {
+                //Console.WriteLine("输入的名称符合文件名命名规则,并且不包含非法字符。");
+                return true;
+            }
+            else
+            {
+                //Console.WriteLine("输入的名称不符合文件名命名规则,或者包含非法字符。");
+                return false;
+            }
+        }
+    }
+}

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

@@ -0,0 +1,163 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core
+{
+    /// <summary>
+    /// 应用一些配置文件路径
+    /// </summary>
+    public static class FilePath
+    {
+        /// <summary>
+        /// 用户权限数据库路径
+        /// </summary>
+        public static string UserDbPath = "..//Database File//User.db";
+
+        /// <summary>
+        /// 生产记录数据库路径
+        /// </summary>
+        public static string ProductionRecordsDbPath = "..//Database File//ProductionRecords.db";
+
+        /// <summary>
+        /// 帮助文件夹路径
+        /// </summary>
+        public static string HelpPath = "..//Help";
+
+        /// <summary>
+        /// 校准文件夹路径
+        /// </summary>
+        public static string CalibrationPath = "..//Calibration";
+
+        /// <summary>
+        /// 软件设置参数文件
+        /// </summary>
+        public static string ApplicationConfigurationPath = "..//Config//ApplicationConfigurationPath.cfg";
+
+        /// <summary>
+        /// 相机配置文件路径
+        /// </summary>
+        public static string CamerasConfigurationPath = "..//Config//CameraConfigurationPath.cfg";
+        
+        /// <summary>
+        /// 机器人配置文件路径
+        /// </summary>
+        public static string RobotsConfigurationPath = "..//Config//RobotsConfiguration.cfg";
+
+        /// <summary>
+        /// Feeder配置文件路径
+        /// </summary>
+        public static string FeedersConfigurationPath = "..//Config//FeedersConfiguration.cfg";
+
+        /// <summary>
+        /// PLC配置文件路径
+        /// </summary>
+        public static string PlcConfigurationPath = "..//Config//PlcConfiguration.cfg";
+
+        /// <summary>
+        /// 后台TCP/ip配置文件路径
+        /// </summary>
+        public static string BgTcpIpConfigurationPath = "..//Config//BgTcpIpConfiguration.cfg";
+
+        /// <summary>
+        /// 后台Modbus TCP配置文件路径
+        /// </summary>
+        public static string BgModbusTcpConfigurationPath = "..//Config//BgModbusTcpConfiguration.cfg";
+
+        /// <summary>
+        /// 后台EthernetIP配置文件路径
+        /// </summary>
+        public static string BgEthernetIPCommunicatePath = "..//Config//BgEthernetIPCommunicatePath.cfg";
+
+
+
+        /// <summary>
+        /// 后台 MC 通讯配置(旧版单文件,用于迁移至 Plc 列表)
+        /// </summary>
+        public static string BgMCToPcCommunicatePath = "..//Config//BgMCToPcCommunicatePath.cfg";
+
+        /// <summary>
+        /// 后台 SFIS 配置文件路径
+        /// </summary>
+        public static string BgSfisCommunicatePath = "..//Config//BgSfisCommunicatePath.cfg";
+
+
+
+        /// <summary>
+        /// Modbus TCP 主站配置文件路径(连接电批/扭矩控制器)
+        /// </summary>
+        public static string ModbusTcpMasterConfigurationPath = "..//Config//ModbusTcpMasterConfiguration.cfg";
+
+        /// <summary>
+        /// 字体大小配置文件路径
+        /// </summary>
+        public static string FontSizeConfigurationPath = "..//Config//FontSizeConfiguration.cfg";
+
+        /// <summary>
+        /// 语言配置文件路径
+        /// </summary>
+        public static string LanguageConfigurationPath = "..//Config//LanguageConfiguration.cfg";
+
+        /// <summary>
+        /// 软件配置文件路径
+        /// </summary>
+        public static string DeviceConfigurationPath = "..//Config//DeviceConfiguration.cfg";
+
+        /// <summary>
+        /// 用户点动集合配置文件路径
+        /// </summary>
+        public static string UserInchingConfigurationPath = "..//Config//UserInchingConfiguration.cfg";
+
+        /// <summary>
+        /// 所有产品文件夹路径
+        /// </summary>
+        public static string ProductsPath = "..//Products";
+
+        /// <summary>
+        /// 视觉方案工具文件夹路径
+        /// </summary>
+        public static string VisionTemplatePath = "..//Vision Template";
+
+        /// <summary>
+        /// 产品模板文件夹路径
+        /// </summary>
+        public static string ProductTemplatePath = "..//Product Template";
+
+        /// <summary>
+        /// 简单模式模板流程路径
+        /// </summary>
+        public static string SimpleProcedurePath = "..//Vision Template//TemplateToolBlock.vpp";
+
+        /// <summary>
+        /// 相机校准模板工具组
+        /// </summary>
+        public static string CalibrationToolblockPath = "..//Vision Template//Calibration.vpp";
+
+        /// <summary>
+        /// Feeder清料任务文件路径
+        /// </summary>
+        public static string FeedersClearTaskPath = "..//Config//FeedersClearTask.cfg";
+
+        /// <summary>
+        /// 视觉处理模板脚本路径
+        /// </summary>
+        public static string ScriptVisionTemplatePath = "..//Script Template//Vision Template.cs";
+
+        /// <summary>
+        /// 后台模板脚本路径
+        /// </summary>
+        public static string ScriptBackgroundTemplatePath = "..//Script Template//Background Template.cs";
+
+        /// <summary>
+        /// 后台脚本存放文件夹
+        /// </summary>
+        public static string BackgroundScriptPath = "..//Background Script";
+
+        /// <summary>
+        /// 自动寻频配置文件路径
+        /// </summary>
+        public static string FeederFindFrequencyConfigurationPath = "..//Config//FeederFindFrequencyConfiguration.cfg";
+    }
+}

+ 311 - 0
TeamAAS-VM/Core/GalaxyMethod/CDecide.cs

@@ -0,0 +1,311 @@
+using GxIAPINET;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core.GalaxyMethod
+{
+    public static class CDecide
+    {
+        public const uint GVSP_PIX_MONO = 0x01000000;   ///<判断是否为MONO格式的掩码
+        public const uint GVSP_PIX_RGB = 0x02000000;   ///<判断是否为RGB格式的掩码
+        public const uint GVSP_PIX_CUSTOM = 0x80000000;   ///<判断是否为自定义格式的掩码
+        public const uint GVSP_PIX_COLOR_MASK = 0xFF000000;   ///<判断是否为彩色格式的掩码
+        public const uint GVSP_PIX_ID_MASK = 0x0000FFFF;   ///<将图像格式与下述宏定义做按位与(&)运算,可得到像素格式的ID
+
+        /// <summary>
+        /// 是否支持黑白
+        /// </summary>
+        public static bool GetISMono(uint nPixelFormat)
+        {
+            bool bIsMono = ((GVSP_PIX_COLOR_MASK & nPixelFormat) == GVSP_PIX_MONO);
+            return bIsMono;
+        }
+
+        /// <summary>
+        /// 是否支持彩色
+        /// </summary>
+        public static bool GetIsBayer(uint nPixelFormat)
+        {
+            bool bIsBayer = (((GVSP_PIX_ID_MASK & (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR8) <= (GVSP_PIX_ID_MASK & nPixelFormat)
+                               && (GVSP_PIX_ID_MASK & nPixelFormat) <= (GVSP_PIX_ID_MASK & (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12))
+                               || ((GVSP_PIX_ID_MASK & (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR14) <= (GVSP_PIX_ID_MASK & nPixelFormat)
+                               && (GVSP_PIX_ID_MASK & nPixelFormat) <= (GVSP_PIX_ID_MASK & (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG14))
+                               || ((GVSP_PIX_ID_MASK & (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR16) <= (GVSP_PIX_ID_MASK & nPixelFormat)
+                               && (GVSP_PIX_ID_MASK & nPixelFormat) <= (GVSP_PIX_ID_MASK & (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG16)));
+            return bIsBayer;
+        }
+
+        /// <summary>
+        /// 是否支持RGB
+        /// </summary>
+        public static bool GetIsRGB(uint nPixelFormat)
+        {
+            bool bIsBayer = ((GVSP_PIX_COLOR_MASK & nPixelFormat) == GVSP_PIX_RGB);
+            return bIsBayer;
+        }
+
+        /// <summary>
+        /// 是否支持RGB8
+        /// </summary>
+        public static bool GetIsRGB8(uint nPixelFormat)
+        {
+            bool bIsRGB8 = ((nPixelFormat == (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_RGB8)
+                           || (nPixelFormat == (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8));
+            return bIsRGB8;
+        }
+
+        /// <summary>
+        /// 是否为黑白
+        /// </summary>
+        public static bool GetIsGray(uint nPixelFormat)
+        {
+
+            bool bIsGray = (GetISMono(nPixelFormat)) && (!GetIsBayer(nPixelFormat)) && (!GetIsRGB(nPixelFormat));
+            return bIsGray;
+        }
+
+        /// <summary>
+        /// 根据像素格式获取对应ID
+        /// </summary>
+        public static void GetConvertPixelFormat(String strPixelFormat, ref uint nPixelFormatValue)
+        {
+            switch (strPixelFormat)
+            {
+                case "Mono8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8;
+                    break;
+
+                case "BayerRG8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG8;
+                    break;
+
+                case "BayerGB8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB8;
+                    break;
+
+                case "BayerGR8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR8;
+                    break;
+
+                case "BayerBG8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG8;
+                    break;
+
+                case "RGB8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_RGB8;
+                    break;
+
+                case "BGR8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8;
+                    break;
+
+                case "Mono10":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10;
+                    break;
+
+                case "Mono10_Packed":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10_PACKED;
+                    break;
+
+                case "Mono10_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10_P;
+                    break;
+
+                case "BayerRG10":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10;
+                    break;
+
+                case "BayerRG10_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10_P;
+                    break;
+
+                case "BayerRG10_Packet":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10_PACKED;
+                    break;
+
+                case "BayerGB10":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10;
+                    break;
+
+                case "BayerGB10_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10_P;
+                    break;
+
+                case "BayerGB10_Packet":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10_PACKED;
+                    break;
+
+                case "BayerGR10":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10;
+                    break;
+
+                case "BayerGR10_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10_P;
+                    break;
+
+                case "BayerGR10_Packet":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10_PACKED;
+                    break;
+
+                case "BayerBG10":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10;
+                    break;
+
+                case "BayerBG10_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10_P;
+                    break;
+
+                case "BayerBG10_Packet":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10_PACKED;
+                    break;
+
+                case "Mono12":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12;
+                    break;
+
+                case "Mono12_Packed":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12_PACKED;
+                    break;
+
+                case "Mono12_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12_P;
+                    break;
+
+                case "BayerRG12":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12;
+                    break;
+
+                case "BayerRG12_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12_P;
+                    break;
+
+                case "BayerRG12_Packet":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12_PACKED;
+                    break;
+
+                case "BayerGB12":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12;
+                    break;
+
+                case "BayerGB12_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12_P;
+                    break;
+
+                case "BayerGB12_Packet":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12_PACKED;
+                    break;
+
+                case "BayerGR12":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12;
+                    break;
+
+                case "BayerGR12_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12_P;
+                    break;
+
+                case "BayerGR12_Packet":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12_PACKED;
+                    break;
+
+                case "BayerBG12":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12;
+                    break;
+
+                case "BayerBG12_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12_P;
+                    break;
+
+                case "BayerBG12_Packet":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12_PACKED;
+                    break;
+
+                case "Mono14":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO14;
+                    break;
+
+                case "Mono14_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO14_P;
+                    break;
+
+                case "BayerRG14":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG14;
+                    break;
+
+                case "BayerRG14_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG14_P;
+                    break;
+
+                case "BayerGB14":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB14;
+                    break;
+
+                case "BayerGB14_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB14_P;
+                    break;
+
+                case "BayerGR14":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR14;
+                    break;
+
+                case "BayerGR14_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR14_P;
+                    break;
+
+                case "BayerBG14":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG14;
+                    break;
+
+                case "BayerBG14_P":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG14_P;
+                    break;
+
+                case "Mono16":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO16;
+                    break;
+
+                case "BayerRG16":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG16;
+                    break;
+
+                case "BayerGB16":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB16;
+                    break;
+
+                case "BayerGR16":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR16;
+                    break;
+
+                case "BayerBG16":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG16;
+                    break;
+
+                case "R8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_R8;
+                    break;
+
+                case "B8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_B8;
+                    break;
+
+                case "G8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_G8;
+                    break;
+
+                case "YUV422_8":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_YUV422_8;
+                    break;
+
+                case "YUV422_8_UYVY":
+                    nPixelFormatValue = (uint)GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_YUV422_8_UYVY;
+                    break;
+
+                default:
+                    nPixelFormatValue = 0;
+                    break;
+            }
+        }
+    }
+}

+ 82 - 0
TeamAAS-VM/Core/GalaxyMethod/CWin32Bitmaps.cs

@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading.Tasks;
+//IntPtr
+using HDC = System.IntPtr;
+using LPVOID = System.IntPtr;
+
+//UInt32
+using DWORD = System.UInt32;
+using UINT = System.UInt32;
+
+namespace TeamAAS_VP.Core.GalaxyMethod
+{
+    public class CWin32Bitmaps
+    {
+        [StructLayout(LayoutKind.Sequential)]
+        public struct BITMAPFILEHEADER
+        {
+            public ushort bfType;
+            public int bfSize;
+            public ushort bfReserved1;
+            public ushort bfReserved2;
+            public uint bfOffBits;
+        }
+        [StructLayout(LayoutKind.Sequential)]
+        public struct BITMAPINFOHEADER
+        {
+            public uint biSize;
+            public int biWidth;
+            public int biHeight;
+            public ushort biPlanes;
+            public ushort biBitCount;
+            public uint biCompression;
+            public int biSizeImage;
+            public int biXPelsPerMeter;
+            public int biYPelsPerMeter;
+            public uint biClrUsed;
+            public uint biClrImportant;
+        }
+        [StructLayout(LayoutKind.Sequential)]
+        public struct RGBQUAD
+        {
+            public byte rgbBlue;
+            public byte rgbGreen;
+            public byte rgbRed;
+            public byte rgbReserved;
+        }
+        [StructLayout(LayoutKind.Sequential)]
+        public struct BITMAPINFO
+        {
+            public BITMAPINFOHEADER bmiHeader;
+            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
+            public RGBQUAD[] bmiColors;
+        }
+
+        [DllImport("gdi32.dll", CharSet = CharSet.Auto)]
+        public static extern int SetStretchBltMode(
+            HDC hdc,          // handle to DC
+            int iStretchMode  // bitmap stretching mode
+            );
+
+        [DllImport("gdi32.dll", CharSet = CharSet.Auto)]
+        public static extern int StretchDIBits(
+            HDC hdc,                   // handle to DC
+            int XDest,                 // x-coord of destination upper-left corner
+            int YDest,                 // y-coord of destination upper-left corner
+            int nDestWidth,            // width of destination rectangle
+            int nDestHeight,           // height of destination rectangle
+            int XSrc,                  // x-coord of source upper-left corner
+            int YSrc,                  // y-coord of source upper-left corner
+            int nSrcWidth,             // width of source rectangle
+            int nSrcHeight,            // height of source rectangle
+            byte[] lpBits,             // bitmap bits
+            LPVOID lpBitsInfo,         // bitmap data            
+            UINT iUsage,               // usage options
+            DWORD dwRop                // raster operation code
+            );
+    }
+}

+ 45 - 0
TeamAAS-VM/Core/ImageHelper.cs

@@ -0,0 +1,45 @@
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core
+{
+    public class ImageHelper
+    {
+        /// <summary>
+        /// 压缩并保存图片
+        /// </summary>
+        /// <param name="bitmap"></param>
+        /// <param name="path">目标图像存储路径JPEG</param>
+        /// <param name="quality">压缩等级,0到100,0 最差质量,100 最佳</param>
+        public static void CompressImage(Bitmap bitmap, string path, long quality = 100)
+        {
+            ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
+            System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
+            EncoderParameters parameters = new EncoderParameters(1);
+            EncoderParameter parameter = new EncoderParameter(encoder, quality);
+            parameters.Param[0] = parameter;
+            bitmap.Save(path, codecInfo, parameters);
+            bitmap.Dispose();
+            parameter.Dispose();
+            parameters.Dispose();
+        }
+
+        private static ImageCodecInfo GetEncoderInfo(String mimeType)
+        {
+            int j;
+            ImageCodecInfo[] encoders;
+            encoders = ImageCodecInfo.GetImageEncoders();
+            for (j = 0; j < encoders.Length; ++j)
+            {
+                if (encoders[j].MimeType == mimeType)
+                    return encoders[j];
+            }
+            return null;
+        }
+    }
+}

+ 75 - 0
TeamAAS-VM/Core/IniConfigHelper.cs

@@ -0,0 +1,75 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Core
+{
+    /// <summary>
+    /// INI配置文件操作类(使用 Windows API)
+    /// </summary>
+    public class IniConfigHelper
+    {
+        private readonly string _filePath;
+
+        [DllImport("kernel32")]
+        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
+
+        [DllImport("kernel32")]
+        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
+
+        public IniConfigHelper(string iniFileName = "config.ini")
+        {
+            // 判断路径1
+            if (IsPathContainingDirectory(iniFileName))
+            {
+                if (!Directory.Exists(System.IO.Path.GetDirectoryName(iniFileName)))
+                {
+                    Directory.CreateDirectory(Path.GetDirectoryName(iniFileName));
+                }
+                _filePath=iniFileName;
+            }
+            else
+            {
+                // 配置文件存储路径(应用程序所在目录)
+                _filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, iniFileName);
+            }
+            
+
+            // 如果文件不存在则创建
+            if (!File.Exists(_filePath))
+            {
+                File.Create(_filePath).Close();
+            }
+        }
+
+        public void WriteValue(string section, string key, string value)
+        {
+            WritePrivateProfileString(section, key, value, _filePath);
+        }
+
+        public string ReadValue(string section, string key, string defaultValue = "")
+        {
+            var sb = new StringBuilder(255);
+            GetPrivateProfileString(section, key, defaultValue, sb, 255, _filePath);
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 判断路径是否包含文件夹路径
+        /// </summary>
+        /// <param name="path"></param>
+        /// <returns></returns>
+        public bool IsPathContainingDirectory(string path)
+        {
+            // 获取文件夹路径部分
+            string directory = Path.GetDirectoryName(path);
+
+            // 如果目录部分不为空,则表示路径包含文件夹路径
+            return !string.IsNullOrEmpty(directory);
+        }
+    }
+}

+ 5204 - 0
TeamAAS-VM/Core/Management.cs

@@ -0,0 +1,5204 @@
+using Cognex.VisionPro.ToolBlock;
+using Cognex.VisionPro;
+using MathNet.Numerics.LinearAlgebra;
+using MathNet.Numerics.RootFinding;
+using NPOI.SS.Formula.Functions;
+using NPOI.Util;
+using OpenCvSharp;
+using OpenCvSharp.Flann;
+using Prism.Events;
+using Prism.Ioc;
+using Prism.Mvvm;
+using Prism.Regions;
+using Prism.Services.Dialogs;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Net.Sockets;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Interop;
+using System.Windows.Media;
+using System.Windows.Media.Media3D;
+using Team.FFFeederService;
+using Team.FFFeederService.Interfaces;
+using TeamAAS_VP.Data;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Events;
+using TeamAAS_VP.Models;
+using TeamAAS_VP.ViewModels.Home;
+using TeamAAS_VP;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+using static MaterialDesignThemes.Wpf.Theme.ToolBar;
+using System.ComponentModel;
+using System.Collections;
+using System.Reflection.Metadata;
+using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.Core.PLCs;
+using TeamAAS_VP.Interfaces;
+using Opc.Ua;
+using TeamAAS_VP.Core.Robots;
+using TeamAAS_VP.Core.RFID;
+using TeamAAS_VP.Controls;
+using TeamAAS_VP.Core.Sfis;
+
+namespace TeamAAS_VP.Core
+{
+    public class Management : BindableBase
+    {
+        /// <summary>EthernetIP 底栏状态项固定 Id(与设备 Id 无关)</summary>
+        public static readonly Guid EthernetIpStatusId = new Guid("E4E10000-0001-4000-8000-000000000001");
+
+        #region 字段
+        IRegionManager _regionManager;
+        IEventAggregator _eventAggregator;
+        IContainerProvider _container;
+
+        System.Threading.Timer cTtimer;
+        System.Threading.Timer yieldtimer;
+        private bool IsStart = false;
+        private DateTime StartTime = DateTime.Now;
+
+        #endregion
+
+        #region 属性
+        /// <summary>
+        /// 当前用户
+        /// </summary>
+        public User CurrentUser { get; set; } = new User() { UserName = "操作员", UserPassword = "", IsRemember = false, userPart = Enums.UserPart.Operator, CreateTime = DateTime.Now };
+
+        /// <summary>
+        /// 设备参数
+        /// </summary>
+        public DeviceConfiguration DeviceConfig { get; set; } = new DeviceConfiguration();
+
+        private Language _CurrentLanguage = Language.ChineseSimplified;
+        /// <summary>
+        /// 当前软件使用的语言
+        /// </summary>
+        public Language CurrentLanguage
+        {
+            get { return _CurrentLanguage; }
+            set { SetProperty(ref _CurrentLanguage, value); }
+        }
+
+        private ObservableCollection<ShowRender> _Renders;
+
+        /// <summary>
+        /// 显示界面
+        /// </summary>
+        public ObservableCollection<ShowRender> Renders
+        {
+            get { return _Renders; }
+            set { SetProperty(ref _Renders, value); }
+        }
+
+
+        private Dictionary<Guid, Thread> _plcTrigger = new Dictionary<Guid, Thread>();
+
+        /// <summary>
+        /// 当前plc触发监控
+        /// </summary>
+        public Dictionary<Guid, Thread> PlcTrigger { get => _plcTrigger; set => _plcTrigger = value; }
+
+        private ObservableCollection<ProductModel> _Products;
+
+        /// <summary>
+        /// 产品列表
+        /// </summary>
+        public ObservableCollection<ProductModel> Products
+        {
+            get { return _Products; }
+            set { SetProperty(ref _Products, value); }
+        }
+
+        private ProductModel _CurrentProduct;
+
+        /// <summary>
+        /// 当前产品
+        /// </summary>
+        public ProductModel CurrentProduct
+        {
+            get { return _CurrentProduct; }
+            set { SetProperty(ref _CurrentProduct, value); }
+        }
+
+        public FeederService FeederService { get; set; }
+
+        public RobotService RobotService { get; set; }
+
+        public CameraService CameraService { get; set; }
+
+        public PlcService PlcService { get; set; }
+
+        public BgCommunicate BgCommunicate { get; private set; }
+
+        public BgModbusTcpCommunicate BgModbusTcpCommunicate { get; private set; }
+
+
+        private CancellationTokenSource _handshakeCts;
+        private Task _handshakeTask;
+        private CancellationTokenSource _heartbeatCts;
+        private Task _heartbeatTask;
+        private CancellationTokenSource _sfisSignalCts;
+        private Task _sfisSignalTask;
+        private SfisWorkflowService _sfisWorkflow;
+        private RFIDTagData _lastRfidTag;
+        private readonly object _sync = new object();
+        public SIG350RFIDClient BgEipCommunicate { get; private set; }
+
+        private CancellationTokenSource _mcReconnectCts;
+        private Task _mcReconnectTask;
+        private readonly object _mcReconnectSync = new object();
+        private DateTime _mcLastReconnectAttempt = DateTime.MinValue;
+        private const int McReconnectIntervalMs = 3000;
+        private Action<string> _mcPlcLogHandler;
+        private volatile bool _mcMonitorLoopsStarted;
+
+        public ModbusTcpMasterCommunicate ModbusTcpMasterCommunicate { get; private set; }
+
+        /// <summary>
+        /// Modbus TCP 主站配置(连接电批等设备)
+        /// </summary>
+        public ModbusTcpMasterConfig ModbusTcpMasterConfig { get; set; } = new ModbusTcpMasterConfig();
+
+        private ObservableCollection<StatusInfo> _Status = new ObservableCollection<StatusInfo>();
+
+        /// <summary>
+        /// 状态栏集合
+        /// </summary>
+        public ObservableCollection<StatusInfo> Status
+        {
+            get { return _Status; }
+            set { SetProperty(ref _Status, value); }
+        }
+
+        private TimeSpan _CT;
+
+        public TimeSpan CT
+        {
+            get { return _CT; }
+            set { SetProperty(ref _CT, value); }
+        }
+
+        private Int64 _TotalQuantity;
+        /// <summary>
+        /// 总产量
+        /// </summary>
+        public Int64 TotalQuantity
+        {
+            get { return _TotalQuantity; }
+            set { SetProperty(ref _TotalQuantity, value); }
+        }
+
+        private Int64 _TotalQuantityToday;
+        /// <summary>
+        /// 当天的总产量
+        /// </summary>
+        public Int64 TotalQuantityToday
+        {
+            get { return _TotalQuantityToday; }
+            set { SetProperty(ref _TotalQuantityToday, value); }
+        }
+
+        private Int64 _CurrentUPH;
+        /// <summary>
+        /// 当前的UPH
+        /// </summary>
+        public Int64 CurrentUPH
+        {
+            get { return _CurrentUPH; }
+            set { SetProperty(ref _CurrentUPH, value); }
+        }
+
+        public Dictionary<string, object> BackupObject { get; set; } = new Dictionary<string, object>();
+
+        #endregion
+
+        #region 命令
+
+        #endregion
+
+        #region 事件
+
+        #endregion
+
+        public Management(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container)
+        {
+            _regionManager = regionManager;
+            _eventAggregator = ea;
+            _container = container;
+            cTtimer = new Timer(DoCycleTime, null, 5000, 100);
+            yieldtimer = new Timer(DoYieldTime, null, 10000, 1000);
+            Renders = new ObservableCollection<ShowRender>();
+        }
+
+        #region 配置参数读写操作
+        /// <summary>
+        /// 读取配置参数
+        /// </summary>
+        public void ReadConfig()
+        {
+            ReadCamerasDeviceConfig();
+            ReadRobotsDeviceConfig();
+            ReadFeedersDeviceConfig();
+            ReadPlcDeviceConfig();
+            ReadBgTcpIpDeviceConfig();
+            ReadBgModbusTcpDeviceConfig();
+            ReadModbusTcpMasterDeviceConfig();
+            ReadBgEthernetIPDeviceConfig();
+            ReadBgSfisDeviceConfig();
+        }
+
+        /// <summary>
+        /// 读取相机设备配置参数
+        /// </summary>
+        public void ReadCamerasDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.CamerasConfigurationPath))
+                {
+                    DeviceConfig.Cameras = FileHelper.ReadJsonFile<ObservableCollection<CameraInfo>>(FilePath.CamerasConfigurationPath);
+                }
+                else
+                {
+                    DeviceConfig.Cameras = new ObservableCollection<CameraInfo>();
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.Robots = new ObservableCollection<RobotInfo>();
+                LogHelper.WriteLogError("加载相机配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存相机设备配置参数
+        /// </summary>
+        public void SaveCamerasDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(DeviceConfig.Cameras, FilePath.CamerasConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存相机配置参数至文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 读取机器人设备配置参数
+        /// </summary>
+        public void ReadRobotsDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.RobotsConfigurationPath))
+                {
+                    DeviceConfig.Robots = FileHelper.ReadJsonFile<ObservableCollection<RobotInfo>>(FilePath.RobotsConfigurationPath);
+                }
+                else
+                {
+                    DeviceConfig.Robots = new ObservableCollection<RobotInfo>();
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.Robots = new ObservableCollection<RobotInfo>();
+                LogHelper.WriteLogError("加载机器人配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存机器人设备配置参数
+        /// </summary>
+        public void SaveRobotsDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(DeviceConfig.Robots, FilePath.RobotsConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存机器人配置参数至文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 读取Feeder设备配置参数
+        /// </summary>
+        public void ReadFeedersDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.FeedersConfigurationPath))
+                {
+                    DeviceConfig.Feeders = FileHelper.ReadJsonFile<ObservableCollection<FeederInfo>>(FilePath.FeedersConfigurationPath);
+                }
+                else
+                {
+                    DeviceConfig.Feeders = new ObservableCollection<FeederInfo>();
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.Feeders = new ObservableCollection<FeederInfo>();
+                LogHelper.WriteLogError("加载Feeder配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存Feeder设备配置参数
+        /// </summary>
+        public void SaveFeederDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(DeviceConfig.Feeders, FilePath.FeedersConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存Feeder配置参数至文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 读取PLC设备配置参数
+        /// </summary>
+        public void ReadPlcDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.PlcConfigurationPath))
+                {
+                    DeviceConfig.Plcs = FileHelper.ReadJsonFile<ObservableCollection<PlcInfo>>(FilePath.PlcConfigurationPath);
+                }
+                else
+                {
+                    DeviceConfig.Plcs = new ObservableCollection<PlcInfo>();
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.Plcs = new ObservableCollection<PlcInfo>();
+                LogHelper.WriteLogError("加载PLC配置文件时出错!", ex);
+            }
+
+            TryMigrateLegacyMcConfig();
+        }
+
+        private void TryMigrateLegacyMcConfig()
+        {
+            if (DeviceConfig.Plcs.Any(p => p.CommunicationType == CommunicationType.Mitsubishi_MC))
+                return;
+
+            try
+            {
+                if (!File.Exists(FilePath.BgMCToPcCommunicatePath))
+                    return;
+
+                var legacy = FileHelper.ReadJsonFile<MCToPCInfo>(FilePath.BgMCToPcCommunicatePath);
+                if (legacy == null)
+                    return;
+
+                var mcPlc = new PlcInfo
+                {
+                    Id = Guid.NewGuid(),
+                    Name = "Mitsubishi MC",
+                    CommunicationType = CommunicationType.Mitsubishi_MC
+                };
+                mcPlc.ApplyMcInfo(legacy);
+                DeviceConfig.Plcs.Add(mcPlc);
+                SavePlcDeviceConfig();
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("迁移旧版 MC 配置至 PLC 列表时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存PLC设备配置参数
+        /// </summary>
+        public void SavePlcDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(DeviceConfig.Plcs, FilePath.PlcConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存PLC配置参数至文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 读取语言配置参数
+        /// </summary>
+        public void ReadLanguageDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.LanguageConfigurationPath))
+                {
+                    CurrentLanguage = FileHelper.ReadJsonFile<Language>(FilePath.LanguageConfigurationPath);
+                }
+                else
+                {
+                    CurrentLanguage = Language.ChineseSimplified;
+                }
+            }
+            catch (Exception ex)
+            {
+                CurrentLanguage = Language.ChineseSimplified;
+                LogHelper.WriteLogError("加载Language配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存语言配置参数
+        /// </summary>
+        public void SaveLanguageDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(CurrentLanguage, FilePath.LanguageConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存Language配置参数至文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 读取后台TCPIP通讯配置参数
+        /// </summary>
+        public void ReadBgTcpIpDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.BgTcpIpConfigurationPath))
+                {
+                    DeviceConfig.BgCommunicate = FileHelper.ReadJsonFile<BgTcpIP>(FilePath.BgTcpIpConfigurationPath);
+                }
+                else
+                {
+                    DeviceConfig.BgCommunicate = new BgTcpIP();
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.BgCommunicate = new BgTcpIP();
+                LogHelper.WriteLogError("加载后台TCPIP通讯配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存后台TCPIP通讯配置参数
+        /// </summary>
+        public void SaveBgTcpIpDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(DeviceConfig.BgCommunicate, FilePath.BgTcpIpConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存后台TCPIP通讯配置参数至文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 读取后台ModbusTcp通讯配置参数
+        /// </summary>
+        public void ReadBgModbusTcpDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.BgModbusTcpConfigurationPath))
+                {
+                    DeviceConfig.BgModbusCommunicate = FileHelper.ReadJsonFile<BgModbusTcp>(FilePath.BgModbusTcpConfigurationPath);
+                }
+                else
+                {
+                    DeviceConfig.BgModbusCommunicate = new BgModbusTcp();
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.BgModbusCommunicate = new BgModbusTcp();
+                LogHelper.WriteLogError("加载后台Modbus TCP通讯配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存后台ModbusTcp通讯配置参数
+        /// </summary>
+        public void SaveBgModbusTcpDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(DeviceConfig.BgModbusCommunicate, FilePath.BgModbusTcpConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存后台ModbusTcp通讯配置参数至文件时出错!", ex);
+            }
+        }
+
+
+
+        /// <summary>
+        /// 读取后台EthernetIP通讯配置参数
+        /// </summary>
+        public void ReadBgEthernetIPDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.BgEthernetIPCommunicatePath))
+                {
+                    DeviceConfig.BgEthernetIPCommunicate = FileHelper.ReadJsonFile<BgEthernetIP>(FilePath.BgEthernetIPCommunicatePath);
+                    
+                }
+                else
+                {
+                    DeviceConfig.BgEthernetIPCommunicate = new BgEthernetIP();
+                    FileHelper.WriteJsonFile(DeviceConfig.BgEthernetIPCommunicate, FilePath.BgEthernetIPCommunicatePath);
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.BgEthernetIPCommunicate = new BgEthernetIP();
+                LogHelper.WriteLogError("加载后台Eip通讯配置文件时出错!", ex);
+            }
+        }
+
+        public void ReadBgSfisDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.BgSfisCommunicatePath))
+                {
+                    DeviceConfig.BgSfisCommunicate = FileHelper.ReadJsonFile<BgSfisConfig>(FilePath.BgSfisCommunicatePath);
+                }
+                else
+                {
+                    DeviceConfig.BgSfisCommunicate = new BgSfisConfig();
+                    FileHelper.WriteJsonFile(DeviceConfig.BgSfisCommunicate, FilePath.BgSfisCommunicatePath);
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.BgSfisCommunicate = new BgSfisConfig();
+                LogHelper.WriteLogError("加载 SFIS 配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存EIP配置
+        /// </summary>
+        public void SaveBgEthernetIPDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(DeviceConfig.BgEthernetIPCommunicate, FilePath.BgEthernetIPCommunicatePath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存后台Eip通讯配置参数至文件时出错!", ex);
+            }
+        }
+
+        public void SaveBgSfisDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(DeviceConfig.BgSfisCommunicate, FilePath.BgSfisCommunicatePath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存 SFIS 配置参数至文件时出错!", ex);
+            }
+        }
+
+        #endregion
+
+        #region 初始化硬件模块
+        /// <summary>
+        /// 初始化视觉
+        /// </summary>
+        public Tuple<bool, string> InitVision()
+        {
+            try
+            {
+
+                return new Tuple<bool, string>(true, "");
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("初始化VM视觉方式时出错!", ex);
+                return new Tuple<bool, string>(false, ex.Message);
+            }
+
+        }
+
+        /// <summary>
+        /// 初始化Feeder
+        /// </summary>
+        /// <returns></returns>
+        public async Task<Tuple<bool, string>> InitFeeders()
+        {
+            FeederService = new FeederService();
+            StringBuilder sb = new StringBuilder();
+            foreach (var item in DeviceConfig.Feeders)
+            {
+                FeederService.CreateFeeder(item.Id, item.IP, item.Port, item.FeederBrand);
+
+                Status.Add(new StatusInfo(item.Id, item.FeederName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
+                try
+                {
+                    FeederService.GetFeeder(item.Id).FeederConnectedEvent += Management_FeederConnectedEvent;
+                    FeederService.GetFeeder(item.Id).FeederDisconnectedEvent += Management_FeederDisconnectedEvent;
+                    await FeederService.GetFeeder(item.Id).ConnectAsync();     //连接Feeder
+                    //SendTaskMessage($"{item.FeederName}已连接!", MessageLevel.Debug);
+                }
+                catch (Exception ex)
+                {
+                    sb.AppendLine($"{item.FeederName}:{Lang.断开连接}![{ex.Message}]");
+                    SendTaskMessage($"{item.FeederName}{Lang.断开连接}!", MessageLevel.Alarm);
+                }
+            }
+            if (sb.Length == 0)
+            {
+                return new Tuple<bool, string>(true, "");
+            }
+            else
+            {
+                return new Tuple<bool, string>(false, sb.ToString());
+            }
+        }
+
+        /// <summary>
+        /// 初始化机器人
+        /// </summary>
+        /// <returns></returns>
+        public async Task<Tuple<bool, string>> InitRobots()
+        {
+            RobotService = new RobotService();
+            StringBuilder sb = new StringBuilder();
+            foreach (var item in DeviceConfig.Robots)
+            {
+                RobotService.CreateRobot(item.Id, item);
+                if (item.RobotBrand == RobotBrand.XYZ_Platform || item.RobotBrand == RobotBrand.XYZU_Platform)
+                {
+                    RobotService.GetRobot(item.Id).TrggerChangeEvent += Management_TrggerChangeEvent;
+                    continue;
+                }
+
+                try
+                {
+                    Status.Add(new StatusInfo(item.Id, item.RobotName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
+                    RobotService.GetRobot(item.Id).ReceivedEvent += Management_ReceivedEvent;
+                    RobotService.GetRobot(item.Id).SendEvent += Management_SendEvent;
+                    RobotService.GetRobot(item.Id).ConnectedEvent += Management_ConnectedEvent;
+                    RobotService.GetRobot(item.Id).DisconnectedEvent += Management_DisconnectedEvent;
+                    await RobotService.GetRobot(item.Id).ConnectAsync();     //连接Robot
+                    SendTaskMessage($"{item.RobotName}{Lang.已连接}!", MessageLevel.Debug);
+                }
+                catch (Exception ex)
+                {
+                    sb.AppendLine($"{item.RobotName}:{Lang.断开连接}![{ex.Message}]");
+                    SendTaskMessage($"{item.RobotName}{Lang.断开连接}!", MessageLevel.Alarm);
+                }
+            }
+            if (sb.Length == 0)
+            {
+                return new Tuple<bool, string>(true, "");
+            }
+            else
+            {
+                return new Tuple<bool, string>(false, sb.ToString());
+            }
+        }
+
+
+
+        /// <summary>
+        /// 初始化PLC
+        /// </summary>
+        /// <returns></returns>
+        public async Task<Tuple<bool, string>> InitPlc()
+        {
+            PlcService = new PlcService();
+            StringBuilder sb = new StringBuilder();
+            foreach (var item in DeviceConfig.Plcs)
+            {
+                try
+                {
+                    if (!PlcService.CreatePlc(item.Id, item))
+                    {
+                        sb.AppendLine($"{item.Name}: 不支持的 PLC 通讯类型 [{item.CommunicationType}]");
+                        continue;
+                    }
+
+                    var plc = PlcService.GetPlc(item.Id);
+                    if (plc == null)
+                    {
+                        sb.AppendLine($"{item.Name}: 创建 PLC 失败");
+                        continue;
+                    }
+
+                    Status.Add(new StatusInfo(item.Id, item.Name + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
+                    plc.ConnectChangedEvent += Management_PlcConnectChangedEvent;
+                    await plc.ConnectAsync();
+                }
+                catch (Exception ex)
+                {
+                    sb.AppendLine($"{item.Name}:{Lang.断开连接}![{ex.Message}]");
+                    SendTaskMessage($"{item.Name}{Lang.断开连接}!", MessageLevel.Alarm);
+                }
+            }
+            if (sb.Length == 0)
+            {
+                return new Tuple<bool, string>(true, "");
+            }
+            else
+            {
+                return new Tuple<bool, string>(false, sb.ToString());
+            }
+        }
+
+        /// <summary>
+        /// 初始化相机
+        /// </summary>
+        /// <returns></returns>
+        public Task<Tuple<bool, string>> InitCameras()
+        {
+            CameraService = new CameraService();
+            StringBuilder sb = new StringBuilder();
+            foreach (var item in DeviceConfig.Cameras)
+            {
+
+                try
+                {
+                    Renders.Add(new ShowRender() { Id = item.Id, CameraName = item.CameraName });
+                    CameraService.CreateCamera(item.Id, item);
+                    Status.Add(new StatusInfo(item.Id, item.CameraName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
+                    CameraService.GetCamera(item.Id).CameraConnectChangedEvent += Management_CameraConnectChangedEvent;
+                    if (CameraService.GetCamera(item.Id).OpenDevice())
+                    {
+                        SendTaskMessage($"{item.CameraName}{Lang.已连接}!", MessageLevel.Debug);
+                    }
+                    else
+                    {
+                        SendTaskMessage($"{item.CameraName}{Lang.连接失败}!", MessageLevel.Alarm);
+                        sb.AppendLine($"{item.CameraName}:{Lang.连接失败}!");
+                    }
+                }
+                catch (Exception ex)
+                {
+                    SendTaskMessage($"{item.CameraName}{Lang.连接失败}!", MessageLevel.Alarm);
+                    sb.AppendLine($"{item.CameraName}:{Lang.连接失败}!:{ex.Message}");
+                }
+
+            }
+            _container.Resolve<ShowVisionRenderViewModel>().Renders = Renders;
+
+            if (sb.Length == 0)
+            {
+                return Task.FromResult(new Tuple<bool, string>(true, ""));
+            }
+            else
+            {
+                return Task.FromResult(new Tuple<bool, string>(false, sb.ToString()));
+            }
+        }
+
+        /// <summary>
+        /// 初始化后台TCP服务器通讯
+        /// </summary>
+        public void InitBgTcp()
+        {
+            try
+            {
+
+                BgCommunicate = new BgCommunicate(DeviceConfig.BgCommunicate);
+                BgCommunicate.ConnectedEvent += BgCommunicate_ConnectedEvent;
+                BgCommunicate.DisconnectedEvent += BgCommunicate_DisconnectedEvent;
+                BgCommunicate.ReceivedEvent += BgCommunicate_ReceivedEvent;
+                BgCommunicate.SendEvent += BgCommunicate_SendEvent;
+                BgCommunicate.StartListening();
+                SendTaskMessage($"{Lang.已开启监听端口}:{DeviceConfig.BgCommunicate.Port}", MessageLevel.Debug);
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage($"{Lang.未开启监听端口}:{DeviceConfig.BgCommunicate.Port}", MessageLevel.Error);
+                LogHelper.WriteLogError("开启后台服务器通讯时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 初始化后台ModbusTCP从站
+        /// </summary>
+        public void InitModbusTcp()
+        {
+            try
+            {
+                BgModbusTcpCommunicate = new BgModbusTcpCommunicate(DeviceConfig.BgModbusCommunicate);
+                if (DeviceConfig.BgModbusCommunicate.IsEnabled)
+                {
+                    BgModbusTcpCommunicate.Listen();
+                    SendTaskMessage($"Start Modbus Tcp Slave:{BgModbusTcpCommunicate.IP}:{BgModbusTcpCommunicate.Port}:{BgModbusTcpCommunicate.SlaveID}", MessageLevel.Debug);
+                }
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage($"No Start Modbus Tcp Slave:{ex.Message}", MessageLevel.Alarm);
+                LogHelper.WriteLogError("开启后台Modbus TCP通讯时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 读取 Modbus TCP 主站配置
+        /// </summary>
+        public void ReadModbusTcpMasterDeviceConfig()
+        {
+            try
+            {
+                if (File.Exists(FilePath.ModbusTcpMasterConfigurationPath))
+                {
+                    ModbusTcpMasterConfig = FileHelper.ReadJsonFile<ModbusTcpMasterConfig>(FilePath.ModbusTcpMasterConfigurationPath);
+                }
+                else
+                {
+                    ModbusTcpMasterConfig = new ModbusTcpMasterConfig();
+                }
+            }
+            catch (Exception ex)
+            {
+                ModbusTcpMasterConfig = new ModbusTcpMasterConfig();
+                LogHelper.WriteLogError("加载 Modbus TCP 主站配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存 Modbus TCP 主站配置
+        /// </summary>
+        public void SaveModbusTcpMasterDeviceConfig()
+        {
+            try
+            {
+                FileHelper.WriteJsonFile(ModbusTcpMasterConfig, FilePath.ModbusTcpMasterConfigurationPath);
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("保存 Modbus TCP 主站配置时出错!", ex);
+            }
+        }
+
+
+
+        
+        /// <summary>
+        /// 初始化 Modbus TCP 主站(轮询电批/扭矩控制器)
+        /// </summary>
+        public void InitModbusTcpMaster()
+        {
+            try
+            {
+                ModbusTcpMasterCommunicate?.Stop();
+                ModbusTcpMasterCommunicate = new ModbusTcpMasterCommunicate(ModbusTcpMasterConfig, _eventAggregator);
+                if (!ModbusTcpMasterConfig.IsEnabled)
+                {
+                    return;
+                }
+
+                ModbusTcpMasterCommunicate.Start();
+                SendTaskMessage($"Start Modbus Tcp Master:{ModbusTcpMasterConfig.IP}:{ModbusTcpMasterConfig.Port}:{ModbusTcpMasterConfig.SlaveID}", MessageLevel.Debug);
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage($"No Start Modbus Tcp Master:{ex.Message}", MessageLevel.Alarm);
+                LogHelper.WriteLogError("开启 Modbus TCP 主站通讯时出错!", ex);
+            }
+        }
+
+
+
+        /// <summary>
+        /// 初始化 EthernetIP
+        /// </summary>
+        public void InitEthernetIP()
+        {
+            try
+            {
+                EnsureEthernetIpStatusEntry();
+                DisposeRfidClient();
+                BgEipCommunicate = new SIG350RFIDClient(DeviceConfig.BgEthernetIPCommunicate);
+                BgEipCommunicate.BeforeStartRfidReading = ApplyEthernetIpRfidConfiguration;
+                BgEipCommunicate.OnLog += BgEipCommunicate_OnLog;
+                BgEipCommunicate.OnTagDataReceived += RfidClient_OnTagDataReceived;
+                BgEipCommunicate.OnConnectReceive += Management_EipConnectChangedEvent;
+
+                if (!DeviceConfig.BgEthernetIPCommunicate.IsEnabled)
+                {
+                    UpdateEthernetIpStatus(false);
+                    return;
+                }
+
+                if (BgEipCommunicate.Connect())
+                {
+                    UpdateEthernetIpStatus(true);
+                    SendTaskMessage($"EthernetIP:{DeviceConfig.BgEthernetIPCommunicate.IP}", MessageLevel.Debug);
+                    StartEthernetIpRfidIO();
+                }
+                else
+                {
+                    UpdateEthernetIpStatus(false);
+                    // Connect 失败时会触发 OnConnectReceive(false),内部自动重连
+                }
+            }
+            catch (Exception ex)
+            {
+                UpdateEthernetIpStatus(false);
+                SendTaskMessage($"EthernetIP err:{ex.Message}", MessageLevel.Alarm);
+                LogHelper.WriteLogError("开启 EthernetIP通讯时出错!", ex);
+            }
+        }
+
+        private void EnsureEthernetIpStatusEntry()
+        {
+            if (Status.Any(s => s.ID == EthernetIpStatusId))
+                return;
+
+            App.Current.Dispatcher.Invoke(() =>
+            {
+                if (!Status.Any(s => s.ID == EthernetIpStatusId))
+                {
+                    Status.Add(new StatusInfo(
+                        EthernetIpStatusId,
+                        $"{Lang.EthernetIP}{Lang.未连接}",
+                        new SolidColorBrush(Colors.Red)));
+                }
+            });
+        }
+
+        private void UpdateEthernetIpStatus(bool isConnected)
+        {
+            var sta = Status.FirstOrDefault(s => s.ID == EthernetIpStatusId);
+            if (sta == null)
+                return;
+
+            App.Current.Dispatcher.Invoke(() =>
+            {
+                if (isConnected)
+                {
+                    sta.Message = $"{Lang.EthernetIP}{Lang.已连接}";
+                    sta.Background = new SolidColorBrush(Colors.Green);
+                }
+                else
+                {
+                    sta.Message = $"{Lang.EthernetIP}{Lang.未连接}";
+                    sta.Background = new SolidColorBrush(Colors.Red);
+                }
+            });
+        }
+
+        private void Management_EipConnectChangedEvent(bool isConnected)
+        {
+            if (isConnected)
+            {
+                SendTaskMessage($"{Lang.EthernetIP}{Lang.已连接}!", MessageLevel.Debug);
+                TryStartHandshakeAfterEipReady();
+            }
+            else
+            {
+                SendTaskMessage($"{Lang.EthernetIP}{Lang.断开连接}!", MessageLevel.Error);
+            }
+            UpdateEthernetIpStatus(isConnected);
+        }
+
+        /// <summary>配置 RFID 端口(1..N)并固定为 UID 读模式。</summary>
+        private void ApplyEthernetIpRfidConfiguration()
+        {
+            if (BgEipCommunicate == null || !BgEipCommunicate.IsConnected)
+                return;
+
+            var eipConfig = DeviceConfig.BgEthernetIPCommunicate;
+            var ports = eipConfig.GetEnabledPortNumbers();
+            BgEipCommunicate.ConfigureRFIDPorts(ports, PortMode.IOLAutostart);
+            BgEipCommunicate.ConfigureReadOptions(eipConfig.ToRfh5xxReadOptions());
+            SendTaskMessage($"RFID 已配置端口 1–{eipConfig.RfidPortCount},读 UID", MessageLevel.Debug);
+        }
+
+        private void StartEthernetIpRfidIO()
+        {
+            if (BgEipCommunicate == null || !BgEipCommunicate.IsConnected)
+                return;
+
+            try
+            {
+                ApplyEthernetIpRfidConfiguration();
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage("RFID 端口配置失败: " + ex.Message, MessageLevel.Alarm);
+                LogHelper.WriteLogError("RFID 端口配置失败", ex);
+            }
+
+            BgEipCommunicate.StartRFIDReading(DeviceConfig.BgEthernetIPCommunicate.CycleTime);
+            TryStartHandshakeAfterEipReady();
+        }
+
+        /// <summary>EIP 就绪后尝试启动 Ready 握手;MC 未连接则跳过,由 MC 重连循环补启。</summary>
+        private void TryStartHandshakeAfterEipReady()
+        {
+            var mcPlc = GetMcPlcInfo();
+            if (mcPlc == null)
+                return;
+
+            var client = GetMcPlcClient();
+            if (client == null || !client.IsConnected)
+                return;
+
+            TryStartHandshakeLoop(mcPlc);
+        }
+
+
+        /// <summary>
+        /// 初始化三菱 MC PLC:自动连接、心跳、Ready 握手、SFIS 信号监听
+        /// </summary>
+        public void InitMcCommunicate()
+        {
+            var mcPlc = GetMcPlcInfo();
+            if (mcPlc == null)
+            {
+                SendTaskMessage("未配置三菱 MC PLC,跳过 MC 通讯初始化", MessageLevel.Debug);
+                return;
+            }
+
+            try
+            {
+                StopMcCommunicateLoops();
+
+                var mcWrapper = PlcService?.GetPlc(mcPlc.Id) as MitsubishiMcPLC;
+                if (mcWrapper == null)
+                {
+                    SendTaskMessage("MC PLC 未通过 PlcService 创建,请检查 PLC 配置", MessageLevel.Alarm);
+                    return;
+                }
+
+                var client = mcWrapper.Client;
+                if (_mcPlcLogHandler == null)
+                    _mcPlcLogHandler = msg => SendTaskMessage($"PLC {msg}", MessageLevel.Info);
+                client.OnLog -= _mcPlcLogHandler;
+                client.OnLog += _mcPlcLogHandler;
+                client.ConnectionLost -= McPlcConnectionLost;
+                client.ConnectionLost += McPlcConnectionLost;
+
+                if (!client.IsConnected)
+                {
+                    mcWrapper.Connect();
+                }
+
+                if (!client.IsConnected)
+                {
+                    SendTaskMessage("PLC 连接失败,将自动重连", MessageLevel.Alarm);
+                    StartMcReconnectLoop();
+                    return;
+                }
+
+                SendTaskMessage("PLC TCP 连接成功,正在测试 MC 读写...", MessageLevel.Info);
+                string testDev = string.IsNullOrWhiteSpace(mcPlc.PlcDataStartDevice) ? "D110" : mcPlc.PlcDataStartDevice.Trim();
+                if (testDev == "0")
+                    testDev = "D110";
+
+                if (!client.TestCommunication(testDev))
+                {
+                    SendTaskMessage("MC 通讯测试失败,请检查:二进制3E、端口、允许RUN中写入", MessageLevel.Alarm);
+                }
+                else
+                {
+                    SendTaskMessage("连接成功,MC 字通讯正常", MessageLevel.Info);
+                }
+
+                string bitTestDev = ResolveBitTestDevice(mcPlc);
+                if (bitTestDev != null)
+                {
+                    if (!client.TestBitCommunication(bitTestDev))
+                        SendTaskMessage("MC 位通讯测试失败,请检查 OK/NG 位地址及 RUN 中写入", MessageLevel.Alarm);
+                }
+                else
+                {
+                    SendTaskMessage("MC 位通讯测试跳过:请配置读OK或读NG位地址", MessageLevel.Debug);
+                }
+
+                client.ResetHeartbeatState();
+                EnsureMcCommunicateLoopsRunning(mcPlc, client);
+                StartMcReconnectLoop();
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage("PLC 连接失败: " + ex.Message, MessageLevel.Alarm);
+                LogHelper.WriteLogError("PLC 连接失败", ex);
+                StopMcCommunicateLoops();
+            }
+        }
+
+        private void McPlcConnectionLost()
+        {
+            _mcMonitorLoopsStarted = false;
+            SendTaskMessage("MC PLC 连接中断", MessageLevel.Alarm);
+        }
+
+        /// <summary>MC 连接可用时确保心跳 / SFIS / Ready 握手循环已启动。</summary>
+        private void EnsureMcCommunicateLoopsRunning(PlcInfo mcPlc, MitsubishiPLC client)
+        {
+            if (mcPlc == null || client == null || !client.IsConnected)
+                return;
+
+            client.ResetHeartbeatState();
+            StartHeartbeatLoop(mcPlc);
+            StartSfisSignalLoop();
+            TryStartHandshakeLoop(mcPlc);
+            _mcMonitorLoopsStarted = true;
+        }
+
+        private void TryStartHandshakeLoop(PlcInfo mcPlc)
+        {
+            if (mcPlc == null || !mcPlc.PlcForwardEnabled || !CanStartHandshake(mcPlc))
+                return;
+
+            StartHandshakeLoop();
+        }
+
+        private PlcInfo GetMcPlcInfo()
+        {
+            return DeviceConfig?.Plcs?.FirstOrDefault(p => p.CommunicationType == CommunicationType.Mitsubishi_MC);
+        }
+
+        private MitsubishiPLC GetMcPlcClient()
+        {
+            var mcInfo = GetMcPlcInfo();
+            if (mcInfo == null || PlcService == null)
+                return null;
+
+            return (PlcService.GetPlc(mcInfo.Id) as MitsubishiMcPLC)?.Client;
+        }
+
+        private bool CanStartHandshake(PlcInfo mcPlc)
+        {
+            if (BgEipCommunicate == null || !BgEipCommunicate.IsConnected || !BgEipCommunicate.IsIOModeActive)
+                return false;
+
+            var mapping = mcPlc.ToPlcMapping();
+            return MitsubishiPLC.IsDeviceEnabled(mapping.ReadyBitDevice)
+                && MitsubishiPLC.IsDeviceEnabled(mapping.PortDevice)
+                && MitsubishiPLC.IsDeviceEnabled(mapping.DataStartDevice);
+        }
+
+        private string ResolveBitTestDevice(PlcInfo mcPlc)
+        {
+            if (mcPlc == null) return null;
+            if (MitsubishiPLC.IsDeviceEnabled(mcPlc.PlcOkBitDevice))
+                return mcPlc.PlcOkBitDevice.Trim();
+            if (MitsubishiPLC.IsDeviceEnabled(mcPlc.PlcNgBitDevice))
+                return mcPlc.PlcNgBitDevice.Trim();
+            return null;
+        }
+
+        private void StopMcCommunicateLoops()
+        {
+            try
+            {
+                _mcMonitorLoopsStarted = false;
+                StopMcReconnectLoop();
+                StopHandshakeLoop();
+                StopHeartbeatLoop();
+                StopSfisSignalLoop();
+                ResetSfisWorkflow();
+            }
+            catch { /* ignore */ }
+        }
+
+        private void StartMcReconnectLoop()
+        {
+            StopMcReconnectLoop();
+            _mcReconnectCts = new CancellationTokenSource();
+            var token = _mcReconnectCts.Token;
+            _mcReconnectTask = Task.Run(() => McReconnectLoop(token), token);
+        }
+
+        private void StopMcReconnectLoop()
+        {
+            try
+            {
+                if (_mcReconnectCts != null)
+                {
+                    _mcReconnectCts.Cancel();
+                    try
+                    {
+                        if (_mcReconnectTask != null)
+                            _mcReconnectTask.Wait(2000);
+                    }
+                    catch (AggregateException) { /* ignore */ }
+                    _mcReconnectCts.Dispose();
+                }
+            }
+            catch { /* ignore */ }
+            finally
+            {
+                _mcReconnectCts = null;
+                _mcReconnectTask = null;
+            }
+        }
+
+        private void McReconnectLoop(CancellationToken token)
+        {
+            int attempt = 0;
+
+            while (!token.IsCancellationRequested)
+            {
+                try
+                {
+                    var mcPlc = GetMcPlcInfo();
+                    if (mcPlc == null)
+                    {
+                        Thread.Sleep(1000);
+                        continue;
+                    }
+
+                    var mcWrapper = PlcService?.GetPlc(mcPlc.Id) as MitsubishiMcPLC;
+                    var client = mcWrapper?.Client;
+                    if (client == null)
+                    {
+                        Thread.Sleep(1000);
+                        continue;
+                    }
+
+                    if (client.IsConnected)
+                    {
+                        if (!_mcMonitorLoopsStarted)
+                            EnsureMcCommunicateLoopsRunning(mcPlc, client);
+                        attempt = 0;
+                        Thread.Sleep(500);
+                        continue;
+                    }
+
+                    if ((DateTime.UtcNow - _mcLastReconnectAttempt).TotalMilliseconds < McReconnectIntervalMs)
+                    {
+                        Thread.Sleep(500);
+                        continue;
+                    }
+
+                    _mcLastReconnectAttempt = DateTime.UtcNow;
+                    attempt++;
+                    SendTaskMessage($"MC PLC 连接断开,正在重连(第 {attempt} 次)...", MessageLevel.Info);
+
+                    bool connected;
+                    lock (_mcReconnectSync)
+                    {
+                        if (client.IsConnected)
+                        {
+                            connected = true;
+                        }
+                        else
+                        {
+                            mcWrapper.Connect();
+                            connected = client.IsConnected;
+                        }
+                    }
+
+                    if (connected)
+                    {
+                        EnsureMcCommunicateLoopsRunning(mcPlc, client);
+                        SendTaskMessage("MC PLC 重连成功", MessageLevel.Info);
+                        attempt = 0;
+                    }
+                    else
+                    {
+                        SendTaskMessage("MC PLC 重连失败,将继续重试", MessageLevel.Alarm);
+                    }
+                }
+                catch (Exception ex)
+                {
+                    if (token.IsCancellationRequested)
+                        break;
+
+                    LogHelper.WriteLogError("MC 重连循环异常", ex);
+                    Thread.Sleep(McReconnectIntervalMs);
+                }
+            }
+        }
+
+        private void StartHeartbeatLoop(PlcInfo mcPlc)
+        {
+            StopHeartbeatLoop();
+            if (mcPlc == null) return;
+
+            string device = mcPlc.PlcHeartbeatDevice;
+            if (!MitsubishiPLC.IsDeviceEnabled(device))
+                return;
+
+            PlcHeartbeatKind kind;
+            try
+            {
+                kind = MitsubishiPLC.ResolveHeartbeatKind(device);
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage("PLC 心跳地址无效", MessageLevel.Alarm);
+                LogHelper.WriteLogError("PLC 心跳地址无效", ex);
+                return;
+            }
+
+            if (kind == PlcHeartbeatKind.Disabled)
+                return;
+
+            int intervalMs = Math.Max(200, mcPlc.PlcHeartbeatIntervalMs);
+            _heartbeatCts = new CancellationTokenSource();
+            var token = _heartbeatCts.Token;
+            _heartbeatTask = Task.Run(() => HeartbeatLoop(token, device.Trim(), intervalMs), token);
+
+            SendTaskMessage("PLC 已启动心跳 " + device.Trim()
+                + (kind == PlcHeartbeatKind.Bit ? "(位翻转)" : "(字递增)")
+                + " 间隔=" + intervalMs + "ms", MessageLevel.Info);
+        }
+
+        private void StopHeartbeatLoop()
+        {
+            try
+            {
+                if (_heartbeatCts != null)
+                {
+                    _heartbeatCts.Cancel();
+                    try
+                    {
+                        if (_heartbeatTask != null)
+                            _heartbeatTask.Wait(2000);
+                    }
+                    catch (AggregateException) { /* ignore */ }
+                    _heartbeatCts.Dispose();
+                }
+            }
+            catch { /* ignore */ }
+            finally
+            {
+                _heartbeatCts = null;
+                _heartbeatTask = null;
+            }
+        }
+
+        private void HeartbeatLoop(CancellationToken token, string device, int intervalMs)
+        {
+            while (!token.IsCancellationRequested)
+            {
+                try
+                {
+                    MitsubishiPLC plc;
+                    lock (_sync)
+                        plc = GetMcPlcClient();
+
+                    if (plc == null || !plc.IsConnected)
+                    {
+                        Thread.Sleep(100);
+                        continue;
+                    }
+
+                    plc.PulseHeartbeat(device);
+                }
+                catch (Exception ex)
+                {
+                    if (!token.IsCancellationRequested)
+                    {
+                        SendTaskMessage("心跳异常: " + ex.Message, MessageLevel.Alarm);
+                        LogHelper.WriteLogError("心跳异常", ex);
+                    }
+                }
+
+                Thread.Sleep(intervalMs);
+            }
+        }
+
+        private void StartHandshakeLoop()
+        {
+            StopHandshakeLoop();
+            _handshakeCts = new CancellationTokenSource();
+            var token = _handshakeCts.Token;
+            _handshakeTask = Task.Run(() => HandshakeLoop(token), token);
+            SendTaskMessage("已启动 Ready 握手循环", MessageLevel.Info);
+        }
+
+        private void HandshakeLoop(CancellationToken token)
+        {
+            bool lastReady = false;
+
+            while (!token.IsCancellationRequested)
+            {
+                try
+                {
+                    MitsubishiPLC plc;
+                    SIG350RFIDClient rfid;
+                    lock (_sync)
+                    {
+                        plc = GetMcPlcClient();
+                        rfid = BgEipCommunicate;
+                    }
+
+                    if (plc == null || !plc.IsConnected || rfid == null || !rfid.IsConnected || !rfid.IsIOModeActive)
+                    {
+                        Thread.Sleep(50);
+                        continue;
+                    }
+
+                    PlcRfidMapping mapping = SnapshotMapping();
+                    if (!MitsubishiPLC.IsDeviceEnabled(mapping.ReadyBitDevice))
+                    {
+                        Thread.Sleep(100);
+                        continue;
+                    }
+
+                    bool ready = plc.ReadReadyBit(mapping);
+                    if (ready && !lastReady)
+                    {
+                        SendTaskMessage("PLC 检测到 Ready=ON,开始读卡", MessageLevel.Info);
+                        ProcessReadyRequest(plc, rfid, mapping, token);
+
+                        while (!token.IsCancellationRequested)
+                        {
+                            if (!plc.IsConnected)
+                                break;
+                            if (!plc.ReadReadyBit(mapping))
+                                break;
+                            Thread.Sleep(20);
+                        }
+
+                        if (!token.IsCancellationRequested && plc.IsConnected)
+                        {
+                            plc.ClearReceiveBit(mapping);
+                            SendTaskMessage("PLC Ready=OFF,已清除 Receive", MessageLevel.Info);
+                        }
+
+                        lastReady = false;
+                        continue;
+                    }
+
+                    lastReady = ready;
+                    Thread.Sleep(20);
+                }
+                catch (Exception ex)
+                {
+                    if (token.IsCancellationRequested)
+                        break;
+                    SendTaskMessage("PLC 握手异常", MessageLevel.Alarm);
+                    LogHelper.WriteLogError("PLC 握手异常", ex);
+                    Thread.Sleep(100);
+                    lastReady = false;
+                }
+            }
+        }
+
+        private PlcRfidMapping SnapshotMapping()
+        {
+            lock (_sync)
+            {
+                var mcPlc = GetMcPlcInfo();
+                return mcPlc?.ToPlcMapping() ?? new PlcRfidMapping();
+            }
+        }
+
+        private void ProcessReadyRequest(MitsubishiPLC plc, SIG350RFIDClient rfid, PlcRfidMapping mapping, CancellationToken token)
+        {
+            int port;
+            try
+            {
+                port = plc.ReadRequestPort(mapping);
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage("PLC 读端口号失败", MessageLevel.Alarm);
+                LogHelper.WriteLogError("PLC 读端口号失败", ex);
+                try { plc.WriteReadFailure(mapping); } catch { /* ignore */ }
+                return;
+            }
+
+            SendTaskMessage("PLC 请求端口 " + port, MessageLevel.Info);
+
+            if (port < 1 || port > 8)
+            {
+                SendTaskMessage("端口号无效: " + port, MessageLevel.Alarm);
+                try { plc.WriteReadFailure(mapping); } catch { /* ignore */ }
+                return;
+            }
+
+            if (token.IsCancellationRequested)
+                return;
+
+            RFIDTagData tag = null;
+            try
+            {
+                int timeout = mapping.ReadTimeoutMs > 0 ? mapping.ReadTimeoutMs : 2000;
+                var readOpts = DeviceConfig.BgEthernetIPCommunicate.ToRfh5xxReadOptions();
+                tag = rfid.ReadRFIDTag(port, timeout, readOpts);
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage("RFID 读卡异常", MessageLevel.Alarm);
+                LogHelper.WriteLogError("RFID 读卡异常", ex);
+            }
+
+            if (tag != null && tag.Data != null && tag.Data.Length > 0)
+            {
+                lock (_sync)
+                    _lastRfidTag = CloneTag(tag);
+
+                try
+                {
+                    plc.WriteReadSuccess(mapping, tag);
+                }
+                catch (Exception ex)
+                {
+                    SendTaskMessage("RFID 写 OK/数据失败", MessageLevel.Alarm);
+                    LogHelper.WriteLogError("RFID 写 OK/数据失败", ex);
+                }
+            }
+            else
+            {
+                SendTaskMessage("RFID 端口 " + port + " 未读到标签", MessageLevel.Alarm);
+                try { plc.WriteReadFailure(mapping); }
+                catch (Exception ex)
+                {
+                    SendTaskMessage("RFID 写 NG 失败", MessageLevel.Alarm);
+                    LogHelper.WriteLogError("RFID 写 NG 失败", ex);
+                }
+            }
+        }
+
+        private bool SnapshotSfisEnabled()
+        {
+            lock (_sync)
+                return DeviceConfig.BgSfisCommunicate?.IsEnabled == true;
+        }
+
+        private SfisConfig SnapshotSfisConfig()
+        {
+            lock (_sync)
+                return DeviceConfig.BgSfisCommunicate?.ToSfisConfig() ?? new SfisConfig();
+        }
+
+        private PlcSfisFeedback SnapshotSfisPlcFeedback()
+        {
+            lock (_sync)
+                return DeviceConfig.BgSfisCommunicate?.ToPlcSfisFeedback() ?? new PlcSfisFeedback();
+        }
+
+        private SfisWorkflowService CreateSfisWorkflow()
+        {
+            var workflow = new SfisWorkflowService(SnapshotSfisConfig());
+            workflow.OnLog += msg => SendTaskMessage("SFIS " + msg, MessageLevel.Info);
+            return workflow;
+        }
+
+        private SfisWorkflowService GetOrCreateSfisWorkflow()
+        {
+            lock (_sync)
+            {
+                if (_sfisWorkflow != null)
+                    return _sfisWorkflow;
+            }
+
+            var workflow = CreateSfisWorkflow();
+            lock (_sync)
+            {
+                if (_sfisWorkflow == null)
+                    _sfisWorkflow = workflow;
+                else
+                {
+                    try { workflow.Dispose(); }
+                    catch { /* ignore */ }
+                }
+                return _sfisWorkflow;
+            }
+        }
+
+        private void ResetSfisWorkflow()
+        {
+            lock (_sync)
+            {
+                if (_sfisWorkflow != null)
+                {
+                    try { _sfisWorkflow.Dispose(); }
+                    catch { /* ignore */ }
+                    _sfisWorkflow = null;
+                }
+            }
+        }
+
+        private void StartSfisSignalLoop()
+        {
+            StopSfisSignalLoop();
+            var sfis = DeviceConfig.BgSfisCommunicate;
+            if (sfis == null || !sfis.IsEnabled)
+                return;
+
+            bool passReady = sfis.PassEnabled && MitsubishiPLC.IsDeviceEnabled(sfis.PlcSfisPassSignalDevice);
+            bool uploadReady = sfis.UploadEnabled && MitsubishiPLC.IsDeviceEnabled(sfis.PlcSfisUploadSignalDevice);
+            if (!passReady && !uploadReady)
+                return;
+
+            _sfisSignalCts = new CancellationTokenSource();
+            var token = _sfisSignalCts.Token;
+            _sfisSignalTask = Task.Run(() => SfisSignalLoop(token), token);
+            SendTaskMessage("SFIS 已启动信号监听"
+                + (passReady ? " 过站=" + sfis.PlcSfisPassSignalDevice.Trim() : string.Empty)
+                + (uploadReady ? " 上传=" + sfis.PlcSfisUploadSignalDevice.Trim() : string.Empty), MessageLevel.Info);
+        }
+
+        private void StopSfisSignalLoop()
+        {
+            try
+            {
+                if (_sfisSignalCts != null)
+                {
+                    _sfisSignalCts.Cancel();
+                    try
+                    {
+                        if (_sfisSignalTask != null)
+                            _sfisSignalTask.Wait(2000);
+                    }
+                    catch (AggregateException) { /* ignore */ }
+                    _sfisSignalCts.Dispose();
+                }
+            }
+            catch { /* ignore */ }
+            finally
+            {
+                _sfisSignalCts = null;
+                _sfisSignalTask = null;
+            }
+        }
+
+        private void SfisSignalLoop(CancellationToken token)
+        {
+            bool lastPass = false;
+            bool lastUpload = false;
+
+            while (!token.IsCancellationRequested)
+            {
+                try
+                {
+                    if (!SnapshotSfisEnabled())
+                    {
+                        lastPass = false;
+                        lastUpload = false;
+                        Thread.Sleep(200);
+                        continue;
+                    }
+
+                    MitsubishiPLC plc;
+                    lock (_sync)
+                        plc = GetMcPlcClient();
+
+                    if (plc == null || !plc.IsConnected)
+                    {
+                        Thread.Sleep(100);
+                        continue;
+                    }
+
+                    var sfis = DeviceConfig.BgSfisCommunicate;
+                    bool passEnabled = sfis.PassEnabled;
+                    bool uploadEnabled = sfis.UploadEnabled;
+                    string passDev = sfis.PlcSfisPassSignalDevice;
+                    string uploadDev = sfis.PlcSfisUploadSignalDevice;
+
+                    bool passOn = passEnabled && MitsubishiPLC.IsDeviceEnabled(passDev) && plc.ReadBit(passDev);
+                    bool uploadOn = uploadEnabled && MitsubishiPLC.IsDeviceEnabled(uploadDev) && plc.ReadBit(uploadDev);
+
+                    if (passEnabled && passOn && !lastPass)
+                    {
+                        SendTaskMessage("SFIS 过站信号上升沿 " + passDev.Trim(), MessageLevel.Info);
+                        RunSfisOnSignal(plc, runPass: true, runUpload: false);
+                    }
+                    else if (passEnabled && !passOn && lastPass)
+                    {
+                        try
+                        {
+                            plc.ClearSfisReceiveBit(SnapshotSfisPlcFeedback(), isPassStation: true);
+                            SendTaskMessage("过站信号 OFF,已清除 Receive", MessageLevel.Info);
+                        }
+                        catch (Exception ex)
+                        {
+                            SendTaskMessage("清除过站 Receive 失败: " + ex.Message, MessageLevel.Alarm);
+                        }
+                    }
+
+                    if (uploadEnabled && uploadOn && !lastUpload)
+                    {
+                        SendTaskMessage("SFIS 上传信号上升沿 " + uploadDev.Trim(), MessageLevel.Info);
+                        RunSfisOnSignal(plc, runPass: false, runUpload: true);
+                    }
+                    else if (uploadEnabled && !uploadOn && lastUpload)
+                    {
+                        try
+                        {
+                            plc.ClearSfisReceiveBit(SnapshotSfisPlcFeedback(), isPassStation: false);
+                            SendTaskMessage("上传信号 OFF,已清除 Receive", MessageLevel.Info);
+                        }
+                        catch (Exception ex)
+                        {
+                            SendTaskMessage("清除上传 Receive 失败: " + ex.Message, MessageLevel.Alarm);
+                        }
+                    }
+
+                    lastPass = passOn;
+                    lastUpload = uploadOn;
+                    Thread.Sleep(50);
+                }
+                catch (Exception ex)
+                {
+                    if (token.IsCancellationRequested)
+                        break;
+                    SendTaskMessage("SFIS 信号监听异常: " + ex.Message, MessageLevel.Alarm);
+                    Thread.Sleep(200);
+                    lastPass = false;
+                    lastUpload = false;
+                }
+            }
+        }
+
+        private struct SfisRunPlan
+        {
+            public bool RunPass;
+            public bool RunUpload;
+        }
+
+        private void RunSfisOnSignal(MitsubishiPLC plc, bool runPass, bool runUpload)
+        {
+            bool isPassStation = runPass;
+            PlcSfisFeedback feedback = SnapshotSfisPlcFeedback();
+            bool success = false;
+
+            try
+            {
+                RFIDTagData tag = TryLoadTagForSfis(plc);
+                if (tag == null)
+                {
+                    SendTaskMessage("SFIS 无可用 RFID 数据,写 PLC NG", MessageLevel.Alarm);
+                    WriteSfisPlcResult(plc, feedback, isPassStation, false);
+                    return;
+                }
+
+                success = TryRunSfisWorkflow(tag, new SfisRunPlan { RunPass = runPass, RunUpload = runUpload });
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage("SFIS 流程异常: " + ex.Message, MessageLevel.Alarm);
+                success = false;
+            }
+
+            WriteSfisPlcResult(plc, feedback, isPassStation, success);
+        }
+
+        private void WriteSfisPlcResult(MitsubishiPLC plc, PlcSfisFeedback feedback, bool isPassStation, bool success)
+        {
+            try
+            {
+                plc.WriteSfisResult(feedback, isPassStation, success);
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage((isPassStation ? "过站" : "上传") + " 回写失败: " + ex.Message, MessageLevel.Alarm);
+            }
+        }
+
+        private RFIDTagData TryLoadTagForSfis(MitsubishiPLC plc)
+        {
+            PlcRfidMapping mapping = SnapshotMapping();
+            var readOpts = DeviceConfig.BgEthernetIPCommunicate.ToRfh5xxReadOptions();
+
+            if (MitsubishiPLC.IsDeviceEnabled(mapping.DataStartDevice))
+            {
+                try
+                {
+                    byte[] data = plc.ReadDeviceBytes(mapping.DataStartDevice, mapping.MaxDataBytes);
+                    data = TrimTrailingZeros(data);
+                    if (data.Length > 0)
+                    {
+                        int port = 0;
+                        if (MitsubishiPLC.IsDeviceEnabled(mapping.PortDevice))
+                            port = plc.ReadRequestPort(mapping);
+
+                        return new RFIDTagData
+                        {
+                            Port = port,
+                            Data = data,
+                            Timestamp = DateTime.Now,
+                            PayloadKind = readOpts.Kind
+                        };
+                    }
+                }
+                catch (Exception ex)
+                {
+                    SendTaskMessage("SFIS 从 PLC 读取 RFID 数据失败: " + ex.Message, MessageLevel.Alarm);
+                }
+            }
+
+            lock (_sync)
+            {
+                if (_lastRfidTag != null && _lastRfidTag.Data != null && _lastRfidTag.Data.Length > 0)
+                    return CloneTag(_lastRfidTag);
+            }
+
+            return null;
+        }
+
+        private static RFIDTagData CloneTag(RFIDTagData tag)
+        {
+            return new RFIDTagData
+            {
+                Port = tag.Port,
+                Data = (byte[])tag.Data.Clone(),
+                Timestamp = tag.Timestamp,
+                Quality = tag.Quality,
+                PayloadKind = tag.PayloadKind
+            };
+        }
+
+        private static byte[] TrimTrailingZeros(byte[] data)
+        {
+            if (data == null || data.Length == 0)
+                return new byte[0];
+
+            int len = data.Length;
+            while (len > 0 && data[len - 1] == 0)
+                len--;
+
+            if (len == data.Length)
+                return data;
+
+            var trimmed = new byte[len];
+            Array.Copy(data, trimmed, len);
+            return trimmed;
+        }
+
+        private bool TryRunSfisWorkflow(RFIDTagData tag, SfisRunPlan plan)
+        {
+            try
+            {
+                var config = SnapshotSfisConfig();
+                var context = SfisRfidMapper.FromRfidTag(tag, config);
+                var result = GetOrCreateSfisWorkflow().ProcessUnit(context, plan.RunPass, plan.RunUpload);
+                PrintSfisResult(result);
+                return result.Success;
+            }
+            catch (ArgumentException ex)
+            {
+                SendTaskMessage("SFIS 数据无效: " + ex.Message, MessageLevel.Alarm);
+                return false;
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage("SFIS 流程异常: " + ex.Message, MessageLevel.Alarm);
+                return false;
+            }
+        }
+
+        private void PrintSfisResult(SfisWorkflowResult result)
+        {
+            if (result == null)
+                return;
+
+            SendTaskMessage(result.Success
+                ? "SFIS 流程成功 ISN=" + result.Isn
+                : "SFIS 流程失败 ISN=" + result.Isn + " => " + result.ErrorMessage, MessageLevel.Info);
+
+            if (result.Steps == null)
+                return;
+
+            foreach (var step in result.Steps)
+            {
+                string msg = step.Response != null ? step.Response.Message : string.Empty;
+                int code = step.Response != null ? step.Response.ReturnCode : -1;
+                SendTaskMessage("SFIS   " + step.StepName + ": P_RET=" + code + " " + msg, MessageLevel.Debug);
+            }
+        }
+
+        private void BgEipCommunicate_OnLog(string obj)
+        {
+            SendTaskMessage(obj, MessageLevel.Info);
+        }
+
+
+        /// <summary>
+        /// 初始化后台脚本
+        /// </summary>
+        public void InitBackgroundcript()
+        {
+            try
+            {
+                if (!Directory.Exists(FilePath.BackgroundScriptPath))
+                {
+                    Directory.CreateDirectory(FilePath.BackgroundScriptPath);
+                }
+
+                try
+                {
+                    string[] files = Directory.GetFiles(FilePath.BackgroundScriptPath);
+                    List<string> ScriptFilesCollection = new List<string>();
+                    foreach (string file in files)
+                    {
+                        string fileName = Path.GetFileName(file);
+                        string fileExtension = Path.GetExtension(file);
+                        if (fileExtension == ".cs")
+                        {
+                            ScriptFilesCollection.Add(file);
+                        }
+                    }
+                    foreach (var item in ScriptFilesCollection)
+                    {
+                        try
+                        {
+                            string script = FileHelper.ReadFile(item);
+                            SendTaskMessage($"{Lang.执行脚本}:{item}", MessageLevel.Info);
+                            Task.Factory.StartNew(() =>
+                            {
+                                ScriptHelper.ExecuteScriptingAsync(script, _regionManager, _eventAggregator, _container, rst =>
+                            {
+                                if (!rst.Item1)
+                                {
+                                    foreach (var err in rst.Item2)
+                                    {
+                                        SendTaskMessage($"{Lang.后台脚本出错}:{err}", MessageLevel.Error);
+                                    }
+                                }
+                            });
+                            });
+                        }
+                        catch (Exception ex)
+                        {
+                            LogHelper.WriteLogError($"开启脚本时出错:{item}", ex);
+                        }
+                    }
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("读取本地脚本文件列表时出错", ex);
+                }
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("开启后台脚本时出错!", ex);
+            }
+        }
+        #endregion
+
+        #region 产品操作
+        /// <summary>
+        /// 加载所有产品
+        /// </summary>
+        public void LoadAllProducts()
+        {
+            Products = new ObservableCollection<ProductModel>();
+            try
+            {
+                if (File.Exists(FilePath.ProductsPath + "//ProductList.cfg"))
+                {
+                    Dictionary<Guid, string> list = FileHelper.ReadJsonFile<Dictionary<Guid, string>>(FilePath.ProductsPath + "//ProductList.cfg");
+                    foreach (var item in list)
+                    {
+                        Products.Add(FileHelper.ReadJsonFile<ProductModel>(FilePath.ProductsPath + "//" + item.Value + "//" + item.Value + ".cfg"));
+                        //for (int i = 0; i < Products[Products.Count - 1].CameraProcedures.Count; i++)
+                        //{
+                        //    for (int j = 0; j < Products[Products.Count - 1].CameraProcedures[i].ProcedureModels.Count; j++)
+                        //    {
+                        //        string prcPath = FilePath.ProductsPath + "//" + item.Value + "//" + Products[Products.Count - 1].CameraProcedures[i].Camera + "//" + Products[Products.Count - 1].CameraProcedures[i].ProcedureModels[j].Name + ".prc";
+                        //        Products[Products.Count - 1].CameraProcedures[i].ProcedureModels[j].Procedure = VmProcedure.Load(prcPath);
+                        //    }
+                        //}
+                    }
+                    SendTaskMessage($"{Lang.所有产品加载完成}!", MessageLevel.Debug);
+                }
+                else
+                {
+                    SendTaskMessage($"{Lang.无产品}!", MessageLevel.Alarm);
+                }
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage(ex.Message, MessageLevel.Error);
+                LogHelper.WriteLogError("加载所有产品时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 加载产品
+        /// </summary>
+        public void LoadProducts(ProductModel product)
+        {
+            var prd = Products.FirstOrDefault(x => x.ID == product.ID);
+            if (prd == null)
+            {
+                return;
+            }
+            try
+            {
+                //清除上一个产品的相机拍照数据
+                feederCurentBlobArea = new Dictionary<Guid, Dictionary<Guid, double>>();
+                LastPointsForFeeder = new Dictionary<Guid, List<Vector<double>>>();
+                PointCollection = new Dictionary<Guid, Dictionary<string, Queue<string>>>();
+
+                for (int i = 0; i < prd.CameraProcedures.Count; i++)
+                {
+                    for (int j = 0; j < prd.CameraProcedures[i].ProcedureModels.Count; j++)
+                    {
+                        string prcPath = FilePath.ProductsPath + "//" + prd.Name + "//" + prd.CameraProcedures[i].Camera + "//" + prd.CameraProcedures[i].ProcedureModels[j].Name + ".vpp";
+                        prd.CameraProcedures[i].ProcedureModels[j].ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                    }
+                }
+
+                //设置Feeder的光源亮度及Feeder的振动参数
+
+                prd.IsLoad = true;
+                foreach (var item in Products)
+                {
+                    if (item.ID != prd.ID)
+                    {
+                        item.IsLoad = false;
+                    }
+                }
+                CurrentProduct = prd;
+
+                Dictionary<Guid, List<NodeId>> keyValuePairs = new Dictionary<Guid, List<NodeId>>();
+                Dictionary<Guid, ObservableCollection<ProcedureOutputOpcAdr>> keyValuePairsT = new Dictionary<Guid, ObservableCollection<ProcedureOutputOpcAdr>>();
+                foreach (var item in prd.CameraProcedures)
+                {
+                    foreach (var itemT in item.ProcedureModels)
+                    {
+                        IRobot robot = RobotService.GetRobot(itemT.RobotId);
+                        if (robot != null && robot.Brand == RobotBrand.XYZ_Platform)
+                        {
+                            if (keyValuePairs.ContainsKey(itemT.Id))
+                            {
+                                keyValuePairs[itemT.Id].Add(itemT.TriggerCommand);
+                            }
+                            else
+                            {
+                                keyValuePairs.Add(itemT.Id, new List<NodeId> { itemT.TriggerCommand });
+                            }
+                            if (!keyValuePairsT.ContainsKey(itemT.Id))
+                            {
+                                keyValuePairsT.Add(itemT.Id, itemT.ProcedureOutputsOpcAdrs);
+                            }
+
+                        }
+                    }
+                }
+
+                Guid[] Threadkeys = PlcTrigger.Keys.ToArray();
+                Thread[] ThreadValues = PlcTrigger.Values.ToArray();
+                for (int i = 0; i < PlcTrigger.Count; i++)
+                {
+                    var procedure = prd.CameraProcedures.FirstOrDefault(p => p.ProcedureModels?.FirstOrDefault(f => f.Id == Threadkeys[i]) != null);
+                    Guid guid = procedure.ProcedureModels.FirstOrDefault(f => f.Id == Threadkeys[i]).RobotId;
+                    XYZ_Platform robot = RobotService.GetRobot(guid) as XYZ_Platform;
+                    robot.IsTrigger = false;
+                    ThreadValues[i].Abort();
+                }
+                PlcTrigger.Clear();
+                Guid[] keys = keyValuePairs.Keys.ToArray();
+                List<NodeId>[] values = keyValuePairs.Values.ToArray();
+
+                for (int i = 0; i < keyValuePairs?.Count; i++)
+                {
+
+                    var procedure = prd.CameraProcedures.FirstOrDefault(p =>
+                                                             p.ProcedureModels?.FirstOrDefault(f => f.Id == keys[i]) != null);
+                    Guid guid = procedure.ProcedureModels.FirstOrDefault(f => f.Id == keys[i]).RobotId;
+                    XYZ_Platform robot = RobotService.GetRobot(guid) as XYZ_Platform;
+                    robot.IsTrigger = false;
+                    if (keyValuePairsT.ContainsKey(keys[i]))
+                    {
+                        List<ProcedureOutputOpcAdr> ProcedureOutputOpcAdrs = new List<ProcedureOutputOpcAdr>();
+                        var saas = keyValuePairsT[keys[i]];
+                        for (int j = 0; j < keyValuePairsT[keys[i]]?.Count; j++)
+                        {
+                            ProcedureOutputOpcAdrs.Add(keyValuePairsT[keys[i]][j]);
+                        }
+                        robot.IsTrigger = true;
+                        Thread thread = robot.CreateThreadToTrigger(values[i].ToArray(), ProcedureOutputOpcAdrs);
+                        PlcTrigger.Add(keys[i], thread);
+                    }
+                }
+                DatabaseHelper.UpdateProductDatabase(product);
+
+                SendTaskMessage(Lang.产品加载完成.Replace("{0}", CurrentProduct.Name), MessageLevel.Debug);
+                App.Current.Dispatcher.Invoke(() =>
+                {
+                    _eventAggregator.GetEvent<ProductChangedNotification>().Publish(CurrentProduct);
+                    _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.产品加载完成.Replace("{0}", CurrentProduct.Name), Duration = 1 });
+                });
+
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage(ex.Message, MessageLevel.Error);
+                LogHelper.WriteLogError($"加载产品[{prd.Name}]时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存产品
+        /// </summary>
+        /// <param name="product"></param>
+        public void SaveProducts(ProductModel product)
+        {
+            try
+            {
+                product.DateTime = DateTime.Now;
+                var prod = Products.FirstOrDefault(item => item.ID == product.ID);
+                if (prod != null)
+                {
+                    prod = product;
+                }
+                else
+                {
+                    product.IsCreate = false;
+                    Products.Add(product);
+                }
+
+                Dictionary<Guid, string> list = new Dictionary<Guid, string>();
+                foreach (var item in Products)
+                {
+                    list.Add(item.ID, item.Name);
+                }
+                FileHelper.WriteJsonFile(list, FilePath.ProductsPath + "//ProductList.cfg");
+                FileHelper.WriteJsonFile(product, FilePath.ProductsPath + "//" + product.Name + "//" + product.Name + ".cfg");
+                foreach (var item in product.CameraProcedures)
+                {
+                    foreach (var item1 in item.ProcedureModels)
+                    {
+                        string prcPath = FilePath.ProductsPath + "//" + product.Name + "//" + item.Camera + "//" + item1.Name + ".vpp";
+                        if (!Directory.Exists(Path.GetDirectoryName(prcPath)))
+                        {
+                            Directory.CreateDirectory(Path.GetDirectoryName(prcPath));
+                        }
+                        if (item1.ToolBlock != null)
+                        {
+                            CogSerializer.SaveObjectToFile(item1.ToolBlock, prcPath);
+                            //item1.ToolBlock= CogSerializer.LoadObjectFromFile(FilePath.SimpleProcedurePath) as CogToolBlock;
+                        }
+                        else
+                        {
+                            if (File.Exists(prcPath))
+                            {
+                                item1.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                            }
+                            else
+                            {
+                                item1.ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.SimpleProcedurePath) as CogToolBlock;
+                            }
+                        }
+                    }
+                }
+
+                DatabaseHelper.UpdateProductDatabase(product);
+
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.保存完成, Duration = 1 });
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage(ex.Message, MessageLevel.Error);
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
+                LogHelper.WriteLogError("保存产品时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存产品
+        /// </summary>
+        public void SaveProducts()
+        {
+            Dictionary<Guid, string> list = new Dictionary<Guid, string>();
+            foreach (var item in Products)
+            {
+                list.Add(item.ID, item.Name);
+            }
+            FileHelper.WriteJsonFile(list, FilePath.ProductsPath + "//ProductList.cfg");
+            _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.保存完成, Duration = 1 });
+        }
+
+        /// <summary>
+        /// 保存产品模板
+        /// </summary>
+        /// <param name="product"></param>
+        public void SaveProductTemplate(ProductModel product)
+        {
+            try
+            {
+                product.DateTime = DateTime.Now;
+                var prod = Products.FirstOrDefault(item => item.ID == product.ID);
+                if (prod != null)
+                {
+                    prod = product;
+                }
+                else
+                {
+                    product.IsCreate = false;
+                }
+
+
+                FileHelper.WriteJsonFile(product, FilePath.ProductTemplatePath + "//" + product.Name + "//" + product.Name + ".cfg");
+                foreach (var item in product.CameraProcedures)
+                {
+                    foreach (var item1 in item.ProcedureModels)
+                    {
+                        string prcPath = FilePath.ProductTemplatePath + "//" + product.Name + "//" + item.Camera + "//" + item1.Name + ".vpp";
+                        if (!Directory.Exists(Path.GetDirectoryName(prcPath)))
+                        {
+                            Directory.CreateDirectory(Path.GetDirectoryName(prcPath));
+                        }
+                        if (item1.ToolBlock != null)
+                        {
+                            CogSerializer.SaveObjectToFile(item1.ToolBlock, prcPath);
+                            //item1.ToolBlock= CogSerializer.LoadObjectFromFile(FilePath.SimpleProcedurePath) as CogToolBlock;
+                        }
+                        else
+                        {
+                            if (File.Exists(prcPath))
+                            {
+                                item1.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                            }
+                            else
+                            {
+                                item1.ToolBlock = CogSerializer.LoadObjectFromFile(FilePath.SimpleProcedurePath) as CogToolBlock;
+                            }
+                        }
+                    }
+                }
+
+                DatabaseHelper.UpdateProductDatabase(product);
+
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.保存完成, Duration = 1 });
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage(ex.Message, MessageLevel.Error);
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
+                LogHelper.WriteLogError("保存产品模板时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 复制产品
+        /// </summary>
+        /// <param name="product"></param>
+        /// <param name="newName"></param>
+        public ProductModel CopyProduct(ProductModel product, string newName)
+        {
+            var p = product.Clone();
+            p.Name = newName;
+            p.ID = Guid.NewGuid();
+            p.DateTime = DateTime.Now;
+            for (int i = 0; i < p.CameraProcedures.Count; i++)
+            {
+                for (int j = 0; j < p.CameraProcedures[i].ProcedureModels.Count; j++)
+                {
+                    string sorPath = FilePath.ProductsPath + "//" + ((ProductModel)product).Name + "//" + p.CameraProcedures[i].Camera + "//" + ((ProductModel)product).CameraProcedures[i].ProcedureModels[j].Name + ".vpp";
+                    string procname = p.CameraProcedures[i].ProcedureModels[j].Name.Split('-')[2];
+                    procname = $"{p.Name}-{p.CameraProcedures[i].Camera}-{procname}";
+                    p.CameraProcedures[i].ProcedureModels[j].Name = procname;
+                    string prcPath = FilePath.ProductsPath + "//" + p.Name + "//" + p.CameraProcedures[i].Camera + "//" + p.CameraProcedures[i].ProcedureModels[j].Name + ".vpp";
+                    if (!Directory.Exists(Path.GetDirectoryName(prcPath)))
+                    {
+                        Directory.CreateDirectory(Path.GetDirectoryName(prcPath));
+                    }
+
+                    if (File.Exists(sorPath))
+                    {
+                        File.Copy(sorPath, prcPath, true);
+                        if (p.CameraProcedures[i].ProcedureModels[j].ToolBlock == null)
+                        {
+                            p.CameraProcedures[i].ProcedureModels[j].ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock;
+                        }
+                    }
+                }
+            }
+            Products.Add(p);
+            SaveProducts(p);
+            return p;
+        }
+
+        /// <summary>
+        /// 重新命名产品
+        /// </summary>
+        /// <param name="product"></param>
+        /// <param name="newName"></param>
+        public void RenameProduct(ProductModel product, string newName)
+        {
+            string oldname = product.Name;
+
+            //更改产品名称
+            product.Name = newName;
+
+            //遍历所有的相机流程,更改相机流程的名称
+            for (int i = 0; i < product.CameraProcedures.Count; i++)
+            {
+                for (int j = 0; j < product.CameraProcedures[i].ProcedureModels.Count; j++)
+                {
+                    //旧路径
+                    string sorPath = FilePath.ProductsPath + "//" + oldname + "//" + product.CameraProcedures[0].Camera + "//" + product.CameraProcedures[i].ProcedureModels[j].Name + ".vpp";
+                    string procname = product.CameraProcedures[i].ProcedureModels[j].Name.Split('-')[2];
+                    procname = $"{product.Name}-{product.CameraProcedures[i].Camera}-{procname}";
+                    product.CameraProcedures[i].ProcedureModels[j].Name = procname;
+                    //新路径
+                    string prcPath = FilePath.ProductsPath + "//" + product.Name + "//" + product.CameraProcedures[0].Camera + "//" + product.CameraProcedures[i].ProcedureModels[j].Name + ".vpp";
+                    if (!Directory.Exists(Path.GetDirectoryName(prcPath)))
+                    {
+                        Directory.CreateDirectory(Path.GetDirectoryName(prcPath));
+                    }
+                    if (File.Exists(sorPath))
+                    {
+                        File.Copy(sorPath, prcPath, true);
+                        File.Delete(sorPath);
+                    }
+                }
+                string prcPath1 = FilePath.ProductsPath + "//" + oldname + "//" + product.CameraProcedures[0].Camera;
+                if (Directory.Exists(prcPath1))
+                {
+                    Directory.Delete(prcPath1);
+                }
+            }
+
+            //更改产品数据库
+            string src = FilePath.ProductsPath + "//" + oldname + "//" + oldname + ".db";
+            string dsc = FilePath.ProductsPath + "//" + product.Name + "//" + product.Name + ".db";
+            if (File.Exists(src))
+            {
+                File.Copy(src, dsc, true);
+                File.Delete(src);
+            }
+            //更改数据库中有关的产品名称
+            DatabaseHelper.RevampProductName(product, oldname);
+
+            SaveProducts(product);
+
+            //删除旧产品路径
+            string sorPath1 = FilePath.ProductsPath + "//" + oldname + "//" + oldname + ".cfg";
+            if (File.Exists(sorPath1))
+            {
+                File.Delete(sorPath1);
+            }
+            sorPath1 = FilePath.ProductsPath + "//" + oldname;
+            if (Directory.Exists(sorPath1))
+            {
+                Directory.Delete(sorPath1);
+            }
+        }
+
+        /// <summary>
+        /// 移除产品
+        /// </summary>
+        /// <param name="product"></param>
+        public void RemoveProduct(ProductModel product)
+        {
+            var prod = Products.FirstOrDefault(p => p.ID == product.ID);
+            if (prod != null)
+            {
+                Products.Remove(prod);
+                SaveProducts();
+            }
+        }
+
+        #endregion
+
+        #region 相机校准操作
+        /// <summary>
+        /// 加载所有校准
+        /// </summary>
+        public void LoadAllCalibration()
+        {
+            try
+            {
+                if (File.Exists(FilePath.CalibrationPath + "//CalibrationList.cfg"))
+                {
+                    DeviceConfig.Calibrations = new ObservableCollection<CalibrationInfo>();
+                    Dictionary<Guid, string> list = FileHelper.ReadJsonFile<Dictionary<Guid, string>>(FilePath.CalibrationPath + "//CalibrationList.cfg");
+                    foreach (var item in list)
+                    {
+                        DeviceConfig.Calibrations.Add(FileHelper.ReadJsonFile<CalibrationInfo>(FilePath.CalibrationPath + "//" + item.Value + "//" + item.Value + ".cfg"));
+                    }
+                    SendTaskMessage(Lang.校准加载完成, MessageLevel.Debug);
+                }
+                else
+                {
+                    SendTaskMessage(Lang.无校准, MessageLevel.Alarm);
+                }
+            }
+            catch (Exception ex)
+            {
+                DeviceConfig.Calibrations = new ObservableCollection<CalibrationInfo>();
+                LogHelper.WriteLogError("加载校准配置文件时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 保存校准
+        /// </summary>
+        /// <param name="calibration"></param>
+        public void SaveCalibration(CalibrationInfo calibration)
+        {
+            try
+            {
+                calibration.DateTime = DateTime.Now;
+                var calib = DeviceConfig.Calibrations.FirstOrDefault(item => item.Id == calibration.Id);
+                if (calib != null)
+                {
+                    calib = calibration;
+                }
+                else
+                {
+                    calibration.IsCreate = false;
+                    DeviceConfig.Calibrations.Add(calibration);
+                }
+
+                Dictionary<Guid, string> list = new Dictionary<Guid, string>();
+                foreach (var item in DeviceConfig.Calibrations)
+                {
+                    list.Add(item.Id, item.Name);
+                }
+                FileHelper.WriteJsonFile(list, FilePath.CalibrationPath + "//CalibrationList.cfg");
+                FileHelper.WriteJsonFile(calibration, FilePath.CalibrationPath + "//" + calibration.Name + "//" + calibration.Name + ".cfg");
+                if (calibration.ToolBlock != null)
+                {
+                    string prcPath = FilePath.CalibrationPath + "//" + calibration.Name + "//" + calibration.Name + ".vpp";
+                    if (!Directory.Exists(Path.GetDirectoryName(prcPath)))
+                    {
+                        Directory.CreateDirectory(Path.GetDirectoryName(prcPath));
+                    }
+                    CogSerializer.SaveObjectToFile(calibration.ToolBlock, prcPath);
+                }
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.保存完成, Duration = 1 });
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage(ex.Message, MessageLevel.Error);
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = ex.Message, Duration = 1 });
+                LogHelper.WriteLogError("保存校准时出错!", ex);
+            }
+        }
+
+        /// <summary>
+        /// 移除校准
+        /// </summary>
+        /// <param name=""></param>
+        public void RemoveCalibration(CalibrationInfo calibration)
+        {
+            var calib = DeviceConfig.Calibrations.FirstOrDefault(p => p.Id == calibration.Id);
+            if (calib != null)
+            {
+                DeviceConfig.Calibrations.Remove(calib);
+                Dictionary<Guid, string> list = new Dictionary<Guid, string>();
+                foreach (var item in DeviceConfig.Calibrations)
+                {
+                    list.Add(item.Id, item.Name);
+                }
+                FileHelper.WriteJsonFile(list, FilePath.CalibrationPath + "//CalibrationList.cfg");
+                _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg = Lang.保存完成, Duration = 1 });
+            }
+        }
+
+        #endregion
+
+        #region Feeder清料动作
+        /// <summary>
+        /// 加载Feeder清料动作
+        /// </summary>
+        public Dictionary<Guid, ObservableCollection<FeederClearWork>> LoadFeedersClearTask()
+        {
+            Dictionary<Guid, ObservableCollection<FeederClearWork>> FeedersClearWork = new Dictionary<Guid, ObservableCollection<FeederClearWork>>();
+            try
+            {
+                if (File.Exists(FilePath.FeedersClearTaskPath))
+                {
+                    FeedersClearWork = FileHelper.ReadJsonFile<Dictionary<Guid, ObservableCollection<FeederClearWork>>>(FilePath.FeedersClearTaskPath);
+                }
+                return FeedersClearWork;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("加载Feeder清料动作配置文件时出错!", ex);
+                return FeedersClearWork;
+            }
+        }
+
+        /// <summary>
+        /// 保存Feeder清料动作
+        /// </summary>
+        public void SaveFeedersClearTask(Dictionary<Guid, ObservableCollection<FeederClearWork>> FeedersClearWork)
+        {
+            FileHelper.WriteJsonFile(FeedersClearWork, FilePath.FeedersClearTaskPath);
+        }
+
+        /// <summary>
+        /// 执行Feeder清料
+        /// </summary>
+        /// <param name="FeederId"></param>
+        /// <param name="feederClearWork"></param>
+        /// <returns></returns>
+        public async Task ExecuteFeederClear(Guid FeederId, FeederClearWork feederClearWork, CancellationToken cancellationToken)
+        {
+            IVoiceCoilMotorFeeder Feeder = FeederService.GetFeeder(FeederId);
+
+            if (!Feeder.IsConnected)
+            {
+                return;
+            }
+
+            for (int i = 0; i < feederClearWork.ClearCount; i++)
+            {
+                //1.Feeder振动之前,打开挡板
+                await Feeder.OutputAsync((int)feederClearWork.BeforeOutput + 1, 0);
+                await Task.Delay(200);
+
+                //2.执行配置的Feeder振动任务
+                for (int j = 0; j < feederClearWork.VibrationCount; j++)
+                {
+                    await ExecuteFeederWorks(Feeder, feederClearWork.FeederWorks, true);
+
+                    //如果料仓停止了,则打开料仓运动
+                    if (!await Feeder.GetOutputStatusAsync())
+                    {
+                        await Feeder.OutputAsync((int)feederClearWork.BeforeOutput + 1, 0);
+                    }
+                    if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                    {
+                        await Feeder.StopOutputAsync();
+                        return;
+                    }
+                }
+
+                if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                {
+                    await Feeder.StopOutputAsync();
+                    return;
+                }
+
+                //3.Feeder振动之后,关闭挡板
+                await Feeder.StopOutputAsync();
+                await Task.Delay(300);
+            }
+            //3.Feeder振动之后,关闭挡板
+            await Feeder.StopOutputAsync();
+            await Task.Delay(300);
+        }
+        #endregion
+
+        #region 机器人指令执行
+
+        public Dictionary<Guid, CancellationTokenSource> RobotTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
+        /// <summary>
+        /// 机器人TCP接收
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        private async void Management_ReceivedEvent(Guid robotid, object arg2, TouchSocket.Sockets.ReceivedDataEventArgs e)
+        {
+            try
+            {
+                if (!RobotTCPCollection.ContainsKey(robotid))
+                    RobotTCPCollection.Add(robotid, new CancellationTokenSource());
+                else
+                {
+                    if (RobotTCPCollection[robotid].IsCancellationRequested)
+                    {
+                        RobotTCPCollection[robotid] = new CancellationTokenSource();
+                    }
+                }
+                var robot = await RobotService.GetRobotAsync(robotid);
+                var r = DeviceConfig.Robots.FirstOrDefault(ro => ro.Id == robotid);
+                //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
+                var buffer = e.ByteBlock.Span.ToString(robot.GetEncoding());
+                SendTaskMessage($"{r.RobotName}Received:{buffer}", MessageLevel.Info);
+
+                var _ = Task.Run(async () =>
+                {
+                    try
+                    {
+                        await ExecuteRemoteCommand(buffer, async result =>
+                        {
+                            if (result.Item1)
+                            {
+                                try
+                                {
+                                    if (result.Item2.Length > 1)
+                                    {
+                                        foreach (var item in result.Item2)
+                                        {
+                                            if (robot.ConnectType == TCPConnectType.Client)
+                                            {
+                                                if (robot.IsConnected)
+                                                {
+                                                    await robot.SendAsync($"{item}");
+                                                }
+                                            }
+                                            else
+                                            {
+                                                var cient = (ITcpSessionClient)arg2;
+                                                if (cient.Online)
+                                                {
+                                                    await robot.SendAsync(cient, $"{item}");
+                                                }
+                                            }
+                                            await Task.Delay(10);
+                                        }
+                                    }
+                                    else
+                                    {
+                                        if (robot.ConnectType == TCPConnectType.Client)
+                                        {
+                                            if (robot.IsConnected)
+                                            {
+                                                await robot.SendAsync($"{result.Item2[0]}");
+                                            }
+                                        }
+                                        else
+                                        {
+                                            var cient = (ITcpSessionClient)arg2;
+                                            if (cient.Online)
+                                            {
+                                                await robot.SendAsync(cient, $"{result.Item2[0]}");
+                                            }
+                                        }
+                                    }
+                                }
+                                catch (Exception ex)
+                                {
+                                    LogHelper.WriteLogError("TCP发送数据时出错!", ex);
+                                    SendTaskMessage(ex.Message, MessageLevel.Alarm);
+                                }
+
+                            }
+                        }, RobotTCPCollection[robotid].Token);
+                    }
+                    catch (Exception ex)
+                    {
+                        LogHelper.WriteLogError("处理机器人接收的命令时出错!", ex);
+                        SendTaskMessage(ex.Message, MessageLevel.Alarm);
+                    }
+                });
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("处理机器人接收的命令时出错!", ex);
+                SendTaskMessage(ex.Message, MessageLevel.Alarm);
+            }
+        }
+
+
+        /// <summary>
+        /// 机器人XY模组执行命令
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private async void Management_TrggerChangeEvent(Guid arg1, object arg2, List<ProcedureOutputOpcAdr> arg3)
+        {
+            if (!RobotTCPCollection.ContainsKey(arg1))
+                RobotTCPCollection.Add(arg1, new CancellationTokenSource());
+            else
+            {
+                if (RobotTCPCollection[arg1].IsCancellationRequested)
+                {
+                    RobotTCPCollection[arg1] = new CancellationTokenSource();
+                }
+            }
+            var robot = await RobotService.GetRobotAsync(arg1) as XYZ_Platform;
+            var r = DeviceConfig.Robots.FirstOrDefault(ro => ro.Id == arg1);
+            SendTaskMessage($"{r.RobotName}Received:{arg2}", MessageLevel.Info);
+            var _ = Task.Run(async () =>
+            {
+                try
+                {
+                    await ExecuteRemoteCommand(arg2.ToString(), async result =>
+                    {
+                        if (result.Item1)
+                        {
+                            try
+                            {
+
+                                string[] adrs = new string[arg3.Count];
+                                object[] values = new object[arg3.Count];
+                                values[0] = false;
+                                values[1] = false;
+                                string[] results = result.Item2[0].Split(',');
+                                for (int i = 0; i < arg3.Count; i++)
+                                {
+                                    if (i == 0)
+                                    {
+                                        if (results[1] == "OK")
+                                        {
+                                            adrs[i] = arg3[i].Name;
+                                            values[i] = true;
+                                            adrs[i + 1] = arg3[i + 1].Name;
+                                            values[i + 1] = false;
+                                        }
+                                        else
+                                        {
+                                            adrs[i] = arg3[i].Name;
+                                            values[i] = false;
+                                            adrs[i + 1] = arg3[i + 1].Name;
+                                            values[i + 1] = true;
+                                        }
+                                        i += 1;
+                                        continue;
+                                    }
+                                    if (i < arg3.Count - 1)
+                                    {
+                                        adrs[i] = arg3[i].Name;
+                                        if (i < results.Length)
+                                        {
+                                            float res = 0f;
+                                            if (float.TryParse(results[i], out res))
+                                            {
+                                                values[i] = results[i];
+                                            }
+                                            else
+                                            {
+                                                values[i] = res;
+                                            }
+                                        }
+                                        else
+                                        {
+                                            values[i] = 0f;
+                                        }
+                                    }
+                                }
+                                adrs[adrs.Length - 1] = arg3[arg3.Count - 1].Name;
+                                values[values.Length - 1] = true;
+                                robot.Plc.OpcUaClient.WriteNodes(adrs, values);
+                                await Task.Delay(10);
+
+
+                            }
+                            catch (Exception ex)
+                            {
+                                LogHelper.WriteLogError("回复plc发送数据时出错!", ex);
+                                SendTaskMessage(ex.Message, MessageLevel.Alarm);
+                            }
+
+                        }
+                    }, RobotTCPCollection[arg1].Token);
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("处理XYZ机器人接收的命令时出错!", ex);
+                    SendTaskMessage(ex.Message, MessageLevel.Alarm);
+                }
+            });
+        }
+
+        #region 处理命令
+
+        /// <summary>
+        /// 执行命令
+        /// </summary>
+        /// <param name="command"></param>
+        public async Task ExecuteRemoteCommand(string command, Action<Tuple<bool, string[]>> callback, CancellationToken cancellationToken)
+        {
+            string[] commandItem = command.Split(',');
+            if (CurrentProduct == null)
+            {
+                if (commandItem[0] == "GetProductName")
+                {
+                    callback.Invoke(new Tuple<bool, string[]>(true, new string[] { $"{commandItem[0]},null" }));
+                    return;
+                }
+            }
+
+            ProcedureModel procedure = null;
+            foreach (var cameraProcedures in CurrentProduct.CameraProcedures)
+            {
+                procedure = cameraProcedures.ProcedureModels.FirstOrDefault(p => p.TriggerCommand == commandItem[0]);
+                if (procedure != null) break;
+            }
+
+            if (procedure != null)
+            {
+                //相机拍照
+                await RunProcedure(procedure, commandItem, rst =>
+                {
+                    if (rst.Item1)
+                    {
+                        if (rst.Item2.Length > 1)
+                        {
+                            List<string> buffers = new List<string>();
+                            foreach (var item in rst.Item2)
+                            {
+                                buffers.Add($"{commandItem[0]},{item}");
+                            }
+                            callback.Invoke(new Tuple<bool, string[]>(rst.Item1, buffers.ToArray()));
+                        }
+                        else
+                        {
+                            callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2[0]}" }));
+                        }
+                    }
+                    else
+                    {
+                        callback.Invoke(rst);
+                    }
+                }, cancellationToken);
+                return;
+            }
+
+            switch (commandItem[0])
+            {
+                case "LoadProduct":
+                    await LoadProduct(commandItem[1], rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetProductName":
+                    await GetCurrentProductName(rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetProductID":
+                    await GetCurrentProductID(rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetSpeed":
+                    await GetCurrentProductSpeed(rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetAllRobotPoints":
+                    await GetAllRobotPoints(rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetRobotPointsCount":
+                    await GetRobotPointsCount(rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetRobotPoint":
+                    await GetRobotPoint(int.Parse(commandItem[1]), rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetPalletsCount":
+                    await GetPalletsCount(rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetAllPallets":
+                    await GetAllPallet(rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetPallet":
+                    await GetPallet(commandItem[1], rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetPalletPoint":
+                    await GetPalletPoint(commandItem[1], int.Parse(commandItem[2]), rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetToolCount":
+                    await GetToolCount(commandItem[1], rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetTool":
+                    await GetTool(commandItem[1], int.Parse(commandItem[2]), rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "GetProcedureParam":
+                    await GetProcedureParam(commandItem[1], rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "CycleTime":
+                    ExecuteCycleTime(commandItem[1], rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "Record":
+                    AddProductionRecords(commandItem[1], rst =>
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                    });
+                    break;
+                case "Err":
+                    SendTaskMessage(commandItem[1], MessageLevel.Error);
+                    DatabaseHelper.AppendAlarm(commandItem[1]);
+                    break;
+                case "Info":
+                    SendTaskMessage(commandItem[1], MessageLevel.Info);
+                    break;
+                case "GetGlobalParam":
+                    if (commandItem.Length == 2)
+                    {
+                        GetGlobalParam(commandItem[1], -1, rst =>
+                        {
+                            callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                        });
+                    }
+                    else if (commandItem.Length == 3)
+                    {
+                        GetGlobalParam(commandItem[1], int.Parse(commandItem[2]), rst =>
+                        {
+                            callback.Invoke(new Tuple<bool, string[]>(rst.Item1, new string[] { $"{commandItem[0]},{rst.Item2}" }));
+                        });
+                    }
+                    break;
+            }
+
+        }
+
+        /// <summary>
+        /// 运行流程
+        /// </summary>
+        /// <param name="procedure">流程对象</param>
+        /// <param name="items">触发命令</param>
+        /// <param name="callback">回调函数</param>
+        /// <param name="cancellationToken">取消任务</param>
+        /// <returns></returns>
+        public async Task RunProcedure(ProcedureModel procedure, string[] items, Action<Tuple<bool, string[]>> callback, CancellationToken cancellationToken)
+        {
+
+            string path = FilePath.ProductsPath + "//" + CurrentProduct.Name + "//" + procedure.CameraName + "//" + procedure.Name + ".cs";
+            string script = "";
+            if (File.Exists(path))
+            {
+                try
+                {
+                    script = FileHelper.ReadFile(path);
+                    SendTaskMessage(Lang.执行视觉处理脚本, MessageLevel.Debug);
+                    var rst1 = await ScriptHelper.ExecuteVisionScriptingAsync(script, _regionManager, _eventAggregator, _container, procedure, items, rst =>
+                    {
+                        callback.Invoke(rst);
+                    });
+                    if (!rst1.Item1)
+                    {
+                        SendTaskMessage(Lang.视觉处理脚本出错, MessageLevel.Error);
+                        callback.Invoke(new Tuple<bool, string[]>(false, new string[] { "ScriptError" }));
+                        foreach (var item in rst1.Item2)
+                        {
+                            SendTaskMessage(item, MessageLevel.Error);
+                        }
+
+                    }
+                }
+                catch (Exception ex)
+                {
+                    SendTaskMessage(ex.Message, MessageLevel.Error);
+                    LogHelper.WriteLogError("执行视觉处理脚本时出错!", ex);
+                    callback.Invoke(new Tuple<bool, string[]>(false, new string[] { "ScriptError" }));
+                }
+            }
+            else
+            {
+                //正常执行模块,每次拍照,会返回所有的结果数据
+                IVoiceCoilMotorFeeder Feeder = null;
+                if (procedure.FeederId != Guid.Empty)
+                {
+                    Feeder = this.FeederService.GetFeeder(procedure.FeederId);
+                    await RunProcedureFeeder(Feeder, procedure, items, rst =>
+                    {
+                        callback.Invoke(rst);
+                    }, cancellationToken);
+                }
+                else
+                {
+                    RunProcedureOther(procedure, items, rst =>
+                    {
+                        callback.Invoke(rst);
+                    }, cancellationToken);
+                }
+            }
+        }
+
+        /// <summary>
+        /// Feeder当前Blob的面积,产品-流程-面积
+        /// </summary>
+        public Dictionary<Guid, Dictionary<Guid, double>> feederCurentBlobArea = new Dictionary<Guid, Dictionary<Guid, double>>();
+        /// <summary>
+        /// 最后一次feeder拍照出来的点位,流程-点数据
+        /// </summary>
+        public Dictionary<Guid, List<Vector<double>>> LastPointsForFeeder = new Dictionary<Guid, List<Vector<double>>>();
+
+        /// <summary>
+        /// 每次拍照得到的点位数据集合,每个流程中包含多个结果输出项,每个结果项中包含多个点位,流程-输出集合-点位队列
+        /// </summary>
+        public Dictionary<Guid, Dictionary<string, Queue<string>>> PointCollection = new Dictionary<Guid, Dictionary<string, Queue<string>>>();
+        /// <summary>
+        /// Feeder相机引导模式
+        /// </summary>
+        /// <param name="Feeder">feeder</param>
+        /// <param name="procedure">流程对象</param>
+        /// <param name="items">触发命令</param>
+        /// <param name="callback">回调函数</param>
+        /// <returns></returns>
+        public async Task RunProcedureFeeder(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, string[] items, Action<Tuple<bool, string[]>> callback, CancellationToken cancellationToken)
+        {
+            //是否检测上次的点位,相同点位排除
+            bool IsCheckLastPoints = false;
+            bool IsSingleResultModel = false;
+            int InputVibration = 0;
+            int GetPosCount = 1;
+            Dictionary<string, string> InputTerminal = null;           //触发命令传入的输入终端
+
+            if (items.Length >= 2 && string.Equals(items[1], "GetPos"))
+            {
+                //Camera1,GetPos,PosCount,CheckLastPoints
+                if (items.Length >= 4 && string.Equals(items[3], "CheckLastPoints"))
+                {
+                    IsCheckLastPoints = true;
+                    GetPosCount = int.Parse(items[2]);
+                }
+                ////Camera1,GetPos,CheckLastPoints
+                else if (items.Length >= 3 && string.Equals(items[2], "CheckLastPoints"))
+                {
+                    IsCheckLastPoints = true;
+                    GetPosCount = 1;
+                }
+                else if (items.Length >= 3 && int.TryParse(items[2], out GetPosCount))
+                {
+
+                }
+                else
+                {
+                    GetPosCount = 1;
+                }
+                if (GetPosCount <= 0)
+                {
+                    GetPosCount = 1;
+                }
+                //进入一次拍照后,,点位数据保存在软件里面,机器人每次跟软件获取一个或者两个点位
+                ////获取点位数据
+                if (!PointCollection.ContainsKey(procedure.Id))
+                {
+                    PointCollection.Add(procedure.Id, new Dictionary<string, Queue<string>>());
+                }
+
+                IsSingleResultModel = true;
+            }
+            else if (items.Length >= 2 && string.Equals(items[1], "ClearPos"))
+            {
+                //进入一次拍照后,,点位数据保存在软件里面,机器人每次跟软件获取一个或者两个点位
+                ////清除所有点位数据
+                if (!PointCollection.ContainsKey(procedure.Id))
+                {
+                    PointCollection.Add(procedure.Id, new Dictionary<string, Queue<string>>());
+                }
+                PointCollection[procedure.Id].Clear();
+                IsSingleResultModel = true;
+                callback.Invoke(new Tuple<bool, string[]>(true, new string[] { "ClearPos" }));
+                return;
+            }
+            else if (items.Length >= 2 && string.Equals(items[1], "CheckLastPoints"))
+            {
+                IsCheckLastPoints = true;
+            }
+            else if (items.Length >= 2 && string.Equals(items[1], "Vibration"))
+            {
+                //先振后拍
+                InputVibration = 1;
+            }
+            else if (items.Length >= 2 && string.Equals(items[1], "NoVibration"))
+            {
+                //先拍再决定是否要不要振
+                InputVibration = 2;
+            }
+            else if (items.Length >= 2 && string.Equals(items[1], "SetVisionToolInputs"))
+            {
+                InputTerminal = new Dictionary<string, string>();
+                //触发命令传入的输入终端
+                for (int i = 2; i < items.Length; i += 2)
+                {
+                    if (!string.IsNullOrEmpty(items[i]) && items.Length >= i + 2)
+                    {
+                        InputTerminal.Add(items[i].Trim(), items[i + 1].Trim());
+                    }
+                }
+                if (InputTerminal.Count <= 0)
+                {
+                    InputTerminal = null;
+                }
+            }
+
+            //如果还没有结果项目,则触发拍照,获取结果
+            if (IsSingleResultModel && PointCollection[procedure.Id].Count > 0)
+            {
+                //遍历所有的结果项
+                foreach (var item in PointCollection[procedure.Id])
+                {
+                    //如果结果的数量大于等于可获取的点位数量,则直接返回点位数据
+                    if (item.Value != null && item.Value.Count >= GetPosCount)
+                    {
+                        List<string> poslist = new List<string>();
+                        for (int i = 0; i < GetPosCount; i++)
+                        {
+                            poslist.Add(item.Value.Dequeue());
+                        }
+                        callback.Invoke(new Tuple<bool, string[]>(true, new string[] { $"OK,{item.Key},{string.Join(",", poslist)}" }));
+                        SendTaskMessage($"{item.Key}{Lang.剩余点位数量}:{item.Value.Count}", MessageLevel.Debug);
+                        return;
+                    }
+                }
+            }
+            if (IsSingleResultModel)
+            {
+                PointCollection[procedure.Id].Clear();
+            }
+
+            await ExecuteFeederForPhotoBefore(Feeder, procedure, InputVibration, cancellationToken);
+
+            if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+            {
+                await Feeder.CloseLightAsync();
+                return;
+            }
+
+            DateTime nowtime = DateTime.Now;
+            //多次拍照
+            for (int i = 0; i < procedure.FeederFailLimit; i++)
+            {
+                if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                {
+                    await Feeder.CloseLightAsync();
+                    return;
+                }
+                SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
+                string photoresult = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
+                if (!string.IsNullOrEmpty(photoresult))
+                {
+                    //多次拍照,如果拍照次数到达上限,直接返回结果
+                    if (i == procedure.FeederFailLimit - 1)
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(true, new string[] { $"NG,{photoresult}" }));
+                        return;
+                    }
+                    else
+                    {
+                        continue;
+                    }
+                }
+
+                var BlobTotalArea = (double)outputCollection["BlobTotalArea"].Value;
+                //记录当前的blob面积
+                Dictionary<Guid, double> tuple;
+                if (feederCurentBlobArea.TryGetValue(CurrentProduct.ID, out tuple))
+                {
+                    //如流程当前已经存在此流程的记录
+                    if (tuple.ContainsKey(procedure.Id))
+                    {
+                        tuple[procedure.Id] = BlobTotalArea;
+                    }
+                    else
+                    {
+                        tuple.Add(procedure.Id, BlobTotalArea);
+                    }
+                }
+                else
+                {
+                    feederCurentBlobArea.Add(CurrentProduct.ID, new Dictionary<Guid, double>());
+                    feederCurentBlobArea[CurrentProduct.ID].Add(procedure.Id, BlobTotalArea);
+                }
+
+                if (!outputCollection.Contains("Found"))
+                {
+                    callback.Invoke(new Tuple<bool, string[]>(true, new string[] { "NG,NoOut[Found]" }));
+                    return;
+                }
+                bool Found = (bool)(outputCollection["Found"].Value);
+                //拍照OK
+                if (Found)
+                {
+                    SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
+                    if (procedure.ProcedureOutputs == null)
+                    {
+                        SendTaskMessage(Lang.视觉流程未配置输出项, MessageLevel.Alarm);
+                        callback.Invoke(new Tuple<bool, string[]>(true, new string[] { "NG,NotOutputs" }));
+                        return;
+                    }
+
+                    var ResultCollection = GetVisionOutput(procedure, outputCollection, items);
+                    if (!ResultCollection.Item1)
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(true, new string[] { ResultCollection.Item2 }));
+                        return;
+                    }
+                    List<string> SendResults = new List<string>();
+                    //将本次点位结果记录至最后一次
+                    if (!LastPointsForFeeder.ContainsKey(Feeder.Id))
+                    {
+                        LastPointsForFeeder.Add(Feeder.Id, new List<Vector<double>>());
+                    }
+
+                    int PosNum = 0;
+                    bool ishavepoint = false;
+                    List<Vector<double>> pointBuffer = new List<Vector<double>>();
+                    foreach (var result in ResultCollection.Item3)
+                    {
+                        //是点位数据时
+                        if (result.Value.Item1)
+                        {
+                            ishavepoint = true;
+                            //值不为空时
+                            if (result.Value.Item2 != null)
+                            {
+                                List<string> points = new List<string>();
+
+                                foreach (var pos in (List<Vector<double>>)(result.Value.Item2))
+                                {
+                                    pointBuffer.Add(pos);
+                                    //判断是否有重复的点位,防止机器人重复取同一个物料,陷入死循环
+                                    if (IsCheckLastPoints)
+                                    {
+                                        if (LastPointsForFeeder.ContainsKey(Feeder.Id))
+                                        {
+                                            var repeated = LastPointsForFeeder[Feeder.Id].FirstOrDefault(p => Math.Abs(p[0] - pos[0]) < 1 && Math.Abs(p[1] - pos[1]) < 1);
+                                            if (repeated != null) continue;
+                                        }
+                                    }
+
+                                    if (IsSingleResultModel)
+                                    {
+                                        PosNum++;
+                                        //如果当前是软件点位队列存储模式,则,将所有数据存储在队列中
+                                        if (!PointCollection[procedure.Id].ContainsKey(result.Key))
+                                        {
+                                            PointCollection[procedure.Id].Add(result.Key, new Queue<string>());
+                                        }
+                                        PointCollection[procedure.Id][result.Key].Enqueue($"{pos[0]:F3},{pos[1]:F3},{pos[2]:F3}");
+                                    }
+                                    else
+                                    {
+                                        //根据当前点位数量决定是否继续输出点位。
+                                        PosNum++;
+                                        if (PosNum >= procedure.OutputPointCountMax)
+                                        {
+                                            points.Add($"{pos[0]:F3},{pos[1]:F3},{pos[2]:F3}");
+                                            break;
+                                        }
+                                        else
+                                        {
+                                            points.Add($"{pos[0]:F3},{pos[1]:F3},{pos[2]:F3}");
+                                        }
+                                    }
+                                }
+                                if (IsSingleResultModel)
+                                {
+                                    //如果当前是软件点位队列存储模式,则,将所有数据存储在队列中
+                                    if (!PointCollection[procedure.Id].ContainsKey(result.Key))
+                                    {
+                                        PointCollection[procedure.Id].Add(result.Key, new Queue<string>());
+                                    }
+                                    SendTaskMessage($"{result.Key}{Lang.可用的点位个数}:{PointCollection[procedure.Id][result.Key].Count}", MessageLevel.Debug);
+                                }
+                                else
+                                {
+                                    if (points.Count == 0)
+                                    {
+                                        SendResults.Add($"0");
+                                        break;
+                                    }
+                                    else
+                                    {
+                                        SendResults.Add($"{points.Count},{string.Join(",", points)}");
+                                    }
+                                }
+                            }
+                            else
+                            {
+                                SendResults.Add($"0");
+                            }
+                        }
+                        //其他输出数据时
+                        else
+                        {
+                            if (result.Value.Item2 != null)
+                            {
+                                SendResults.Add((string)result.Value.Item2);
+                            }
+                            else
+                            {
+                                SendResults.Add($"null");
+                            }
+                        }
+                    }
+                    //将本次点位结果记录至最后一次
+                    LastPointsForFeeder[Feeder.Id] = pointBuffer;
+
+                    if (ishavepoint && PosNum <= 0)
+                    {
+                        //存在点位输出项,但是点位数量为0
+                        await ExecuteFeederForPhotoLater(Feeder, procedure, BlobTotalArea, cancellationToken);
+                        if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                        {
+                            await Feeder.CloseLightAsync();
+                            return;
+                        }
+                        continue;
+                    }
+
+                    if (Feeder != null)
+                    {
+                        await Feeder.CloseLightAsync();
+                    }
+
+                    if (IsSingleResultModel)
+                    {
+                        //遍历所有的结果项
+                        foreach (var item in PointCollection[procedure.Id])
+                        {
+                            //如果结果的数量大于等于可获取的点位数量,则直接返回点位数据
+                            if (item.Value != null && item.Value.Count >= GetPosCount)
+                            {
+                                List<string> poslist = new List<string>();
+                                for (int j = 0; j < GetPosCount; j++)
+                                {
+                                    poslist.Add(item.Value.Dequeue());
+                                }
+                                callback.Invoke(new Tuple<bool, string[]>(true, new string[] { $"OK,{item.Key},{string.Join(",", poslist)}" }));
+                                SendTaskMessage($"{item.Key}{Lang.剩余点位数量}:{item.Value.Count}", MessageLevel.Debug);
+                                return;
+                            }
+                        }
+                    }
+                    else
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(true, new string[] { $"OK,{string.Join(";", SendResults)}" }));
+                    }
+
+                    return;
+                }
+                //拍照NG
+                else
+                {
+                    SendTaskMessage(Lang.拍照NG, MessageLevel.Error);
+
+                    await ExecuteFeederForPhotoLater(Feeder, procedure, BlobTotalArea, cancellationToken);
+                    continue;
+                }
+            }
+
+            SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
+            callback.Invoke(new Tuple<bool, string[]>(true, new string[] { "NG,NoFind" }));
+        }
+
+        /// <summary>
+        /// 相机拍照,其他模式
+        /// </summary>
+        /// <param name="procedure"></param>
+        /// <param name="items"></param>
+        /// <param name="callback"></param>
+        public void RunProcedureOther(ProcedureModel procedure, string[] items, Action<Tuple<bool, string[]>> callback, CancellationToken cancellationToken)
+        {
+            DateTime nowtime = DateTime.Now;
+            Dictionary<string, string> InputTerminal = null;           //触发命令传入的输入终端
+            if (items.Length >= 2 && string.Equals(items[1], "SetVisionToolInputs"))
+            {
+                InputTerminal = new Dictionary<string, string>();
+                //触发命令传入的输入终端
+                for (int i = 2; i < items.Length; i += 2)
+                {
+                    if (!string.IsNullOrEmpty(items[i]) && items.Length >= i + 2)
+                    {
+                        InputTerminal.Add(items[i].Trim(), items[i + 1].Trim());
+                    }
+                }
+                if (InputTerminal.Count <= 0)
+                {
+                    InputTerminal = null;
+                }
+            }
+            for (int i = 0; i < procedure.FeederFailLimit; i++)
+            {
+                if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                {
+                    return;
+                }
+                SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
+                string photoresult = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
+                if (!string.IsNullOrEmpty(photoresult))
+                {
+                    //多次拍照,如果拍照次数到达上限,直接返回结果
+                    if (i == procedure.FeederFailLimit - 1)
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(true, new string[] { $"NG,{photoresult}" }));
+                        return;
+                    }
+                    else
+                    {
+                        continue;
+                    }
+                }
+                if (!outputCollection.Contains("Found"))
+                {
+                    callback.Invoke(new Tuple<bool, string[]>(true, new string[] { "NG,NoOut[Found]" }));
+                    return;
+                }
+                bool Found = (bool)(outputCollection["Found"].Value);
+                //拍照OK
+                if (Found)
+                {
+                    SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
+                    if (procedure.ProcedureOutputs == null)
+                    {
+                        SendTaskMessage(Lang.视觉流程未配置输出项, MessageLevel.Alarm);
+                        callback.Invoke(new Tuple<bool, string[]>(true, new string[] { "NG,NotOutputs" }));
+                        return;
+                    }
+
+                    var ResultCollection = GetVisionOutput(procedure, outputCollection, items);
+                    if (!ResultCollection.Item1)
+                    {
+                        callback.Invoke(new Tuple<bool, string[]>(true, new string[] { ResultCollection.Item2 }));
+                        return;
+                    }
+
+                    List<string> SendResults = new List<string>();
+                    int PosNum = 0;
+                    bool ishavepoint = false;
+                    foreach (var result in ResultCollection.Item3)
+                    {
+                        //是点位数据时
+                        if (result.Value.Item1)
+                        {
+                            ishavepoint = true;
+                            //值不为空时
+                            if (result.Value.Item2 != null)
+                            {
+                                List<string> points = new List<string>();
+
+                                foreach (var pos in (List<Vector<double>>)(result.Value.Item2))
+                                {
+                                    //根据当前点位数量决定是否继续输出点位。
+                                    PosNum++;
+                                    if (PosNum >= procedure.OutputPointCountMax)
+                                    {
+                                        points.Add($"{pos[0]:F3},{pos[1]:F3},{pos[2]:F3}");
+                                        break;
+                                    }
+                                    else
+                                    {
+                                        points.Add($"{pos[0]:F3},{pos[1]:F3},{pos[2]:F3}");
+                                    }
+                                }
+                                if (points.Count == 0)
+                                {
+                                    SendResults.Add($"0");
+                                    break;
+                                }
+                                else
+                                {
+                                    SendResults.Add($"{points.Count},{string.Join(",", points)}");
+                                }
+                            }
+                            else
+                            {
+                                SendResults.Add($"0");
+                            }
+                        }
+                        //其他输出数据时
+                        else
+                        {
+                            if (result.Value.Item2 != null)
+                            {
+                                SendResults.Add((string)result.Value.Item2);
+                            }
+                            else
+                            {
+                                SendResults.Add($"null");
+                            }
+                        }
+                    }
+                    if (ishavepoint && PosNum <= 0)
+                    {
+                        continue;
+                    }
+                    callback.Invoke(new Tuple<bool, string[]>(true, new string[] { $"OK,{string.Join(";", SendResults)}" }));
+                    return;
+                }
+                //拍照NG
+                else
+                {
+                    SendTaskMessage(Lang.拍照NG, MessageLevel.Error);
+                    continue;
+                }
+            }
+            SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
+            callback.Invoke(new Tuple<bool, string[]>(true, new string[] { "NG,NoFind" }));
+        }
+
+        #region 相机拍照
+
+        /// <summary>
+        /// 执行相机拍照
+        /// </summary>
+        /// <param name="procedure"></param>
+        /// <param name="outputCollection"></param>
+        /// <returns></returns>
+        public string ExecutePhoto(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
+        {
+            try
+            {
+                //采集图像
+                var camera = CameraService.GetCamera(procedure.CameraId);
+                bool succed = camera.SetExposureTime(procedure.ExposureTime);
+                if (!succed)
+                {
+                    SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
+                }
+                succed = camera.SetGain(procedure.Gain);
+                if (!succed)
+                {
+                    SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
+                }
+                DateTime nowtime = DateTime.Now;
+                LogHelper.WriteLogInfo("开始采集图像");
+                var image = camera.Grab();
+                if (image == null)
+                {
+
+                    SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
+                    outputCollection = null;
+                    return "CameraError";
+                }
+                procedure.ToolBlock.Inputs["InputImage"].Value = image;
+                LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
+                if (InputTerminal != null)
+                {
+                    LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
+                    foreach (var item in InputTerminal)
+                    {
+                        if (procedure.ToolBlock.Inputs.Contains(item.Key))
+                        {
+                            LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
+                            procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
+                        }
+                        else
+                        {
+                            LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
+                            procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
+                        }
+                    }
+                }
+
+                //运行视觉工具
+                LogHelper.WriteLogInfo("开始运行视觉工具");
+                procedure.ToolBlock.Run();
+
+                if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
+                {
+                    SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
+                    outputCollection = procedure.ToolBlock.Outputs;
+                    ICogRecord record = null;
+                    foreach (CogToolBlockTerminal item in outputCollection)
+                    {
+                        if (item.Value is ICogRecord)
+                            record = item.Value as ICogRecord;
+                    }
+                    _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
+                    {
+                        CameraName = procedure.CameraName,
+                        Id = procedure.CameraId,
+                        Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
+                        Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
+                        Record = record,
+                        Result = (bool)(outputCollection["Found"].Value),
+                        IsShow = true,
+                        IsSaveImage = procedure.IsSaveImage,
+                        SaveImageModel = procedure.SaveImageModel,
+                        SaveImagePathModel = procedure.SaveImagePathModel,
+                        SavePath = procedure.SavePath,
+                        IsCompress = procedure.IsCompress,
+                    });
+                    DatabaseHelper.AddCameraRecords(CurrentProduct.Name, procedure.Name, outputCollection);
+                    return string.Empty;
+                }
+                else
+                {
+                    SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
+                    SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
+                    outputCollection = null;
+                    _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
+                    {
+                        CameraName = procedure.CameraName,
+                        Id = procedure.CameraId,
+                        Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
+                        Graphic = new CogGraphicCollection(),
+                        Result = false,
+                        IsShow = true,
+                        IsSaveImage = procedure.IsSaveImage,
+                        SaveImageModel = procedure.SaveImageModel,
+                        SaveImagePathModel = procedure.SaveImagePathModel,
+                        SavePath = procedure.SavePath
+                    });
+                    DatabaseHelper.AddCameraRecords(CurrentProduct.Name, procedure.Name, outputCollection);
+                    return "ToolBlockError";
+                }
+            }
+            catch (Exception ex)
+            {
+                SendTaskMessage(ex.Message, MessageLevel.Error);
+                LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
+                outputCollection = null;
+                return "Error";
+            }
+        }
+
+        /// <summary>
+        /// 校准转换
+        /// </summary>
+        /// <param name="calib"></param>
+        /// <param name="x"></param>
+        /// <param name="y"></param>
+        /// <param name="angle"></param>
+        /// <returns></returns>
+        public Vector<double> TransformPoint(CalibrationInfo calib, double x, double y, double angle, string[] items, out string message, RobotBrand robotBrand = RobotBrand.Default)
+        {
+            //得到校准矩阵
+            Matrix<double> matrix = Matrix<double>.Build.DenseOfArray(calib.AffineTransformationMaterial);
+            if (calib.CameraMount == CameraMount.FixedDown || calib.CameraMount == CameraMount.MobileJ2 || calib.CameraMount == CameraMount.MobileJ4)
+            {
+                angle *= -1;
+            }
+            //将像素坐标转换成机器人坐标
+            var rpos = matrix * Vector<double>.Build.Dense(new double[] { x, y, 1 });
+            if (calib.CameraMount == Enums.CameraMount.MobileJ4)
+            {
+                if (items.Length < 4)
+                {
+                    SendTaskMessage(Lang.J4移动相机校准转换条件错误, MessageLevel.Alarm);
+                    message = "NG,DataError";
+                    return null;
+                }
+                //像素直接转换成mm时的点位
+                double Robot_X, Robot_Y;
+                Robot_X = rpos[0];
+                Robot_Y = rpos[1];
+
+                //机器人当前TOOL 0下的坐标
+                double curpos_x = 0, curpos_y = 0, curpos_u = 0;
+                curpos_x = double.Parse(items[1]);
+                curpos_y = double.Parse(items[2]);
+                curpos_u = double.Parse(items[3]);
+
+                //得到旋转矩阵
+                double angle1 = Math.PI * (curpos_u - calib.MarkPoint.U) / 180;
+                // 创建T矩阵
+                Matrix<double> rotationMatrix = Matrix<double>.Build.DenseOfArray(new double[,]
+                {
+                                            { Math.Cos(angle1), -Math.Sin(angle1) },
+                                            { Math.Sin(angle1), Math.Cos(angle1) }
+                });
+
+                Vector<double> p3 = Vector<double>.Build.Dense(new double[] { Robot_X - calib.CalibPoints[0].Robot.X, Robot_Y - calib.CalibPoints[0].Robot.Y });
+                Vector<double> phere = Vector<double>.Build.Dense(new double[] { curpos_x, curpos_y });
+
+                var cc = rotationMatrix * p3 + phere;
+                rpos = Vector<double>.Build.Dense(new double[] { cc[0], cc[1] });
+            }
+            else if (calib.CameraMount == Enums.CameraMount.MobileDown_XYPlatform)
+            {
+                if (items.Length < 4)
+                {
+                    SendTaskMessage(Lang.移动相机校准转换条件错误, MessageLevel.Alarm);
+                    message = "NG,DataError";
+                    return null;
+                }
+                //像素直接转换成mm时的点位
+                double Robot_X, Robot_Y;
+                Robot_X = rpos[0];
+                Robot_Y = rpos[1];
+
+                //模组当前TOOL 0下的坐标(相当于模组吸嘴坐标)
+                double curpos_x = 0, curpos_y = 0, curpos_u = 0;
+                curpos_x = double.Parse(items[1]);
+                curpos_y = double.Parse(items[2]);
+                curpos_u = double.Parse(items[3]);
+
+                //得到旋转矩阵
+                //double angle1 = Math.PI * (curpos_u - calib.MarkPoint.U) / 180;
+                double angle1 = 0;
+                // 创建T矩阵
+                Matrix<double> rotationMatrix = Matrix<double>.Build.DenseOfArray(new double[,]
+                {
+                                            { Math.Cos(angle1), -Math.Sin(angle1) },
+                                            { Math.Sin(angle1), Math.Cos(angle1) }
+                });
+
+                Vector<double> p3 = Vector<double>.Build.Dense(new double[] { Robot_X - calib.CalibPoints[0].Robot.X, Robot_Y - calib.CalibPoints[0].Robot.Y });
+                Vector<double> phere = Vector<double>.Build.Dense(new double[] { curpos_x, curpos_y });
+
+                var cc = rotationMatrix * p3 + phere;
+                rpos = Vector<double>.Build.Dense(new double[] { cc[0], cc[1] });//Mark点在tool0下的的坐标
+            }
+            else
+            {
+                //当需要直接转换工具坐标时
+                if (items.Length == 4 && double.TryParse(items[1], out double curposX) && double.TryParse(items[2], out double curposY) && double.TryParse(items[3], out double curposU))
+                {
+                    //根据机器人当前的点位计算工具坐标
+                    ToolCoord tool = new ToolCoord();
+                    if (robotBrand == RobotBrand.Schneider)
+                    {
+                        curposU *= -1;
+                    }
+                    tool.ComputeTool(curposX, curposY, curposU, rpos[0], rpos[1]);
+                    rpos = Vector<double>.Build.Dense(new double[] { tool.X, tool.Y });
+                }
+            }
+            message = string.Empty;
+            return Vector<double>.Build.Dense(new double[] { rpos[0], rpos[1], angle });
+        }
+
+        /// <summary>
+        /// 获取需要输出项
+        /// </summary>
+        /// <param name="procedure"></param>
+        /// <param name="outputCollection"></param>
+        /// <param name="IsCheckLastPoints"></param>
+        /// <returns>是否成功,错误返回内容,<项的名称,<是否是点位数据,值>></returns>
+        public Tuple<bool, string, Dictionary<string, Tuple<bool, object>>> GetVisionOutput(ProcedureModel procedure, CogToolBlockTerminalCollection outputCollection, string[] items)
+        {
+            RobotBrand robotBrand = RobotBrand.Default;
+            var robot = DeviceConfig.Robots.FirstOrDefault(r => r.Id == procedure.RobotId);
+            if (robot != null)
+            {
+                robotBrand = robot.RobotBrand;
+            }
+            List<string> SendResults = new List<string>();
+            //<输出项的名称,<是否点位,每项输出集合值>>
+            Dictionary<string, Tuple<bool, object>> ResultCollection = new Dictionary<string, Tuple<bool, object>>();
+            foreach (var output in procedure.ProcedureOutputs)      //遍历配置的所有需要输出项
+            {
+                //根据输出类型进行区分输出
+                if (output.ValueType == typeof(string))
+                {
+                    //需要点位转换时,进行点位提取
+                    if (output.IsPointTran)
+                    {
+                        if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
+                        {
+                            //如果需要输出的项的值为空,即点位数据为空,则输出点位的个数为0
+                            ResultCollection.Add(output.Name, new Tuple<bool, object>(true, null));
+                            continue;
+                        }
+                        string[] strpoints = outputCollection[output.Name].Value.ToString().Split(";");
+                        List<Vector<double>> currentPointsForFeeder = new List<Vector<double>>();
+                        int index = 0;
+                        //获取相机校准
+                        var calib = DeviceConfig.Calibrations.FirstOrDefault(cal => cal.Id == procedure.CalibrationId);
+                        if (calib == null)
+                        {
+                            SendTaskMessage(Lang.J4移动相机校准转换条件错误1, MessageLevel.Alarm);
+                            return new Tuple<bool, string, Dictionary<string, Tuple<bool, object>>>(false, "NG,NotCalibrations", null);
+                        }
+                        List<string> SendDtat = new List<string>();
+                        List<string> points = new List<string>();
+                        //遍历所有的输出点位
+                        foreach (var pos in strpoints)
+                        {
+                            //转换点位-像素转换成机器人绝对坐标
+                            var rpos = TransformPoint(calib, double.Parse(pos.Split(',')[0]), double.Parse(pos.Split(',')[1]), double.Parse(pos.Split(',')[2]), items, out string message, robotBrand);
+                            if (rpos == null)
+                            {
+                                return new Tuple<bool, string, Dictionary<string, Tuple<bool, object>>>(false, message, null);
+                            }
+                            currentPointsForFeeder.Add(rpos);
+                        }
+
+                        ResultCollection[output.Name] = new Tuple<bool, object>(true, currentPointsForFeeder);
+                    }
+                    //直接输出字符串
+                    else
+                    {
+                        if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
+                        {
+                            ResultCollection.Add(output.Name, new Tuple<bool, object>(false, null));
+                            continue;
+                        }
+                        ResultCollection[output.Name] = new Tuple<bool, object>(false, outputCollection[output.Name].Value.ToString());
+                    }
+                }
+                else
+                {
+                    if (outputCollection[output.Name].Value == null)
+                    {
+                        ResultCollection.Add(output.Name, new Tuple<bool, object>(false, null));
+                    }
+                    else
+                    {
+                        ResultCollection[output.Name] = new Tuple<bool, object>(false, outputCollection[output.Name].Value.ToString());
+                    }
+                }
+            }
+            return new Tuple<bool, string, Dictionary<string, Tuple<bool, object>>>(true, string.Empty, ResultCollection);
+        }
+
+        /// <summary>
+        /// Feeder拍照前,执行Feeder
+        /// </summary>
+        /// <param name="Feeder"></param>
+        /// <param name="procedure"></param>
+        /// <returns></returns>
+        public async Task ExecuteFeederForPhotoBefore(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, int CompulsoryVibration, CancellationToken cancellationToken)
+        {
+            if (Feeder.FeederBrand == FeederBrand.AFAG)
+            {
+                await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
+            }
+            else
+            {
+                //Feeder光源亮度设置
+                if (procedure.LightValue > 3)
+                {
+                    var light = await Feeder.GetLightBrightnessAsync();
+                    if (procedure.LightValue != light)
+                    {
+                        await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
+                    }
+                    //打开光源
+                    await Feeder.OpenLightAsync();
+                }
+            }
+
+            if (CompulsoryVibration == 2)
+            {
+                return;
+            }
+            //先振后拍时
+            if (procedure.VibrationModel == VibrationModel.VibrationPhoto || CompulsoryVibration == 1)
+            {
+                if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
+                {
+                    bool flog = false;
+                    Dictionary<Guid, double> tuple;
+                    if (feederCurentBlobArea.TryGetValue(CurrentProduct.ID, out tuple))
+                    {
+                        //首先判断是否是当前流程
+                        if (tuple.TryGetValue(procedure.Id, out double minArea))
+                        {
+                            //如果上次的Blob面积小于设定的最小值,则触发供料
+                            if (minArea <= procedure.MinArea)
+                            {
+                                flog = true;
+                                SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
+                                await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
+                                await Task.Delay(procedure.WaitFeederStop);
+                                SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
+                            }
+                        }
+                    }
+                    if (!flog)
+                    {
+                        //执行配置的Feeder振动任务
+                        await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken, false);
+                    }
+                    await Task.Delay(procedure.WaitFeederStop);
+                }
+            }
+            else
+            {
+                if (procedure.LightValue > 3)
+                {
+                    await Task.Delay(procedure.WaitPhoto);
+                }
+
+                Dictionary<Guid, double> tuple;
+                if (feederCurentBlobArea.TryGetValue(CurrentProduct.ID, out tuple))
+                {
+                    //首先判断是否是当前流程
+                    if (tuple.TryGetValue(procedure.Id, out double minArea))
+                    {
+                        //如果上次的Blob面积小于设定的最小值,则触发供料
+                        if (minArea <= procedure.MinArea)
+                        {
+                            SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
+                            await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
+                            await Task.Delay(procedure.WaitFeederStop);
+                            SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
+
+                            //执行配置的Feeder振动任务
+                            /*foreach (var feederwork in procedure.FeederWorks.FeederWorkList)
+                            {
+                                if (feederwork.Function == VibrationFunction.Delay)
+                                {
+                                    await Task.Delay(feederwork.Duration);
+                                }
+                                else
+                                {
+                                    await Feeder.StartAction((int)feederwork.Function, feederwork.Duration);
+                                    await Task.Delay(feederwork.Duration);
+                                }
+                            }*/
+                            await Task.Delay(procedure.WaitFeederStop);
+                        }
+                    }
+                }
+            }
+        }
+
+        /// <summary>
+        /// Feeder拍照后,执行Feeder
+        /// </summary>
+        /// <param name="Feeder"></param>
+        /// <param name="procedure"></param>
+        /// <param name="curentBlobArea"></param>
+        /// <returns></returns>
+        public async Task ExecuteFeederForPhotoLater(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, double curentBlobArea, CancellationToken cancellationToken)
+        {
+            //根据斑点面积决定是否料仓供料
+            if (curentBlobArea <= procedure.MinArea)
+            {
+                SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
+                await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
+                await Task.Delay(procedure.WaitFeederStop);
+                SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
+            }
+            else
+            {
+                if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
+                {
+                    SendTaskMessage(Lang.执行Feeder振动, MessageLevel.Info);
+                    //执行配置的Feeder振动任务
+                    await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken);
+
+                    await Task.Delay(procedure.WaitFeederStop);
+                    SendTaskMessage(Lang.Feeder振动结束, MessageLevel.Info);
+                }
+            }
+        }
+
+        #endregion
+
+        /// <summary>
+        /// 加载产品
+        /// </summary>
+        /// <param name="name"></param>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task LoadProduct(string name, Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                ProductModel product = null;
+                product = Products.FirstOrDefault(p => p.Name == name);
+                if (product == null)
+                {
+                    if (int.TryParse(name, out int ProductNumber))
+                    {
+                        product = Products.FirstOrDefault(p => p.NumberCode == ProductNumber);
+                    }
+                    else
+                    {
+                        callback.Invoke(new Tuple<bool, string>(true, "NG,NoProduct"));
+                        return;
+                    }
+                }
+                LoadProducts(product);
+                callback.Invoke(new Tuple<bool, string>(true, "OK"));
+            });
+        }
+
+        /// <summary>
+        /// 获取当前产品名称
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetCurrentProductName(Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, "null"));
+                    return;
+                }
+                callback.Invoke(new Tuple<bool, string>(true, CurrentProduct.Name));
+            });
+        }
+
+        /// <summary>
+        /// 获取当前产品ID
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetCurrentProductID(Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, "null"));
+                    return;
+                }
+                callback.Invoke(new Tuple<bool, string>(true, CurrentProduct.ID.ToString()));
+            });
+        }
+
+        /// <summary>
+        /// 获取速度
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetCurrentProductSpeed(Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null)
+                {
+                    return;
+                }
+                int power = CurrentProduct.Power ? 1 : 0;
+                int IsUserUpCamera = CurrentProduct.IsUserUpCamera ? 1 : 0;
+                callback.Invoke(new Tuple<bool, string>(true, $"{CurrentProduct.Speed},{CurrentProduct.Accel},{CurrentProduct.Speeds},{CurrentProduct.Accels},{power},{IsUserUpCamera}"));
+            });
+        }
+
+        /// <summary>
+        /// 获取所有的机器人点位
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetAllRobotPoints(Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+                {
+                    return;
+                }
+                StringBuilder sb = new StringBuilder();
+                foreach (var item in CurrentProduct.RobotPoint.Points)
+                {
+                    sb.Append($"{item.Number},{item.X.ToString("F3")},{item.Y.ToString("F3")},{item.Z.ToString("F3")},{item.U.ToString("F3")},{item.V.ToString("F3")},{item.W.ToString("F3")},{(int)item.Hand},{item.Local},{item.Tool},{item.RobotId.ToString()},");
+                }
+                callback.Invoke(new Tuple<bool, string>(true, $"{sb.ToString().TrimEnd(',')}"));
+            });
+        }
+
+        /// <summary>
+        /// 获取机器人点位数量
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetRobotPointsCount(Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+                {
+                    return;
+                }
+                if (CurrentProduct.RobotPoint.Points == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"0"));
+                }
+                else
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"{CurrentProduct.RobotPoint.Points.Count}"));
+                }
+            });
+        }
+
+        /// <summary>
+        /// 获取指定编号机器人点位
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetRobotPoint(int number, Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+                {
+                    return;
+                }
+                var pos = CurrentProduct.RobotPoint.Points.FirstOrDefault(p => p.Number == number);
+                if (pos == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"null"));
+                }
+                else
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"{pos.Number},{pos.X.ToString("F3")},{pos.Y.ToString("F3")},{pos.Z.ToString("F3")},{pos.U.ToString("F3")},{pos.V.ToString("F3")},{pos.W.ToString("F3")},{(int)pos.Hand},{pos.Local},{pos.Tool},{pos.RobotId.ToString()}"));
+                }
+            });
+        }
+
+        /// <summary>
+        /// 获取托盘数量
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetPalletsCount(Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+                {
+                    return;
+                }
+                if (CurrentProduct.RobotPoint.Pallets == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"0"));
+                }
+                else
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"{CurrentProduct.RobotPoint.Pallets.Count}"));
+                }
+            });
+        }
+
+        /// <summary>
+        /// 获取所有的托盘
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetAllPallet(Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+                {
+                    return;
+                }
+                StringBuilder sb = new StringBuilder();
+                foreach (var item in CurrentProduct.RobotPoint.Pallets)
+                {
+                    sb.Append($"{item.Name},{item.Row},{item.Column},{(int)item.Arrangement},{item.P0.X.ToString("F3")},{item.P0.Y.ToString("F3")},{item.P0.Z.ToString("F3")},{item.P0.U.ToString("F3")},{item.P0.V.ToString("F3")},{item.P0.W.ToString("F3")},{(int)item.P0.Hand},{item.P0.Local},{item.P0.Tool}," +
+                        $"{item.P1.X.ToString("F3")},{item.P1.Y.ToString("F3")},{item.P1.Z.ToString("F3")},{item.P1.U.ToString("F3")},{item.P1.V.ToString("F3")},{item.P1.W.ToString("F3")},{(int)item.P1.Hand},{item.P1.Local},{item.P1.Tool}," +
+                        $"{item.P2.X.ToString("F3")},{item.P2.Y.ToString("F3")},{item.P2.Z.ToString("F3")},{item.P2.U.ToString("F3")},{item.P2.V.ToString("F3")},{item.P2.W.ToString("F3")},{(int)item.P2.Hand},{item.P0.Local},{item.P2.Tool},");
+                }
+                callback.Invoke(new Tuple<bool, string>(true, $"{sb.ToString().TrimEnd(',')}"));
+            });
+        }
+
+        /// <summary>
+        /// 获取指定名称的托盘
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetPallet(string name, Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+                {
+                    return;
+                }
+                var pallet = CurrentProduct.RobotPoint.Pallets.FirstOrDefault(p => p.Name == name);
+                if (pallet == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"null"));
+                }
+                else
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"{pallet.Name},{pallet.Row},{pallet.Column},{(int)pallet.Arrangement},{pallet.P0.X.ToString("F3")},{pallet.P0.Y.ToString("F3")},{pallet.P0.Z.ToString("F3")},{pallet.P0.U.ToString("F3")},{pallet.P0.V.ToString("F3")},{pallet.P0.W.ToString("F3")},{(int)pallet.P0.Hand},{pallet.P0.Local},{pallet.P0.Tool}," +
+                        $"{pallet.P1.X.ToString("F3")},{pallet.P1.Y.ToString("F3")},{pallet.P1.Z.ToString("F3")},{pallet.P1.U.ToString("F3")},{pallet.P1.V.ToString("F3")},{pallet.P1.W.ToString("F3")},{(int)pallet.P1.Hand},{pallet.P1.Local},{pallet.P1.Tool}," +
+                        $"{pallet.P2.X.ToString("F3")},{pallet.P2.Y.ToString("F3")},{pallet.P2.Z.ToString("F3")},{pallet.P2.U.ToString("F3")},{pallet.P2.V.ToString("F3")},{pallet.P2.W.ToString("F3")},{(int)pallet.P2.Hand},{pallet.P0.Local},{pallet.P2.Tool}"));
+                }
+            });
+        }
+
+        /// <summary>
+        /// 获取夹具末端执行器数量
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetToolCount(string command, Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.CameraProcedures == null)
+                {
+                    return;
+                }
+                ProcedureModel procedure = null;
+                foreach (var cameraProcedures in CurrentProduct.CameraProcedures)
+                {
+                    procedure = cameraProcedures.ProcedureModels.FirstOrDefault(p => p.TriggerCommand == command);
+                    if (procedure != null) break;
+                }
+                if (procedure == null || procedure.ToolInfo == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"0"));
+                    return;
+                }
+                callback.Invoke(new Tuple<bool, string>(true, $"{procedure.ToolInfo.Count}"));
+            });
+        }
+
+        /// <summary>
+        /// 获取指定编号的夹具末端执行器参数
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetTool(string command, int index, Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.CameraProcedures == null)
+                {
+                    return;
+                }
+                ProcedureModel procedure = null;
+                foreach (var cameraProcedures in CurrentProduct.CameraProcedures)
+                {
+                    procedure = cameraProcedures.ProcedureModels.FirstOrDefault(p => p.TriggerCommand == command);
+                    if (procedure != null) break;
+                }
+                if (procedure == null || procedure.ToolInfo == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"null"));
+                    return;
+                }
+                var tool = procedure.ToolInfo[index];
+                callback.Invoke(new Tuple<bool, string>(true, $"{tool.Tool.Number},{tool.Tool.X.ToString("F3")},{tool.Tool.Y.ToString("F3")},{tool.OffsetX.ToString("F3")},{tool.OffsetY.ToString("F3")},{tool.OffsetZ.ToString("F3")},{tool.OffsetU.ToString("F3")}"));
+            });
+        }
+
+        /// <summary>
+        /// 获取流程参数
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetProcedureParam(string command, Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+                {
+                    return;
+                }
+
+                ProcedureModel procedure = null;
+                foreach (var cameraProcedures in CurrentProduct.CameraProcedures)
+                {
+                    procedure = cameraProcedures.ProcedureModels.FirstOrDefault(p => p.TriggerCommand == command);
+                    if (procedure != null) break;
+                }
+                if (procedure == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"null"));
+                    return;
+                }
+                callback.Invoke(new Tuple<bool, string>(true, $"{procedure.WaitSuction},{procedure.WaitBlow},{procedure.WaitPhoto}"));
+            });
+        }
+
+        /// <summary>
+        /// 获取指定名称托盘的指定编号的点坐标
+        /// </summary>
+        /// <param name="callback"></param>
+        /// <returns></returns>
+        private Task GetPalletPoint(string name, int index, Action<Tuple<bool, string>> callback)
+        {
+            return Task.Run(() =>
+            {
+                if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+                {
+                    return;
+                }
+                var pallet = CurrentProduct.RobotPoint.Pallets.FirstOrDefault(p => p.Name == name);
+                if (pallet == null)
+                {
+                    callback.Invoke(new Tuple<bool, string>(true, $"null"));
+                }
+                else
+                {
+                    PalletTool palletTool = new PalletTool(pallet);
+                    StringBuilder sb = new StringBuilder();
+                    callback.Invoke(new Tuple<bool, string>(true, $"{pallet.Name},{palletTool.Points.Count()},{index},{palletTool.Points[index].X.ToString("F3")},{palletTool.Points[index].Y.ToString("F3")},{palletTool.Points[index].Z.ToString("F3")}," +
+                        $"{palletTool.Points[index].U.ToString("F3")},{palletTool.Points[index].V.ToString("F3")},{palletTool.Points[index].W.ToString("F3")},{(int)(palletTool.Points[index].Hand)},{palletTool.Points[index].Local},{palletTool.Points[index].Tool}"));
+                }
+            });
+        }
+
+        /// <summary>
+        /// 执行Feeder振动集合
+        /// </summary>
+        /// <param name="feeder"></param>
+        /// <param name="works"></param>
+        /// <returns></returns>
+        public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
+        {
+            //执行配置的Feeder振动任务
+            if (feeder.FeederBrand == FeederBrand.AFAG)
+            {
+                foreach (var feederwork in works.FeederWorkList)
+                {
+                    if (feederwork.ConfigIndex < 0)
+                    {
+                        continue;
+                    }
+                    if (feederwork.ConfigIndex == 0)
+                    {
+                        await Task.Delay(feederwork.Duration);
+                    }
+                    else
+                    {
+                        ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
+                        ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
+                        ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
+                        await Task.Delay(feederwork.Duration);
+                        ((AfagFeeder)feeder).SetIntensity(0);
+                    }
+                    if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                    {
+                        return;
+                    }
+                }
+            }
+            else
+            {
+                foreach (var feederwork in works.FeederWorkList)
+                {
+                    if (feederwork.Function == VibrationFunction.Delay)
+                    {
+                        await Task.Delay(feederwork.Duration);
+                    }
+                    else
+                    {
+                        if (feederwork.SingleAction != null && isUpdateParame)
+                        {
+                            await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
+                        }
+
+                        await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
+                        await Task.Delay(feederwork.Duration);
+                    }
+                    if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                    {
+                        return;
+                    }
+                }
+            }
+        }
+
+        /// <summary>
+        /// 执行Feeder振动集合
+        /// </summary>
+        /// <param name="feeder"></param>
+        /// <param name="works"></param>
+        /// <returns></returns>
+        public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, bool isUpdateParame = true)
+        {
+            //执行配置的Feeder振动任务
+            if (feeder.FeederBrand == FeederBrand.AFAG)
+            {
+                foreach (var feederwork in works.FeederWorkList)
+                {
+                    if (feederwork.ConfigIndex < 0)
+                    {
+                        continue;
+                    }
+                    if (feederwork.ConfigIndex == 0)
+                    {
+                        await Task.Delay(feederwork.Duration);
+                    }
+                    else
+                    {
+                        ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
+                        ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
+                        ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
+                        await Task.Delay(feederwork.Duration);
+                        ((AfagFeeder)feeder).SetIntensity(0);
+                    }
+                }
+            }
+            else
+            {
+                foreach (var feederwork in works.FeederWorkList)
+                {
+                    if (feederwork.Function == VibrationFunction.Delay)
+                    {
+                        await Task.Delay(feederwork.Duration);
+                    }
+                    else
+                    {
+                        if (feederwork.SingleAction != null && isUpdateParame)
+                        {
+                            await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
+                        }
+
+                        await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
+                        await Task.Delay(feederwork.Duration);
+                    }
+                }
+            }
+        }
+
+        /// <summary>
+        /// 执行Feeder料仓供料及振动集合
+        /// </summary>
+        /// <param name="feeder"></param>
+        /// <param name="works"></param>
+        /// <returns></returns>
+        public async Task ExecuteFeederStockWorks(IVoiceCoilMotorFeeder feeder, FeederStockWorks works, bool isUpdateParame = true)
+        {
+            List<Task> tasks = new List<Task>();
+            if (feeder.FeederBrand == FeederBrand.AFAG)
+            {
+                tasks.Add(Task.Run(() =>
+                {
+                    if (works != null && works.FeederStockWorkList != null)
+                    {
+                        //执行配置的料仓振动任务
+                        foreach (var stockwork in works.FeederStockWorkList)
+                        {
+                            if (stockwork.RegisterIndex == 0)
+                            {
+                                Task.Delay(stockwork.Duration).Wait();
+                            }
+                            else if (stockwork.RegisterIndex == 1)
+                            {
+                                if (BgModbusTcpCommunicate != null)
+                                {
+                                    BgModbusTcpCommunicate.Slave.DataStore.HoldingRegisters[stockwork.Address] = 1;
+                                    Thread.Sleep(stockwork.Duration);
+                                    BgModbusTcpCommunicate.Slave.DataStore.HoldingRegisters[stockwork.Address] = 0;
+                                }
+                            }
+                        }
+                    }
+
+                }));
+                tasks.Add(Task.Run(() =>
+                {
+                    if (works != null && works.FeederWorkList != null)
+                    {
+                        //执行配置的Feeder振动任务
+                        foreach (var feederwork in works.FeederWorkList)
+                        {
+                            if (feederwork.ConfigIndex < 0)
+                            {
+                                continue;
+                            }
+                            if (feederwork.ConfigIndex == 0)
+                            {
+                                Thread.Sleep(feederwork.Duration);
+                            }
+                            else
+                            {
+                                ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
+                                ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
+                                ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
+                                Thread.Sleep(feederwork.Duration);
+                                ((AfagFeeder)feeder).SetIntensity(0);
+                            }
+                        }
+                    }
+                }));
+            }
+            else
+            {
+                tasks.Add(Task.Run(() =>
+                {
+                    if (works != null && works.FeederStockWorkList != null)
+                    {
+                        //执行配置的料仓振动任务
+                        foreach (var stockwork in works.FeederStockWorkList)
+                        {
+                            if (stockwork.Function == VibrationFunction.Delay)
+                            {
+                                Task.Delay(stockwork.Duration).Wait();
+                            }
+                            else
+                            {
+                                feeder.OutputAsync(((int)stockwork.Function) + 1, stockwork.Duration).Wait();
+                                Thread.Sleep(stockwork.Duration);
+                            }
+                        }
+                    }
+
+                }));
+                tasks.Add(Task.Run(() =>
+                {
+                    if (works != null && works.FeederWorkList != null)
+                    {
+                        //执行配置的Feeder振动任务
+                        foreach (var feederwork in works.FeederWorkList)
+                        {
+                            if (feederwork.Function == VibrationFunction.Delay)
+                            {
+                                Task.Delay(feederwork.Duration).Wait();
+                            }
+                            else
+                            {
+                                if (feederwork.SingleAction != null && isUpdateParame)
+                                {
+                                    feeder.SetShakeParameters((int)feederwork.Function, feederwork.SingleAction);
+                                }
+                                feeder.StartAction((int)feederwork.Function, feederwork.Duration).Wait();
+                                Thread.Sleep(feederwork.Duration);
+                            }
+                        }
+                    }
+                }));
+            }
+            await Task.WhenAll(tasks);
+        }
+
+        /// <summary>
+        /// 执行Feeder料仓供料及振动集合
+        /// </summary>
+        /// <param name="feeder"></param>
+        /// <param name="works"></param>
+        /// <returns></returns>
+        public async Task ExecuteFeederStockWorks(IVoiceCoilMotorFeeder feeder, FeederStockWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
+        {
+            List<Task> tasks = new List<Task>();
+            if (feeder.FeederBrand == FeederBrand.AFAG)
+            {
+                tasks.Add(Task.Run(() =>
+                {
+                    if (works != null && works.FeederStockWorkList != null)
+                    {
+                        //执行配置的料仓振动任务
+                        foreach (var stockwork in works.FeederStockWorkList)
+                        {
+                            if (stockwork.RegisterIndex == 0)
+                            {
+                                LogHelper.WriteLogDebug($"开启延时:{stockwork.Duration}ms");
+                                Thread.Sleep(stockwork.Duration);
+                                LogHelper.WriteLogDebug($"延时结束");
+                            }
+                            else if (stockwork.RegisterIndex == 1)
+                            {
+                                if (BgModbusTcpCommunicate != null)
+                                {
+                                    LogHelper.WriteLogDebug($"料仓开始震动:{stockwork.Duration}ms");
+                                    BgModbusTcpCommunicate.Slave.DataStore.HoldingRegisters[stockwork.Address] = 1;
+                                    Thread.Sleep(stockwork.Duration);
+                                    BgModbusTcpCommunicate.Slave.DataStore.HoldingRegisters[stockwork.Address] = 0;
+                                    LogHelper.WriteLogDebug($"料仓停止震动:{stockwork.Duration}ms");
+                                }
+                            }
+                            if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                            {
+                                return;
+                            }
+                        }
+                    }
+
+                }));
+                tasks.Add(Task.Run(() =>
+                {
+                    if (works != null && works.FeederWorkList != null)
+                    {
+                        //执行配置的Feeder振动任务
+                        foreach (var feederwork in works.FeederWorkList)
+                        {
+                            if (feederwork.ConfigIndex < 0)
+                            {
+                                continue;
+                            }
+                            if (feederwork.ConfigIndex == 0)
+                            {
+                                Thread.Sleep(feederwork.Duration);
+                            }
+                            else
+                            {
+                                ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
+                                ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
+                                ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
+                                Thread.Sleep(feederwork.Duration);
+                                ((AfagFeeder)feeder).SetIntensity(0);
+                            }
+                            if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                            {
+                                return;
+                            }
+                        }
+                    }
+                }));
+            }
+            else
+            {
+                tasks.Add(Task.Run(() =>
+                {
+                    if (works != null && works.FeederStockWorkList != null)
+                    {
+                        //执行配置的料仓振动任务
+                        foreach (var stockwork in works.FeederStockWorkList)
+                        {
+                            if (stockwork.Function == VibrationFunction.Delay)
+                            {
+                                Task.Delay(stockwork.Duration).Wait();
+                            }
+                            else
+                            {
+                                feeder.OutputAsync(((int)stockwork.Function) + 1, stockwork.Duration).Wait();
+                                Thread.Sleep(stockwork.Duration);
+                            }
+                            if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                            {
+                                return;
+                            }
+                        }
+                    }
+
+                }));
+                tasks.Add(Task.Run(() =>
+                {
+                    if (works != null && works.FeederWorkList != null)
+                    {
+                        //执行配置的Feeder振动任务
+                        foreach (var feederwork in works.FeederWorkList)
+                        {
+                            if (feederwork.Function == VibrationFunction.Delay)
+                            {
+                                Task.Delay(feederwork.Duration).Wait();
+                            }
+                            else
+                            {
+                                if (feederwork.SingleAction != null && isUpdateParame)
+                                {
+                                    feeder.SetShakeParameters((int)feederwork.Function, feederwork.SingleAction);
+                                }
+                                feeder.StartAction((int)feederwork.Function, feederwork.Duration).Wait();
+                                Thread.Sleep(feederwork.Duration);
+                            }
+                            if (cancellationToken != null && cancellationToken.IsCancellationRequested)
+                            {
+                                return;
+                            }
+                        }
+                    }
+                }));
+            }
+            await Task.WhenAll(tasks);
+        }
+
+        /// <summary>
+        /// 执行计时器
+        /// </summary>
+        /// <param name="state"></param>
+        /// <param name="callback"></param>
+        public void ExecuteCycleTime(string state, Action<Tuple<bool, string>> callback)
+        {
+            if (int.Parse(state) == 1)
+            {
+                IsStart = true;
+                StartTime = DateTime.Now;
+                callback.Invoke(new Tuple<bool, string>(true, $"1"));
+            }
+            else
+            {
+                IsStart = false;
+                callback.Invoke(new Tuple<bool, string>(true, $"0"));
+            }
+        }
+
+        /// <summary>
+        /// 生产计数
+        /// </summary>
+        /// <param name="_Content"></param>
+        /// <param name="callback"></param>
+        public void AddProductionRecords(string _Content, Action<Tuple<bool, string>> callback)
+        {
+            DatabaseHelper.AddProductProductionRecords(CurrentProduct.Name, _Content);
+            callback.Invoke(new Tuple<bool, string>(true, _Content));
+        }
+
+        /// <summary>
+        /// 获取产品的全局参数
+        /// </summary>
+        /// <param name="ParamName"></param>
+        /// <param name="index"></param>
+        /// <param name="callback"></param>
+        public void GetGlobalParam(string ParamName, int index, Action<Tuple<bool, string>> callback)
+        {
+            if (CurrentProduct == null || CurrentProduct.RobotPoint == null)
+            {
+                return;
+            }
+            var pos = CurrentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Name == ParamName);
+            if (pos == null)
+            {
+                callback.Invoke(new Tuple<bool, string>(true, $"null"));
+            }
+            else
+            {
+                switch (index)
+                {
+                    case 1:
+                        callback.Invoke(new Tuple<bool, string>(true, $"{pos.Name},{pos.Param1}"));
+                        break;
+                    case 2:
+                        callback.Invoke(new Tuple<bool, string>(true, $"{pos.Name},{pos.Param2}"));
+                        break;
+                    case 3:
+                        callback.Invoke(new Tuple<bool, string>(true, $"{pos.Name},{pos.Param3}"));
+                        break;
+                    case 4:
+                        callback.Invoke(new Tuple<bool, string>(true, $"{pos.Name},{pos.Param4}"));
+                        break;
+                    default:
+                        callback.Invoke(new Tuple<bool, string>(true, $"{pos.Name},{pos.Param1},{pos.Param2},{pos.Param3},{pos.Param4}"));
+                        break;
+                }
+            }
+        }
+        #endregion
+
+        #endregion
+
+        #region 机器人&Feeder&相机连接状态事件
+        /// <summary>
+        /// 机器人发送事件
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void Management_SendEvent(Guid robotid, object arg2, string arg3)
+        {
+            var r = DeviceConfig.Robots.FirstOrDefault(ro => ro.Id == robotid);
+            SendTaskMessage($"{r.RobotName}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_DisconnectedEvent(Guid robotid, object arg2, ClosedEventArgs arg3)
+        {
+            if (RobotTCPCollection.ContainsKey(robotid))
+            {
+                RobotTCPCollection[robotid].Cancel();
+            }
+            var r = DeviceConfig.Robots.FirstOrDefault(ro => ro.Id == robotid);
+            if (r.ConnectType == TCPConnectType.Server)
+            {
+                ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
+                SendTaskMessage($"{r.RobotName}[{socketClient.Id}:{socketClient.IP}]{Lang.断开连接}!", MessageLevel.Error);
+
+                var robot = this.RobotService.GetRobot(robotid);
+                if (robot.TcpService.Count < 1)
+                {
+                    var sta = Status.FirstOrDefault(s => s.ID == robotid);
+                    App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{r.RobotName}{Lang.未连接}";
+                             sta.Background = new SolidColorBrush(Colors.Red);
+                         }));
+
+                }
+            }
+            else
+            {
+                SendTaskMessage($"{r.RobotName}{Lang.断开连接}!", MessageLevel.Error);
+                var sta = Status.FirstOrDefault(s => s.ID == robotid);
+                App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{r.RobotName}{Lang.断开连接}";
+                             sta.Background = new SolidColorBrush(Colors.Red);
+                         }));
+
+            }
+        }
+
+        /// <summary>
+        /// 机器人连接成功时
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void Management_ConnectedEvent(Guid robotid, object arg2, ConnectedEventArgs arg3)
+        {
+            var r = DeviceConfig.Robots.FirstOrDefault(ro => ro.Id == robotid);
+            if (r.ConnectType == TCPConnectType.Server)
+            {
+                ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
+                SendTaskMessage($"{r.RobotName}[{socketClient.Id}:{socketClient.IP}]{Lang.已连接}!", MessageLevel.Debug);
+
+                var robot = this.RobotService.GetRobot(robotid);
+                if (robot.TcpService.Count > 0)
+                {
+                    var sta = Status.FirstOrDefault(s => s.ID == robotid);
+                    App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{r.RobotName}{Lang.已连接}";
+                             sta.Background = new SolidColorBrush(Colors.Green);
+                         }));
+
+                }
+            }
+            else
+            {
+                SendTaskMessage($"{r.RobotName}{Lang.已连接}!", MessageLevel.Debug);
+                var sta = Status.FirstOrDefault(s => s.ID == robotid);
+                App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{r.RobotName}{Lang.已连接}";
+                             sta.Background = new SolidColorBrush(Colors.Green);
+                         }));
+
+            }
+        }
+
+        /// <summary>
+        /// Feeder断开连接时
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void Management_FeederDisconnectedEvent(Guid feederid, ITcpClient arg2, ClosedEventArgs arg3)
+        {
+            var f = DeviceConfig.Feeders.FirstOrDefault(ro => ro.Id == feederid);
+            var sta = Status.FirstOrDefault(s => s.ID == feederid);
+            App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{f.FeederName}{Lang.未连接}";
+                             sta.Background = new SolidColorBrush(Colors.Red);
+                         }));
+
+            SendTaskMessage($"{f.FeederName}{Lang.断开连接}!", MessageLevel.Error);
+        }
+
+        /// <summary>
+        /// Feeder连接成功时
+        /// </summary>
+        /// <param name="arg1"></param>
+        /// <param name="arg2"></param>
+        /// <param name="arg3"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        private void Management_FeederConnectedEvent(Guid feederid, ITcpClient arg2, ConnectedEventArgs arg3)
+        {
+            var f = DeviceConfig.Feeders.FirstOrDefault(ro => ro.Id == feederid);
+            var sta = Status.FirstOrDefault(s => s.ID == feederid);
+            App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{f.FeederName}{Lang.已连接}";
+                             sta.Background = new SolidColorBrush(Colors.Green);
+                         }));
+
+            SendTaskMessage($"{f.FeederName}{Lang.已连接}!", MessageLevel.Debug);
+        }
+
+        /// <summary>
+        /// 相机连接或者断开时
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="state"></param>
+        private void Management_CameraConnectChangedEvent(Guid id, bool state)
+        {
+            var sta = Status.FirstOrDefault(s => s.ID == id);
+            var camera = DeviceConfig.Cameras.FirstOrDefault(c => c.Id == id);
+            if (sta != null && camera != null)
+            {
+                if (state)
+                {
+                    App.Current.Dispatcher.Invoke(new Action(() =>
+                    {
+                        sta.Message = $"{camera.CameraName}{Lang.已连接}";
+                        sta.Background = new SolidColorBrush(Colors.Green);
+                    }));
+
+                }
+                else
+                {
+                    App.Current.Dispatcher.Invoke(new Action(() =>
+                    {
+                        sta.Message = $"{camera.CameraName}{Lang.断开连接}";
+                        sta.Background = new SolidColorBrush(Colors.Red);
+                    }));
+                }
+            }
+        }
+
+        /// <summary>
+        /// PLC连接状态改变事件
+        /// </summary>
+        /// <param name="plc"></param>
+        /// <param name="isconnected"></param>
+        private void Management_PlcConnectChangedEvent(object sender, bool isconnected)
+        {
+            IPlc plc = sender as IPlc;
+            var sta = Status.FirstOrDefault(s => s.ID == plc.Id);
+            if (plc.IsConnected)
+            {
+                SendTaskMessage($"{plc.Name}{Lang.已连接}!", MessageLevel.Debug);
+                if (sta == null) return;
+                App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{plc.Name}{Lang.已连接}";
+                             sta.Background = new SolidColorBrush(Colors.Green);
+                         }));
+            }
+            else
+            {
+                SendTaskMessage($"{plc.Name}{Lang.断开连接}!", MessageLevel.Error);
+                if (sta == null) return;
+                App.Current.Dispatcher.Invoke(new
+                         Action(() =>
+                         {
+                             sta.Message = $"{plc.Name}{Lang.未连接}";
+                             sta.Background = new SolidColorBrush(Colors.Red);
+                         }));
+            }
+        }
+        #endregion
+
+        #region 后台服务器通讯事件
+        private void BgCommunicate_SendEvent(ITcpSessionClient client, string msg)
+        {
+            SendTaskMessage($"{Lang.服务器}[{client.ServicePort}] Send To {Lang.客户端}[{client.Id}:{client.IP}]:{msg}", MessageLevel.Info);
+        }
+
+        public Dictionary<string, CancellationTokenSource> BgCommunicateollection = new Dictionary<string, CancellationTokenSource>();
+        private async void BgCommunicate_ReceivedEvent(ITcpSessionClient client, string msg)
+        {
+
+            try
+            {
+                if (!BgCommunicateollection.ContainsKey(client.Id))
+                {
+                    BgCommunicateollection.Add(client.Id, new CancellationTokenSource());
+                }
+
+                SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]ReceiveFor{Lang.客户端}[{client.Id}:{client.IP}]:{msg}", MessageLevel.Info);
+                Task.Run(async () =>
+                {
+                    try
+                    {
+                        await ExecuteRemoteCommand(msg, async result =>
+                        {
+                            try
+                            {
+                                if (!client.Online)
+                                {
+                                    return;
+                                }
+                                if (result.Item1)
+                                {
+                                    if (result.Item2.Length > 1)
+                                    {
+                                        foreach (var item in result.Item2)
+                                        {
+                                            await BgCommunicate.SendAsync(client, $"{item}");
+                                            await Task.Delay(10);
+                                        }
+                                    }
+                                    else
+                                    {
+                                        await BgCommunicate.SendAsync(client, $"{result.Item2[0]}");
+                                    }
+                                }
+                            }
+                            catch (Exception ex)
+                            {
+                                LogHelper.WriteLogError("后台TCP发送数据时出错!", ex);
+                                SendTaskMessage(ex.Message, MessageLevel.Alarm);
+                            }
+
+                        }, BgCommunicateollection[client.Id].Token);
+                    }
+                    catch (Exception ex)
+                    {
+                        LogHelper.WriteLogError("处理后台服务器接收的命令时出错!", ex);
+                        SendTaskMessage(ex.Message, MessageLevel.Alarm);
+                    }
+                });
+
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("处理后台服务器接收的命令时出错!", ex);
+                SendTaskMessage(ex.Message, MessageLevel.Alarm);
+            }
+        }
+
+        private void BgCommunicate_DisconnectedEvent(ITcpSessionClient client, ClosedEventArgs e)
+        {
+            SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.断开连接}!", MessageLevel.Alarm);
+            if (BgCommunicateollection.ContainsKey(client.Id))
+            {
+                BgCommunicateollection[client.Id].Cancel();
+            }
+        }
+
+        private void BgCommunicate_ConnectedEvent(ITcpSessionClient client, ConnectedEventArgs e)
+        {
+            SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.连接成功}!", MessageLevel.Debug);
+        }
+        #endregion
+
+
+
+        #region Eip
+
+        private void DisposeRfidClient()
+        {
+            try
+            {
+                if (BgEipCommunicate != null)
+                {
+                    BgEipCommunicate.OnTagDataReceived -= RfidClient_OnTagDataReceived;
+                    BgEipCommunicate.OnConnectReceive -= Management_EipConnectChangedEvent;
+                    BgEipCommunicate.Dispose();
+                }
+                UpdateEthernetIpStatus(false);
+            }
+            catch { /* ignore */ }
+            finally
+            {
+                BgEipCommunicate = null;
+                
+            }
+        }
+
+        private void RfidClient_OnTagDataReceived(object sender, RFIDTagDataEventArgs e)
+        {
+            if (e == null || e.Tags == null || e.Tags.Count == 0)
+                return;
+
+            foreach (var tag in e.Tags)
+            {
+                lock (_sync)
+                    _lastRfidTag = CloneTag(tag);
+
+                SendTaskMessage("RFID 端口" + tag.Port + " Hex=" + tag.ToHexString(), MessageLevel.Debug);
+            }
+        }
+
+        private void StopHandshakeLoop()
+        {
+            try
+            {
+                if (_handshakeCts != null)
+                {
+                    _handshakeCts.Cancel();
+                    try
+                    {
+                        if (_handshakeTask != null)
+                            _handshakeTask.Wait(2000);
+                    }
+                    catch (AggregateException) { /* ignore */ }
+                    _handshakeCts.Dispose();
+                }
+            }
+            catch { /* ignore */ }
+            finally
+            {
+                _handshakeCts = null;
+                _handshakeTask = null;
+            }
+        }
+        #endregion
+
+        #region 方法
+
+        private void SendTaskMessage(string msg, MessageLevel level)
+        {
+            _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
+        }
+
+        private void DoCycleTime(object state)
+        {
+            if (IsStart)
+            {
+                App.Current.Dispatcher.Invoke(new Action(() =>
+                {
+                    CT = DateTime.Now - StartTime;
+                }));
+            }
+        }
+
+        private void DoYieldTime(object state)
+        {
+            if (CurrentProduct == null) return;
+            TotalQuantity = DatabaseHelper.GetTotalQuantity(CurrentProduct.Name);
+            TotalQuantityToday = DatabaseHelper.GetTotalQuantityToday(CurrentProduct.Name);
+            CurrentUPH = DatabaseHelper.GetUPH(CurrentProduct.Name);
+        }
+        #region vm启动检测
+
+        /// <summary>
+        /// 杀死所有VM有关进程
+        /// </summary>
+        public void KillVMProcess()
+        {
+            KillProcess("VisionMasterServerApp");
+            KillProcess("VisionMaster");
+            KillProcess("VmModuleProxy.exe");
+            KillProcess("vServerApp.exe");
+        }
+
+        /// <summary>
+        /// 杀死指定进程名的进程
+        /// </summary>
+        /// <param name="strKillName"></param>
+        public void KillProcess(string strKillName)
+        {
+            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
+            {
+                if (p.ProcessName.Contains(strKillName))
+                {
+                    try
+                    {
+                        p.Kill();
+                        p.WaitForExit();
+                    }
+                    catch (Exception ex)
+                    {
+                        LogHelper.WriteLogError($"杀死进程:{strKillName}时失败!", ex);
+                    }
+                }
+            }
+        }
+        #endregion
+
+        #endregion
+    }
+}

+ 518 - 0
TeamAAS-VM/Core/ModbusTcpMasterCommunicate.cs

@@ -0,0 +1,518 @@
+using Modbus.Device;
+using Prism.Events;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Net.Sockets;
+using System.Threading;
+using System.Threading.Tasks;
+using TeamAAS_VP.Events;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.Core
+{
+    /// <summary>
+    /// Modbus TCP 主站:轮询 MDC V2 电批,锁付过程中累积实时曲线,完成后推送结果
+    /// 地址默认值参考 MDC V2 Appendix A(Input Register 功能码 0x04)
+    /// </summary>
+    public class ModbusTcpMasterCommunicate : IDisposable
+    {
+        // MDC V2 事件数据区起始地址(3201~3213 一次读完,保证结果一致性)
+        private const ushort MdcEventDataStartAddress = 3201;
+        private const int MdcEventDataRegisterCount = 13;
+
+        private readonly ModbusTcpMasterConfig _config;
+        private readonly object _masterLock = new object();
+        private readonly IEventAggregator _eventAggregator;
+
+        private TcpClient _tcpClient;
+        private IModbusMaster _master;
+        private CancellationTokenSource _pollCts;
+
+        // 轮询状态
+        private bool _lastFinishComplete;
+        private bool _lastLockInProgress;
+        private int _lastWaveCount;
+        /// <summary>本次锁付周期内是否检测到 Motor RUN,防止启动时误触发完成事件</summary>
+        private bool _finishArmed;
+
+        // 实时累积波形(MDC 无波形缓冲区,靠轮询 3300/3301 累积)
+        private readonly List<WaveData> _accumulatedWave = new List<WaveData>();
+        private DateTime _lockStartTime = DateTime.Now;
+        private double _accumulatedTurns;
+
+        public ModbusTcpMasterConfig Config { get { return _config; } }
+        public bool IsEnabled { get { return _config.IsEnabled; } }
+        public bool IsConnected { get; private set; }
+
+        public ModbusTcpMasterCommunicate(ModbusTcpMasterConfig config, IEventAggregator eventAggregator)
+        {
+            _config = config;
+            _eventAggregator = eventAggregator;
+        }
+
+        public void Start()
+        {
+            if (!_config.IsEnabled)
+            {
+                return;
+            }
+
+            Connect();
+            SyncInitialPollState();
+            _pollCts = new CancellationTokenSource();
+            Task.Run(() => PollLoop(_pollCts.Token));
+        }
+
+        public void Stop()
+        {
+            if (_pollCts != null)
+            {
+                _pollCts.Cancel();
+                _pollCts.Dispose();
+                _pollCts = null;
+            }
+            Disconnect();
+        }
+
+        public void Dispose()
+        {
+            Stop();
+        }
+
+        #region 连接
+
+        private void Connect()
+        {
+            Disconnect();
+            _tcpClient = new TcpClient();
+            _tcpClient.Connect(_config.IP, _config.Port);
+            _master = ModbusIpMaster.CreateIp(_tcpClient);
+            _master.Transport.ReadTimeout = 3000;
+            _master.Transport.WriteTimeout = 3000;
+            IsConnected = true;
+        }
+
+        private void Disconnect()
+        {
+            IsConnected = false;
+            if (_master != null)
+            {
+                _master.Dispose();
+                _master = null;
+            }
+            if (_tcpClient != null)
+            {
+                _tcpClient.Close();
+                _tcpClient = null;
+            }
+        }
+
+        private bool TryReconnect()
+        {
+            try
+            {
+                Connect();
+                SyncInitialPollState();
+                return true;
+            }
+            catch (Exception ex)
+            {
+                IsConnected = false;
+                LogHelper.WriteLogError("Modbus TCP 主站重连失败", ex);
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// 连接/启动时同步电批当前状态,避免 3212 仍为「完成」时误触发锁付完成
+        /// </summary>
+        private void SyncInitialPollState()
+        {
+            _lastFinishComplete = ReadFinishComplete();
+            _lastLockInProgress = ReadLockInProgress();
+            _finishArmed = false;
+            _lastWaveCount = 0;
+            ClearAccumulatedWave();
+        }
+
+        #endregion
+
+        #region 轮询
+
+        private void PollLoop(CancellationToken token)
+        {
+            while (!token.IsCancellationRequested)
+            {
+                try
+                {
+                    PollOnce();
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("Modbus TCP 主站轮询出错", ex);
+                    Disconnect();
+                    Thread.Sleep(2000);
+                    TryReconnect();
+                }
+
+                Thread.Sleep(Math.Max(10, _config.PollIntervalMs));
+            }
+        }
+
+        private void PollOnce()
+        {
+            if (!IsConnected)
+            {
+                TryReconnect();
+                return;
+            }
+
+            bool isLocking = ReadLockInProgress();
+            bool finishComplete = ReadFinishComplete();
+
+            HandleLockStartEdge(isLocking);
+
+            if (isLocking)
+            {
+                AppendRealtimeWavePoint();
+            }
+
+            bool needCurve = isLocking || finishComplete;
+            if (!needCurve)
+            {
+                ResetPollStateIfIdle();
+                return;
+            }
+
+            List<WaveData> waveDatas = GetCurrentWaveDatas();
+            PublishCurveUpdateIfChanged(waveDatas, finishComplete);
+
+            // 必须:先检测到 Motor RUN(_finishArmed),再检测 3212 上升沿,才推送完成
+            if (finishComplete && !_lastFinishComplete && _finishArmed)
+            {
+                PublishLockFinish(waveDatas);
+                ClearAccumulatedWave();
+                _finishArmed = false;
+            }
+
+            _lastFinishComplete = finishComplete;
+            _lastLockInProgress = isLocking;
+        }
+
+        /// <summary>检测到锁付开始时清空累积曲线并允许后续完成判定</summary>
+        private void HandleLockStartEdge(bool isLocking)
+        {
+            if (!isLocking || _lastLockInProgress)
+            {
+                return;
+            }
+
+            ClearAccumulatedWave();
+            _lockStartTime = DateTime.Now;
+            _finishArmed = true;
+            _lastWaveCount = 0;
+        }
+
+        private void ResetPollStateIfIdle()
+        {
+            _lastFinishComplete = false;
+            _lastLockInProgress = false;
+            _finishArmed = false;
+            _lastWaveCount = 0;
+            ClearAccumulatedWave();
+        }
+
+        private void ClearAccumulatedWave()
+        {
+            _accumulatedWave.Clear();
+            _accumulatedTurns = 0;
+        }
+
+        private List<WaveData> GetCurrentWaveDatas()
+        {
+            if (_config.WaveDataMode == WaveDataSourceMode.RegisterBlock)
+            {
+                return ReadWaveDatasFromRegisters();
+            }
+            return new List<WaveData>(_accumulatedWave);
+        }
+
+        private void PublishCurveUpdateIfChanged(List<WaveData> waveDatas, bool finishComplete)
+        {
+            // 完成态已处理过则不再刷曲线,避免 3212 保持为 1 时反复推送空曲线
+            if (finishComplete && _lastFinishComplete)
+            {
+                return;
+            }
+
+            int waveCount = waveDatas.Count;
+            if (waveCount == _lastWaveCount && !finishComplete)
+            {
+                return;
+            }
+
+            _lastWaveCount = waveCount;
+            _eventAggregator.GetEvent<LockCurveUpdateNotification>().Publish(waveDatas);
+        }
+
+        private void PublishLockFinish(List<WaveData> waveDatas)
+        {
+            LockResult result = BuildLockResult(waveDatas);
+            result.LockCurveImagePath = BuildLockCurveImagePath(result.Timestamp);
+            result.CurveCsvPath = BuildLockCurveCsvPath(result.Timestamp);
+            _eventAggregator.GetEvent<LockFinishNotification>().Publish(result);
+        }
+
+        #endregion
+
+        #region MDC 实时波形累积
+
+        /// <summary>
+        /// 锁付进行中:读取 3300 扭矩、3301 转速,累积为曲线点
+        /// </summary>
+        private void AppendRealtimeWavePoint()
+        {
+            float torque = ReadScaledTorque(_config.RealtimeTorqueAddress);
+            float speed = ReadRegister(_config.RealtimeSpeedAddress);
+            double intervalSec = _config.PollIntervalMs / 1000.0;
+            _accumulatedTurns += (speed / 60.0) * intervalSec;
+
+            _accumulatedWave.Add(new WaveData
+            {
+                Torque = torque,
+                Speed = speed,
+                Turns = _accumulatedTurns,
+                Time = (DateTime.Now - _lockStartTime).TotalSeconds
+            });
+        }
+
+        #endregion
+
+        #region 寄存器读取
+
+        private bool ReadLockInProgress()
+        {
+            if (_config.LockInProgressAddress == 0)
+            {
+                return false;
+            }
+
+            // MDC:3307 Motor RUN = 1 表示正在锁付
+            return ReadRegister(_config.LockInProgressAddress) == _config.LockInProgressActiveValue;
+        }
+
+        /// <summary>MDC 3212:1=完成,2=NG,均视为锁付结束</summary>
+        private bool ReadFinishComplete()
+        {
+            ushort status = ReadRegister(_config.FinishFlagAddress);
+            return status == _config.FinishFlagCompleteValue
+                || status == _config.FinishFlagNgValue;
+        }
+
+        /// <summary>
+        /// 组装锁付结果。优先批量读取 MDC 3201~3213 事件区,保证各字段同一时刻快照。
+        /// </summary>
+        private LockResult BuildLockResult(List<WaveData> waveDatas)
+        {
+            if (TryReadMdcEventBlock(out ushort durationMs, out ushort presetNo, out ushort torqueRaw,
+                out ushort status, out ushort snugAngle))
+            {
+                return CreateLockResult(waveDatas, durationMs, presetNo, torqueRaw, status, snugAngle);
+            }
+
+            // 非标准地址布局:逐寄存器读取
+            ushort fallbackStatus = ReadRegister(_config.FinishFlagAddress);
+            return CreateLockResult(
+                waveDatas,
+                ReadRegister(_config.LockDurationAddress),
+                ReadRegister(_config.ProgramNumberAddress),
+                ReadRegister(_config.LockTorqueAddress),
+                fallbackStatus,
+                ReadRegister(_config.LockTurnsAddress));
+        }
+
+        private LockResult CreateLockResult(
+            List<WaveData> waveDatas,
+            ushort durationRaw,
+            ushort presetNo,
+            ushort torqueRaw,
+            ushort status,
+            ushort turnsRaw)
+        {
+            // MDC 3212:1=OK,2=NG(以事件 Status 为准,比 3305 实时位更可靠)
+            bool lockPassed = status == _config.FinishFlagCompleteValue;
+
+            float durationSec = _config.LockDurationIsMilliseconds
+                ? durationRaw / 1000f
+                : durationRaw;
+
+            float lockTurns = _config.TurnsScaleFactor > 0
+                ? turnsRaw / _config.TurnsScaleFactor
+                : turnsRaw;
+
+            float lockTorque = _config.TorqueScaleFactor > 0
+                ? torqueRaw / _config.TorqueScaleFactor
+                : torqueRaw;
+
+            return new LockResult
+            {
+                Timestamp = DateTime.Now,
+                LockTurns = lockTurns,
+                LockTorque = lockTorque,
+                LockDuration = durationSec,
+                LockPassed = lockPassed,
+                ScrewdriverProgramNumber = presetNo,
+                WaveDatas = waveDatas
+            };
+        }
+
+        /// <summary>
+        /// 一次读取 MDC 事件数据块 3201~3213(说明书 Appendix A,功能码 0x04)
+        /// </summary>
+        private bool TryReadMdcEventBlock(
+            out ushort durationMs,
+            out ushort presetNo,
+            out ushort torqueRaw,
+            out ushort status,
+            out ushort snugAngle)
+        {
+            durationMs = presetNo = torqueRaw = status = snugAngle = 0;
+
+            if (!_config.UseInputRegisters || !IsStandardMdcEventLayout())
+            {
+                return false;
+            }
+
+            ushort[] block = ReadRegisters(MdcEventDataStartAddress, MdcEventDataRegisterCount);
+            if (block == null || block.Length < MdcEventDataRegisterCount)
+            {
+                return false;
+            }
+
+            // 相对 3201 的偏移:3201=0, 3202=1, 3204=3, 3212=11, 3213=12
+            durationMs = block[0];
+            presetNo = block[1];
+            torqueRaw = block[3];
+            status = block[11];
+            snugAngle = block[12];
+            return true;
+        }
+
+        /// <summary>判断配置是否为 MDC V2 标准事件区地址布局</summary>
+        private bool IsStandardMdcEventLayout()
+        {
+            return _config.LockDurationAddress == 3201
+                && _config.ProgramNumberAddress == 3202
+                && _config.LockTorqueAddress == 3204
+                && _config.FinishFlagAddress == 3212
+                && _config.LockTurnsAddress == 3213;
+        }
+
+        /// <summary>RegisterBlock 模式:从连续寄存器块批量读波形</summary>
+        private List<WaveData> ReadWaveDatasFromRegisters()
+        {
+            int pointCount = ReadRegister(_config.WaveDataCountAddress);
+            if (pointCount <= 0)
+            {
+                return new List<WaveData>();
+            }
+
+            pointCount = Math.Min(pointCount, _config.MaxWavePoints);
+            int totalRegisters = pointCount * _config.WavePointRegisterCount;
+            ushort[] registers = ReadRegisters(_config.WaveDataStartAddress, totalRegisters);
+
+            List<WaveData> waveDatas = new List<WaveData>(pointCount);
+            for (int i = 0; i < pointCount; i++)
+            {
+                waveDatas.Add(ParseWavePointFromBlock(registers, i * _config.WavePointRegisterCount));
+            }
+            return waveDatas;
+        }
+
+        private WaveData ParseWavePointFromBlock(ushort[] registers, int baseOffset)
+        {
+            return new WaveData
+            {
+                Turns = ReadFloatFromRegisters(registers, baseOffset + 0),
+                Torque = ReadFloatFromRegisters(registers, baseOffset + 2),
+                LockAngle = ReadFloatFromRegisters(registers, baseOffset + 4),
+                Speed = ReadFloatFromRegisters(registers, baseOffset + 6),
+                Slopes = ReadFloatFromRegisters(registers, baseOffset + 8),
+                Time = ReadFloatFromRegisters(registers, baseOffset + 10)
+            };
+        }
+
+        private float ReadScaledTorque(ushort address)
+        {
+            return ScaleTorque(ReadRegister(address));
+        }
+
+        private float ScaleTorque(ushort raw)
+        {
+            if (_config.TorqueScaleFactor <= 0)
+            {
+                return raw;
+            }
+            return raw / _config.TorqueScaleFactor;
+        }
+
+        private ushort ReadRegister(ushort address)
+        {
+            lock (_masterLock)
+            {
+                if (_config.UseInputRegisters)
+                {
+                    return _master.ReadInputRegisters(_config.SlaveID, address, 1)[0];
+                }
+                return _master.ReadHoldingRegisters(_config.SlaveID, address, 1)[0];
+            }
+        }
+
+        private ushort[] ReadRegisters(ushort startAddress, int count)
+        {
+            lock (_masterLock)
+            {
+                if (_config.UseInputRegisters)
+                {
+                    return _master.ReadInputRegisters(_config.SlaveID, startAddress, (ushort)count);
+                }
+                return _master.ReadHoldingRegisters(_config.SlaveID, startAddress, (ushort)count);
+            }
+        }
+
+        private static float ReadFloatFromRegisters(ushort[] registers, int index)
+        {
+            if (registers == null || index + 1 >= registers.Length)
+            {
+                return 0f;
+            }
+            byte[] bytes = new byte[4];
+            BitConverter.GetBytes(registers[index + 1]).CopyTo(bytes, 0);
+            BitConverter.GetBytes(registers[index + 0]).CopyTo(bytes, 2);
+            return BitConverter.ToSingle(bytes, 0);
+        }
+
+        private string BuildLockCurveImagePath(DateTime timestamp)
+        {
+            string folder = _config.LockCurveImageFolder;
+            if (!Directory.Exists(folder))
+            {
+                Directory.CreateDirectory(folder);
+            }
+            return Path.Combine(folder, $"LockCurve_{timestamp:yyyyMMdd_HHmmss_fff}.png");
+        }
+
+        private string BuildLockCurveCsvPath(DateTime timestamp)
+        {
+            string folder = Path.Combine(_config.LockCurveImageFolder, "Csv");
+            if (!Directory.Exists(folder))
+            {
+                Directory.CreateDirectory(folder);
+            }
+            return Path.Combine(folder, $"LockCurve_{timestamp:yyyyMMdd_HHmmss_fff}.csv");
+        }
+
+        #endregion
+    }
+}

+ 66 - 0
TeamAAS-VM/Core/PLCs/MitsubishiMcPLC.cs

@@ -0,0 +1,66 @@
+using OpcUaHelper;
+using System;
+using System.Threading.Tasks;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.Core.PLCs
+{
+    /// <summary>
+    /// 三菱 MC 协议 PLC,封装 <see cref="MitsubishiPLC"/> 并实现 <see cref="IPlc"/> 供 PlcService 统一管理。
+    /// </summary>
+    public class MitsubishiMcPLC : IPlc
+    {
+        public MitsubishiPLC Client { get; private set; }
+
+        public Guid Id { get; private set; }
+
+        public CommunicationType CommunicationType { get; private set; }
+
+        public string EndpointUrl { get; private set; }
+
+        public string Name { get; private set; }
+
+        public OpcUaClient OpcUaClient => null;
+
+        public bool IsConnected => Client != null && Client.IsConnected;
+
+        public event Action<object, bool> ConnectChangedEvent;
+
+        public MitsubishiMcPLC(PlcInfo plcInfo)
+        {
+            if (plcInfo == null)
+                throw new ArgumentNullException(nameof(plcInfo));
+
+            Id = plcInfo.Id;
+            Name = plcInfo.Name;
+            CommunicationType = plcInfo.CommunicationType;
+            EndpointUrl = plcInfo.PlcIp + ":" + plcInfo.PlcPort;
+            Client = new MitsubishiPLC(plcInfo.PlcIp, plcInfo.PlcPort);
+            Client.ConnectionLost += () => ConnectChangedEvent?.Invoke(this, false);
+        }
+
+        public void Connect()
+        {
+            bool connected = Client.Connect();
+            ConnectChangedEvent?.Invoke(this, connected);
+        }
+
+        public Task ConnectAsync()
+        {
+            return Task.Run(Connect);
+        }
+
+        public void Disconnect()
+        {
+            Client.Disconnect();
+            ConnectChangedEvent?.Invoke(this, false);
+        }
+
+        public void Dispose()
+        {
+            Client.Dispose();
+        }
+    }
+}

+ 994 - 0
TeamAAS-VM/Core/PLCs/MitsubishiPLC.cs

@@ -0,0 +1,994 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Sockets;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using TeamAAS_VP.Core.RFID;
+
+namespace TeamAAS_VP.Core.PLCs
+{
+    /// <summary>
+    /// 三菱 PLC MC 协议客户端(3E 帧 / 二进制 / TCP)
+    /// 适用于 Q/L/iQ-R/FX5 等系列以太网通讯
+    /// </summary>
+    public class MitsubishiPLC : IDisposable
+    {
+        // 3E 帧副头部 + 访问路径固定 9 字节,其后才是「数据长度」字段指定的内容
+        private const int McHeaderLength = 9;
+
+        private TcpClient _client;
+        private NetworkStream _stream;
+        private readonly object _sync = new object();
+
+        public string IpAddress { get; }
+        public int Port { get; }
+        public byte NetworkNo { get; set; } = 0x00;
+        public byte PcNo { get; set; } = 0xFF;
+        public ushort IoModuleNo { get; set; } = 0x03FF;
+        public byte StationNo { get; set; } = 0x00;
+        public int TimeoutMs { get; set; } = 3000;
+
+        public event Action<string> OnLog;
+        public event Action ConnectionLost;
+
+        public bool IsConnected => _client != null && _client.Connected;
+
+        public MitsubishiPLC(string ipAddress, int port = 5000)
+        {
+            IpAddress = ipAddress;
+            Port = port;
+        }
+
+        public bool Connect()
+        {
+            try
+            {
+                Disconnect();
+
+                _client = new TcpClient();
+                _client.NoDelay = true;
+                _client.ReceiveTimeout = TimeoutMs;
+                _client.SendTimeout = TimeoutMs;
+                _client.Connect(IpAddress, Port);
+                _stream = _client.GetStream();
+                _stream.ReadTimeout = TimeoutMs;
+                _stream.WriteTimeout = TimeoutMs;
+
+                OnLog?.Invoke("已连接三菱 PLC (" + IpAddress + ":" + Port + ")");
+                return true;
+            }
+            catch (Exception ex)
+            {
+                OnLog?.Invoke("连接 PLC 失败: " + ex.Message);
+                Disconnect();
+                return false;
+            }
+        }
+
+        public void Disconnect()
+        {
+            try
+            {
+                if (_stream != null)
+                    _stream.Close();
+                if (_client != null)
+                    _client.Close();
+            }
+            catch
+            {
+                // ignore cleanup errors
+            }
+            finally
+            {
+                _stream = null;
+                _client = null;
+            }
+        }
+
+        /// <summary>
+        /// 读 Ready 位(PLC→PC 请求读卡)。未配置则抛异常。
+        /// </summary>
+        public bool ReadReadyBit(PlcRfidMapping mapping)
+        {
+            if (mapping == null)
+                throw new ArgumentNullException(nameof(mapping));
+            if (!IsDeviceEnabled(mapping.ReadyBitDevice))
+                throw new InvalidOperationException("Ready 位未配置(不能为 0)");
+
+            lock (_sync)
+                return ReadBit(mapping.ReadyBitDevice);
+        }
+
+        /// <summary>
+        /// 读 PLC 指定的读写头端口号。
+        /// </summary>
+        public int ReadRequestPort(PlcRfidMapping mapping)
+        {
+            if (mapping == null)
+                throw new ArgumentNullException(nameof(mapping));
+            if (!IsDeviceEnabled(mapping.PortDevice))
+                throw new InvalidOperationException("端口寄存器未配置(不能为 0)");
+
+            lock (_sync)
+            {
+                short[] words = ReadWords(mapping.PortDevice, 1);
+                return words[0];
+            }
+        }
+
+        /// <summary>
+        /// 读卡成功:写数据到起始地址,置 OK=1、NG=0。
+        /// </summary>
+        public void WriteReadSuccess(PlcRfidMapping mapping, RFIDTagData tag)
+        {
+            if (mapping == null)
+                throw new ArgumentNullException(nameof(mapping));
+            if (tag == null || tag.Data == null || tag.Data.Length == 0)
+                throw new ArgumentException("标签数据无效");
+            if (tag.Data.Length > mapping.MaxDataBytes)
+                throw new ArgumentException("RFID 数据长度 " + tag.Data.Length + " 超过上限 " + mapping.MaxDataBytes);
+            if (!IsDeviceEnabled(mapping.DataStartDevice))
+                throw new ArgumentException("数据起始寄存器未配置");
+
+            lock (_sync)
+            {
+                if (IsDeviceEnabled(mapping.QualityDevice))
+                    WriteDevice(mapping.QualityDevice, tag.Quality);
+
+                short[] words = BytesToWords(tag.Data);
+                WriteDeviceBlock(mapping.DataStartDevice, words);
+
+                if (IsDeviceEnabled(mapping.OkBitDevice))
+                    WriteBit(mapping.OkBitDevice, true);
+                if (IsDeviceEnabled(mapping.NgBitDevice))
+                    WriteBit(mapping.NgBitDevice, false);
+
+                WriteReceiveBit(mapping, true);
+
+                OnLog?.Invoke("读卡 OK → 已写数据 端口=" + tag.Port
+                    + " 字节=" + tag.Data.Length
+                    + " 起始=" + mapping.DataStartDevice
+                    + (IsDeviceEnabled(mapping.ReceiveBitDevice) ? " Receive=1" : ""));
+            }
+        }
+
+        /// <summary>
+        /// 读卡失败:置 OK=0、NG=1。
+        /// </summary>
+        public void WriteReadFailure(PlcRfidMapping mapping)
+        {
+            if (mapping == null)
+                throw new ArgumentNullException(nameof(mapping));
+
+            lock (_sync)
+            {
+                if (IsDeviceEnabled(mapping.OkBitDevice))
+                    WriteBit(mapping.OkBitDevice, false);
+                if (IsDeviceEnabled(mapping.NgBitDevice))
+                    WriteBit(mapping.NgBitDevice, true);
+
+                WriteReceiveBit(mapping, true);
+
+                OnLog?.Invoke("读卡 NG"
+                    + (IsDeviceEnabled(mapping.ReceiveBitDevice) ? " Receive=1" : ""));
+            }
+        }
+
+        /// <summary>
+        /// 置 Receive=1,通知 PLC 本次读卡交互已完成。
+        /// </summary>
+        public void WriteReceiveBit(PlcRfidMapping mapping, bool value)
+        {
+            if (mapping == null)
+                throw new ArgumentNullException(nameof(mapping));
+            if (!IsDeviceEnabled(mapping.ReceiveBitDevice))
+                return;
+
+            lock (_sync)
+                WriteBit(mapping.ReceiveBitDevice, value);
+        }
+
+        /// <summary>
+        /// Ready 关闭后仅清除 Receive(OK/NG 保持供 PLC 读取)。
+        /// </summary>
+        public void ClearReceiveBit(PlcRfidMapping mapping)
+        {
+            if (mapping == null)
+                throw new ArgumentNullException(nameof(mapping));
+
+            lock (_sync)
+            {
+                if (IsDeviceEnabled(mapping.ReceiveBitDevice))
+                    WriteBit(mapping.ReceiveBitDevice, false);
+            }
+        }
+
+        /// <summary>
+        /// SFIS 过站/上传完成:写 OK/NG + Receive=1(OK/NG 不清除,仅清 Receive)。
+        /// </summary>
+        public void WriteSfisResult(PlcSfisFeedback feedback, bool isPassStation, bool success)
+        {
+            if (feedback == null)
+                throw new ArgumentNullException(nameof(feedback));
+
+            string okDev = isPassStation ? feedback.PassOkBitDevice : feedback.UploadOkBitDevice;
+            string ngDev = isPassStation ? feedback.PassNgBitDevice : feedback.UploadNgBitDevice;
+            string recvDev = isPassStation ? feedback.PassReceiveBitDevice : feedback.UploadReceiveBitDevice;
+            string label = isPassStation ? "过站" : "上传";
+
+            lock (_sync)
+            {
+                if (IsDeviceEnabled(okDev))
+                    WriteBit(okDev, success);
+                if (IsDeviceEnabled(ngDev))
+                    WriteBit(ngDev, !success);
+                if (IsDeviceEnabled(recvDev))
+                    WriteBit(recvDev, true);
+
+                OnLog?.Invoke(label + (success ? " OK" : " NG")
+                    + (IsDeviceEnabled(recvDev) ? " Receive=1" : string.Empty));
+            }
+        }
+
+        /// <summary>SFIS 信号关闭后仅清除对应 Receive。</summary>
+        public void ClearSfisReceiveBit(PlcSfisFeedback feedback, bool isPassStation)
+        {
+            if (feedback == null)
+                throw new ArgumentNullException(nameof(feedback));
+
+            string recvDev = isPassStation ? feedback.PassReceiveBitDevice : feedback.UploadReceiveBitDevice;
+            if (!IsDeviceEnabled(recvDev))
+                return;
+
+            lock (_sync)
+                WriteBit(recvDev, false);
+        }
+
+        private bool _heartbeatBitOn;
+        private short _heartbeatWord;
+
+        /// <summary>连接后重置心跳内部计数/翻转状态。</summary>
+        public void ResetHeartbeatState()
+        {
+            lock (_sync)
+            {
+                _heartbeatBitOn = false;
+                _heartbeatWord = 0;
+            }
+        }
+
+        /// <summary>
+        /// 根据地址类型发送一次心跳:M 等位元件翻转 bool,D 等字元件递增数值。
+        /// </summary>
+        public void PulseHeartbeat(string device)
+        {
+            if (!IsDeviceEnabled(device))
+                return;
+
+            PlcHeartbeatKind kind = ResolveHeartbeatKind(device);
+            lock (_sync)
+            {
+                if (kind == PlcHeartbeatKind.Bit)
+                {
+                    _heartbeatBitOn = !_heartbeatBitOn;
+                    WriteBit(device, _heartbeatBitOn);
+                }
+                else
+                {
+                    _heartbeatWord++;
+                    if (_heartbeatWord <= 0)
+                        _heartbeatWord = 1;
+                    WriteDevice(device, _heartbeatWord);
+                }
+            }
+        }
+
+        /// <summary>解析心跳模式;地址填 0 返回 Disabled。</summary>
+        public static PlcHeartbeatKind ResolveHeartbeatKind(string device)
+        {
+            if (!IsDeviceEnabled(device))
+                return PlcHeartbeatKind.Disabled;
+
+            string type = GetDeviceTypePrefix(device);
+            if (IsBitDeviceType(type))
+                return PlcHeartbeatKind.Bit;
+            if (IsWordDeviceType(type))
+                return PlcHeartbeatKind.Word;
+
+            throw new ArgumentException("心跳地址类型不支持(请使用 M 位或 D 字): " + device, nameof(device));
+        }
+
+        public static string GetDeviceTypePrefix(string device)
+        {
+            if (string.IsNullOrWhiteSpace(device))
+                throw new ArgumentException("软元件名称不能为空", nameof(device));
+
+            var match = Regex.Match(device.Trim(), @"^([A-Za-z]+)(\d+)$");
+            if (!match.Success)
+                throw new ArgumentException("无法解析软元件地址: " + device, nameof(device));
+
+            return match.Groups[1].Value.ToUpperInvariant();
+        }
+
+        private static bool IsBitDeviceType(string type)
+        {
+            switch (type)
+            {
+                case "M":
+                case "L":
+                case "F":
+                case "V":
+                case "S":
+                case "X":
+                case "Y":
+                case "B":
+                case "SM":
+                    return true;
+                default:
+                    return false;
+            }
+        }
+
+        private static bool IsWordDeviceType(string type)
+        {
+            switch (type)
+            {
+                case "D":
+                case "W":
+                case "SD":
+                case "R":
+                case "ZR":
+                    return true;
+                default:
+                    return false;
+            }
+        }
+
+        /// <summary>
+        /// 软元件是否启用:空、空白或 "0" 表示不使用。
+        /// </summary>
+        public static bool IsDeviceEnabled(string device)
+        {
+            if (string.IsNullOrWhiteSpace(device))
+                return false;
+            return device.Trim() != "0";
+        }
+
+        /// <summary>
+        /// 连接后自检:写/读一个字,确认 MC 帧交互正常。
+        /// </summary>
+        public bool TestCommunication(string device = "D110", short testValue = 0x55AA)
+        {
+            if (!IsDeviceEnabled(device))
+            {
+                OnLog?.Invoke("PLC 通讯测试跳过:测试地址未配置");
+                return false;
+            }
+
+            lock (_sync)
+            {
+                try
+                {
+                    short[] before = null;
+                    try
+                    {
+                        before = ReadWords(device, 1);
+                    }
+                    catch
+                    {
+                        before = null;
+                    }
+
+                    WriteDevice(device, testValue);
+                    short[] after = ReadWords(device, 1);
+                    bool ok = after != null && after.Length > 0 && after[0] == testValue;
+
+                    if (before != null && before.Length > 0)
+                    {
+                        try { WriteDevice(device, before[0]); }
+                        catch { /* ignore */ }
+                    }
+
+                    OnLog?.Invoke(ok
+                        ? "PLC 通讯测试成功 (" + device + ")"
+                        : "PLC 通讯测试失败: 写入 " + testValue + " 读回 "
+                          + (after != null && after.Length > 0 ? after[0].ToString() : "空"));
+                    return ok;
+                }
+                catch (Exception ex)
+                {
+                    OnLog?.Invoke("PLC 通讯测试异常: " + ex.Message);
+                    return false;
+                }
+            }
+        }
+
+        /// <summary>
+        /// 连接后自检:对位软元件执行 读→写反→读→恢复,并输出 MC 报文与字读交叉验证。
+        /// </summary>
+        public bool TestBitCommunication(string device)
+        {
+            if (!IsDeviceEnabled(device))
+            {
+                OnLog?.Invoke("PLC 位通讯测试跳过:地址未配置");
+                return false;
+            }
+
+            lock (_sync)
+            {
+                try
+                {
+                    DeviceAddress addr = ParseDevice(device);
+                    OnLog?.Invoke("位测试 [" + device + "] 解析地址=" + addr.Address
+                        + " 软元件=0x" + addr.Code.ToString("X2"));
+
+                    byte rawOriginal = ReadBitRaw(addr);
+                    bool original = IsMcBitOn(rawOriginal);
+                    WordBitSnapshot snapOriginal = ReadWordBitSnapshot(addr);
+                    OnLog?.Invoke("  步骤1 位读: 0x" + rawOriginal.ToString("X2")
+                        + " => " + original + " | 字读 M" + snapOriginal.WordStart
+                        + " bit" + snapOriginal.BitIndex + "=" + snapOriginal.BitOn
+                        + " (字=0x" + snapOriginal.WordHex + ")");
+
+                    bool target = !original;
+                    byte[] writeReq = BuildRequestBody(
+                        command: 0x1401,
+                        subCommand: 0x0001,
+                        deviceCode: addr.Code,
+                        address: addr.Address,
+                        points: 1,
+                        writeData: new[] { ToMcBitValue(target) });
+                    OnLog?.Invoke("  步骤2 位写 " + target + " 完整帧: "
+                        + FormatHex(BuildFrame(writeReq)));
+
+                    WriteBits(addr.Code, addr.Address, new[] { target });
+
+                    byte rawFlipped = ReadBitRaw(addr);
+                    bool flipped = IsMcBitOn(rawFlipped);
+                    WordBitSnapshot snapFlipped = ReadWordBitSnapshot(addr);
+                    OnLog?.Invoke("  步骤3 位读: 0x" + rawFlipped.ToString("X2")
+                        + " => " + flipped + " | 字读 M" + snapFlipped.WordStart
+                        + " bit" + snapFlipped.BitIndex + "=" + snapFlipped.BitOn
+                        + " (字=0x" + snapFlipped.WordHex + ")");
+
+                    WriteBits(addr.Code, addr.Address, new[] { original });
+
+                    byte rawRestored = ReadBitRaw(addr);
+                    bool restored = IsMcBitOn(rawRestored);
+                    OnLog?.Invoke("  步骤4 恢复写 " + original + " 位读: 0x"
+                        + rawRestored.ToString("X2") + " => " + restored);
+
+                    bool ok = flipped != original && restored == original;
+                    if (!ok)
+                        OnLog?.Invoke("  诊断: " + DiagnoseBitTestFailure(
+                            original, rawOriginal, target, rawFlipped, snapFlipped, restored, rawRestored));
+
+                    OnLog?.Invoke(ok
+                        ? "PLC 位通讯测试成功 (" + device + ")"
+                        : "PLC 位通讯测试失败 (" + device + ")");
+                    return ok;
+                }
+                catch (Exception ex)
+                {
+                    OnLog?.Invoke("PLC 位通讯测试异常 (" + device + "): " + ex.Message);
+                    return false;
+                }
+            }
+        }
+
+        private struct WordBitSnapshot
+        {
+            public int WordStart;
+            public int BitIndex;
+            public bool BitOn;
+            public string WordHex;
+        }
+
+        private WordBitSnapshot ReadWordBitSnapshot(DeviceAddress addr)
+        {
+            int wordStart = (addr.Address / 16) * 16;
+            int bitIndex = addr.Address % 16;
+            short[] words = ReadWords(addr.Code, wordStart, 1);
+            int word = words[0] & 0xFFFF;
+            return new WordBitSnapshot
+            {
+                WordStart = wordStart,
+                BitIndex = bitIndex,
+                BitOn = (word & (1 << bitIndex)) != 0,
+                WordHex = word.ToString("X4")
+            };
+        }
+
+        private static string DiagnoseBitTestFailure(
+            bool original, byte rawOriginal,
+            bool target, byte rawFlipped, WordBitSnapshot snapFlipped,
+            bool restored, byte rawRestored)
+        {
+            if (target && (rawFlipped == 0x10 || rawFlipped == 0x01) && snapFlipped.BitOn)
+                return "位读写实际成功,请检查测试判定逻辑";
+            if (target && rawOriginal == 0x00 && rawFlipped == 0x00 && !snapFlipped.BitOn)
+                return "位写后位读/字读均为 OFF — 可能原因: (1) PLC 梯形图强制清 M101 "
+                    + "(2) 位写报文未被 PLC 接受 (3) 未允许 RUN 中写入;请用 Hsl 对同一地址 Write/Read 对照";
+            if (target && !snapFlipped.BitOn && (rawFlipped == 0x10 || rawFlipped == 0x01))
+                return "位读为 ON 但字读为 OFF — 位/字地址映射或读路径异常";
+            if (target && snapFlipped.BitOn && rawFlipped == 0x00)
+                return "字读为 ON 但位读为 OFF — 位读响应解析可能有问题";
+            if (restored != original)
+                return "恢复失败,PLC 可能在持续改写该位";
+            return "未知,请对照步骤2完整帧与 HslCommunication 抓包";
+        }
+
+        private static string FormatHex(byte[] data)
+        {
+            return BitConverter.ToString(data).Replace("-", " ");
+        }
+
+        public short[] ReadWords(string device, int count)
+        {
+            DeviceAddress addr = ParseDevice(device);
+            return ReadWords(addr.Code, addr.Address, count);
+        }
+
+        public void WriteWords(string device, short[] values)
+        {
+            DeviceAddress addr = ParseDevice(device);
+            WriteWords(addr.Code, addr.Address, values);
+        }
+
+        public void WriteDevice(string device, short value)
+        {
+            WriteWords(device, new[] { value });
+        }
+
+        public void WriteDeviceBlock(string startDevice, short[] values)
+        {
+            WriteWords(startDevice, values);
+        }
+
+        /// <summary>从字软元件读取指定字节数(低字节在前)。</summary>
+        public byte[] ReadDeviceBytes(string device, int byteCount)
+        {
+            if (byteCount <= 0)
+                return new byte[0];
+
+            int wordCount = (byteCount + 1) / 2;
+            short[] words = ReadWords(device, wordCount);
+            byte[] all = WordsToBytes(words);
+            if (all.Length <= byteCount)
+                return all;
+
+            var trimmed = new byte[byteCount];
+            Array.Copy(all, trimmed, byteCount);
+            return trimmed;
+        }
+
+        public void WriteBit(string device, bool value)
+        {
+            if (!IsDeviceEnabled(device))
+                return;
+
+            DeviceAddress addr = ParseDevice(device);
+            WriteBits(addr.Code, addr.Address, new[] { value });
+        }
+
+        public bool ReadBit(string device)
+        {
+            if (!IsDeviceEnabled(device))
+                throw new ArgumentException("位地址未启用: " + device);
+
+            DeviceAddress addr = ParseDevice(device);
+            return ReadBits(addr.Code, addr.Address, 1)[0];
+        }
+
+        public bool[] ReadBits(byte deviceCode, int address, int count)
+        {
+            if (count <= 0)
+                throw new ArgumentOutOfRangeException(nameof(count));
+
+            byte[] requestData = BuildRequestBody(
+                command: 0x0401,
+                subCommand: 0x0001,
+                deviceCode: deviceCode,
+                address: address,
+                points: count);
+
+            byte[] response = SendRequest(requestData);
+            if (response.Length < 2 + count)
+                throw new InvalidOperationException("PLC 位读响应数据长度不足");
+
+            var result = new bool[count];
+            for (int i = 0; i < count; i++)
+                result[i] = IsMcBitOn(response[2 + i]);
+            return result;
+        }
+
+        /// <summary>MC 协议位读响应:00H=OFF;01H 或 10H 均表示 ON。</summary>
+        private static bool IsMcBitOn(byte value)
+        {
+            return value == 0x01 || value == 0x10;
+        }
+
+        /// <summary>MC 协议位写请求(1401/0001):00H=OFF,10H=ON。</summary>
+        private static byte ToMcBitValue(bool value)
+        {
+            return value ? (byte)0x10 : (byte)0x00;
+        }
+
+        private byte ReadBitRaw(DeviceAddress addr)
+        {
+            byte[] requestData = BuildRequestBody(
+                command: 0x0401,
+                subCommand: 0x0001,
+                deviceCode: addr.Code,
+                address: addr.Address,
+                points: 1);
+
+            byte[] response = SendRequest(requestData);
+            if (response.Length < 3)
+                throw new InvalidOperationException("PLC 位读响应数据长度不足");
+            return response[2];
+        }
+
+        public short[] ReadWords(byte deviceCode, int address, int count)
+        {
+            if (count <= 0)
+                throw new ArgumentOutOfRangeException(nameof(count));
+
+            byte[] requestData = BuildRequestBody(
+                command: 0x0401,
+                subCommand: 0x0000,
+                deviceCode: deviceCode,
+                address: address,
+                points: count);
+
+            byte[] response = SendRequest(requestData);
+            return ParseWordReadResponse(response, count);
+        }
+
+        public void WriteWords(byte deviceCode, int address, short[] values)
+        {
+            if (values == null || values.Length == 0)
+                throw new ArgumentException("写入数据不能为空", nameof(values));
+
+            byte[] requestData = BuildRequestBody(
+                command: 0x1401,
+                subCommand: 0x0000,
+                deviceCode: deviceCode,
+                address: address,
+                points: values.Length,
+                writeData: WordsToBytes(values));
+
+            SendRequest(requestData);
+        }
+
+        public void WriteBits(byte deviceCode, int address, bool[] values)
+        {
+            if (values == null || values.Length == 0)
+                throw new ArgumentException("写入数据不能为空", nameof(values));
+
+            // 二进制位写入:每点 1 字节,00H=OFF / 10H=ON
+            var data = new byte[values.Length];
+            for (int i = 0; i < values.Length; i++)
+                data[i] = ToMcBitValue(values[i]);
+
+            byte[] requestData = BuildRequestBody(
+                command: 0x1401,
+                subCommand: 0x0001,
+                deviceCode: deviceCode,
+                address: address,
+                points: values.Length,
+                writeData: data);
+
+            SendRequest(requestData);
+        }
+
+        /// <summary>
+        /// 请求数据:监视定时器 + 指令 + 子指令 + 起始软元件(3) + 软元件代码(1) + 点数 + [写数据]
+        /// 注意:二进制 3E 帧中「地址在前、软元件代码在后」。
+        /// </summary>
+        private static byte[] BuildRequestBody(ushort command, ushort subCommand, byte deviceCode, int address, int points, byte[] writeData = null)
+        {
+            using (var ms = new MemoryStream())
+            using (var writer = new BinaryWriter(ms))
+            {
+                writer.Write((ushort)0x0010); // 监视定时器:0x10 * 250ms = 4s
+                writer.Write(command);
+                writer.Write(subCommand);
+
+                // 起始软元件编号:3 字节,低字节在前
+                writer.Write((byte)(address & 0xFF));
+                writer.Write((byte)((address >> 8) & 0xFF));
+                writer.Write((byte)((address >> 16) & 0xFF));
+
+                // 软元件代码
+                writer.Write(deviceCode);
+
+                writer.Write((ushort)points);
+
+                if (writeData != null && writeData.Length > 0)
+                    writer.Write(writeData);
+
+                return ms.ToArray();
+            }
+        }
+
+        private byte[] BuildFrame(byte[] requestData)
+        {
+            using (var ms = new MemoryStream())
+            using (var writer = new BinaryWriter(ms))
+            {
+                writer.Write((ushort)0x0050); // 请求副头部
+                writer.Write(NetworkNo);
+                writer.Write(PcNo);
+                writer.Write(IoModuleNo); // 小端 0x03FF -> FF 03
+                writer.Write(StationNo);
+                writer.Write((ushort)requestData.Length);
+                writer.Write(requestData);
+                return ms.ToArray();
+            }
+        }
+
+        private byte[] SendRequest(byte[] requestData)
+        {
+            if (!IsConnected || _stream == null)
+                throw new InvalidOperationException("PLC 未连接");
+
+            try
+            {
+                lock (_sync)
+                {
+                    byte[] frame = BuildFrame(requestData);
+                    _stream.Write(frame, 0, frame.Length);
+                    _stream.Flush();
+
+                    // 响应头固定 9 字节(不是 11!多读会吃掉结束码,导致后续读超时)
+                    byte[] header = ReadExact(McHeaderLength);
+                    if (header[0] != 0xD0 || header[1] != 0x00)
+                    {
+                        throw new InvalidOperationException(
+                            "PLC 响应副头部无效: " + BitConverter.ToString(header));
+                    }
+
+                    int dataLength = header[7] | (header[8] << 8);
+                    if (dataLength < 2)
+                        throw new InvalidOperationException("PLC 响应数据长度无效: " + dataLength);
+
+                    byte[] body = ReadExact(dataLength);
+
+                    ushort endCode = (ushort)(body[0] | (body[1] << 8));
+                    if (endCode != 0)
+                        throw new InvalidOperationException("PLC 返回错误码: 0x" + endCode.ToString("X4")
+                            + " (" + DescribeEndCode(endCode) + ")");
+
+                    return body;
+                }
+            }
+            catch (Exception ex) when (IsTransportFailure(ex))
+            {
+                OnLog?.Invoke("PLC 通讯中断: " + ex.Message);
+                NotifyConnectionLost();
+                throw;
+            }
+        }
+
+        private void NotifyConnectionLost()
+        {
+            if (_client == null)
+                return;
+
+            Disconnect();
+            ConnectionLost?.Invoke();
+        }
+
+        private static bool IsTransportFailure(Exception ex)
+        {
+            if (ex is IOException || ex is SocketException || ex is ObjectDisposedException)
+                return true;
+
+            if (ex is InvalidOperationException && ex.Message.Contains("连接已断开"))
+                return true;
+
+            return ex.InnerException != null && IsTransportFailure(ex.InnerException);
+        }
+
+        private static string DescribeEndCode(ushort endCode)
+        {
+            switch (endCode)
+            {
+                case 0xC050: return "不允许在 RUN 中写入,请在 PLC 以太网参数中勾选允许 RUN 中写入";
+                case 0xC051: return "请求数据长度错误";
+                case 0xC056: return "指令/子指令不支持";
+                case 0xC059: return "指令格式错误(请检查软元件代码/地址顺序)";
+                case 0xC05C: return "请求内容错误";
+                case 0xC061: return "请求数据长度与实际不符";
+                default: return "详见三菱 MC 协议手册结束代码";
+            }
+        }
+
+        private short[] ParseWordReadResponse(byte[] body, int count)
+        {
+            if (body.Length < 2 + count * 2)
+                throw new InvalidOperationException("PLC 读响应数据长度不足");
+
+            var result = new short[count];
+            int offset = 2;
+            for (int i = 0; i < count; i++)
+            {
+                result[i] = (short)(body[offset] | (body[offset + 1] << 8));
+                offset += 2;
+            }
+            return result;
+        }
+
+        private byte[] ReadExact(int length)
+        {
+            var buffer = new byte[length];
+            int read = 0;
+            while (read < length)
+            {
+                int n = _stream.Read(buffer, read, length - read);
+                if (n <= 0)
+                    throw new IOException("PLC 连接已断开");
+                read += n;
+            }
+            return buffer;
+        }
+
+        private static short[] BytesToWords(byte[] data)
+        {
+            int wordCount = (data.Length + 1) / 2;
+            var words = new short[wordCount];
+            for (int i = 0; i < wordCount; i++)
+            {
+                int idx = i * 2;
+                byte low = data[idx];
+                byte high = idx + 1 < data.Length ? data[idx + 1] : (byte)0;
+                words[i] = (short)(low | (high << 8));
+            }
+            return words;
+        }
+
+        private static byte[] WordsToBytes(short[] words)
+        {
+            var data = new byte[words.Length * 2];
+            for (int i = 0; i < words.Length; i++)
+            {
+                data[i * 2] = (byte)(words[i] & 0xFF);
+                data[i * 2 + 1] = (byte)((words[i] >> 8) & 0xFF);
+            }
+            return data;
+        }
+
+        private struct DeviceAddress
+        {
+            public byte Code;
+            public int Address;
+        }
+
+        private static bool TryParseDevice(string device, out DeviceAddress result)
+        {
+            result = default(DeviceAddress);
+            try
+            {
+                result = ParseDevice(device);
+                return true;
+            }
+            catch
+            {
+                return false;
+            }
+        }
+
+        private static DeviceAddress ParseDevice(string device)
+        {
+            if (string.IsNullOrWhiteSpace(device))
+                throw new ArgumentException("软元件名称不能为空", nameof(device));
+
+            var match = Regex.Match(device.Trim(), @"^([A-Za-z]+)(\d+)$");
+            if (!match.Success)
+                throw new ArgumentException("无法解析软元件地址: " + device, nameof(device));
+
+            string type = match.Groups[1].Value.ToUpperInvariant();
+            string number = match.Groups[2].Value;
+
+            // M/L/F/V/S/SM/SD/D/R/ZR:十进制;X/Y:GX Works 八进制;B/W/SB/SW:十六进制
+            int address;
+            if (type == "X" || type == "Y")
+                address = Convert.ToInt32(number, 8);
+            else if (type == "B" || type == "W" || type == "SB" || type == "SW")
+                address = Convert.ToInt32(number, 16);
+            else
+                address = int.Parse(number);
+
+            byte code;
+            if (!DeviceCodes.TryGetValue(type, out code))
+                throw new ArgumentException("不支持的软元件类型: " + type, nameof(device));
+
+            return new DeviceAddress { Code = code, Address = address };
+        }
+
+        private static readonly Dictionary<string, byte> DeviceCodes = new Dictionary<string, byte>(StringComparer.OrdinalIgnoreCase)
+        {
+            { "SM", 0x91 },
+            { "SD", 0xA9 },
+            { "M", 0x90 },
+            { "L", 0x92 },
+            { "F", 0x93 },
+            { "V", 0x94 },
+            { "S", 0x98 },
+            { "X", 0x9C },
+            { "Y", 0x9D },
+            { "B", 0xA0 },
+            { "D", 0xA8 },
+            { "W", 0xB4 },
+            { "R", 0xAF },
+            { "ZR", 0xB0 }
+        };
+
+        public void Dispose()
+        {
+            Disconnect();
+            GC.SuppressFinalize(this);
+        }
+    }
+
+    public enum PlcHeartbeatKind
+    {
+        Disabled,
+        Bit,
+        Word
+    }
+
+    /// <summary>
+    /// RFID 与 PLC 握手寄存器映射。
+    /// 流程:PLC 置 Ready → PC 读端口号并读卡 → 写数据 → 写 OK/NG → 写 Receive
+    /// → 等 Ready 关闭 → PC 仅清 Receive。
+    /// 地址填 "0" 表示不使用该软元件。
+    /// </summary>
+    public class PlcRfidMapping
+    {
+        /// <summary>RFID 原始数据起始寄存器(PC 写入)</summary>
+        public string DataStartDevice { get; set; } = "D110";
+
+        /// <summary>端口号寄存器(PLC 写入,PC 读取)</summary>
+        public string PortDevice { get; set; } = "D101";
+
+        /// <summary>数据质量(PC 写入,可选)</summary>
+        public string QualityDevice { get; set; } = "D102";
+
+        /// <summary>Ready 位(PLC→PC 请求读卡)</summary>
+        public string ReadyBitDevice { get; set; } = "M100";
+
+        /// <summary>读 OK 位(PC→PLC)</summary>
+        public string OkBitDevice { get; set; } = "0";
+
+        /// <summary>读 NG 位(PC→PLC)</summary>
+        public string NgBitDevice { get; set; } = "0";
+
+        /// <summary>Receive 位(PC→PLC,读卡完成后置 1)</summary>
+        public string ReceiveBitDevice { get; set; } = "0";
+
+        /// <summary>最大转发字节数</summary>
+        public int MaxDataBytes { get; set; } = 32;
+
+        /// <summary>单次读卡超时(毫秒)</summary>
+        public int ReadTimeoutMs { get; set; } = 2000;
+    }
+
+    /// <summary>
+    /// SFIS 过站/上传 PLC 回写映射(PC→PLC)。
+    /// 流程:信号上升沿触发 SFIS → 写 OK/NG + Receive → 信号关闭后仅清 Receive。
+    /// </summary>
+    public class PlcSfisFeedback
+    {
+        public string PassOkBitDevice { get; set; } = "M106";
+        public string PassNgBitDevice { get; set; } = "M107";
+        public string PassReceiveBitDevice { get; set; } = "M108";
+        public string UploadOkBitDevice { get; set; } = "M109";
+        public string UploadNgBitDevice { get; set; } = "M110";
+        public string UploadReceiveBitDevice { get; set; } = "M111";
+    }
+}

+ 122 - 0
TeamAAS-VM/Core/PLCs/OPCuaClientPLC.cs

@@ -0,0 +1,122 @@
+using Opc.Ua;
+using OpcUaHelper;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.Core.PLCs
+{
+    public class OPCuaClientPLC : IPlc
+    {
+        public Guid Id{ get; private set; }
+
+        public CommunicationType CommunicationType { get; private set; }
+
+        public string EndpointUrl { get; private set; }
+
+        public string Name { get; private set; }
+
+        public OpcUaClient OpcUaClient { get; private set; }
+
+        public bool IsConnected { get { return OpcUaClient.Connected; } }
+
+        public event Action<object, bool> ConnectChangedEvent;
+
+        public OPCuaClientPLC(Guid id, string name, string endpointUrl, CommunicationType communicationType)
+        {
+            Id = id;
+            Name = name;
+            EndpointUrl = endpointUrl;
+            CommunicationType = communicationType;
+            OpcUaClient = new OpcUaClient();
+            // 初始化PLC连接
+            OpcUaClient.UserIdentity = new UserIdentity(new AnonymousIdentityToken());
+            // connect to server, this is a sample
+            try
+            {
+                OpcUaClient.ConnectComplete += OpcUaClient_ConnectComplete;
+                OpcUaClient.ReconnectStarting += OpcUaClient_ReconnectStarting;
+                OpcUaClient.ReconnectComplete += OpcUaClient_ReconnectComplete;
+                OpcUaClient.OpcStatusChange += OpcUaClient_OpcStatusChange;
+            }
+            catch (Exception ex)
+            {
+                return;
+            }
+        }
+
+        public OPCuaClientPLC(PlcInfo plcInfo)
+        {
+            Id = plcInfo.Id;
+            Name = plcInfo.Name;
+            EndpointUrl = plcInfo.EndpointUrl;
+            CommunicationType = plcInfo.CommunicationType;
+            OpcUaClient = new OpcUaClient();
+            // 初始化PLC连接
+            OpcUaClient.UserIdentity = new UserIdentity(new AnonymousIdentityToken());
+            // connect to server, this is a sample
+            try
+            {
+                OpcUaClient.ConnectComplete += OpcUaClient_ConnectComplete;
+                OpcUaClient.ReconnectStarting += OpcUaClient_ReconnectStarting;
+                OpcUaClient.ReconnectComplete += OpcUaClient_ReconnectComplete;
+                OpcUaClient.OpcStatusChange += OpcUaClient_OpcStatusChange;
+            }
+            catch (Exception ex)
+            {
+                return;
+            }
+        }
+
+        public void Connect()
+        {
+            OpcUaClient.ConnectServer(EndpointUrl);
+        }
+
+        public Task ConnectAsync()
+        {
+            return OpcUaClient.ConnectServer(EndpointUrl);
+        }
+
+        public void Disconnect()
+        {
+            OpcUaClient.Disconnect();
+        }
+
+        public void Dispose()
+        {
+            OpcUaClient.Disconnect();
+            OpcUaClient.ConnectComplete -= OpcUaClient_ConnectComplete;
+            OpcUaClient.ReconnectStarting -= OpcUaClient_ReconnectStarting;
+            OpcUaClient.ReconnectComplete -= OpcUaClient_ReconnectComplete;
+            OpcUaClient.OpcStatusChange -= OpcUaClient_OpcStatusChange;
+        }
+
+        #region OPC事件
+        private void OpcUaClient_OpcStatusChange(object sender, OpcUaStatusEventArgs e)
+        {
+            //LogHelper.WriteLogInfo($"OPC状态发生改变:Error:{e.Error},Time:{e.Time},Text:{e.Text}");
+        }
+
+        private void OpcUaClient_ReconnectComplete(object sender, EventArgs e)
+        {
+            ConnectChangedEvent?.Invoke(this, OpcUaClient.Connected);
+        }
+
+        private void OpcUaClient_ReconnectStarting(object sender, EventArgs e)
+        {
+            ConnectChangedEvent?.Invoke(this, OpcUaClient.Connected);
+        }
+
+        private void OpcUaClient_ConnectComplete(object sender, EventArgs e)
+        {
+            ConnectChangedEvent?.Invoke(this, OpcUaClient.Connected);
+        }
+        #endregion
+    }
+}

+ 108 - 0
TeamAAS-VM/Core/PLCs/PlcService.cs

@@ -0,0 +1,108 @@
+using OxyPlot;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TeamAAS_VP.Core.Robots;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+namespace TeamAAS_VP.Core.PLCs
+{
+    public class PlcService
+    {
+        private readonly Dictionary<Guid, IPlc> _plcCollection;
+
+        public PlcService()
+        {
+            _plcCollection = new Dictionary<Guid, IPlc>();
+        }
+        public bool CreatePlc(Guid id, PlcInfo plcInfo)
+        {
+            IPlc plc;
+            if (plcInfo.CommunicationType == Enums.CommunicationType.OPC_UA_Client)
+            {
+                plc = new OPCuaClientPLC(plcInfo);
+            }
+            else if (plcInfo.CommunicationType == Enums.CommunicationType.Mitsubishi_MC)
+            {
+                plc = new MitsubishiMcPLC(plcInfo);
+            }
+            else
+            {
+                return false;
+            }
+
+            if (_plcCollection.ContainsKey(id))
+            {
+                var currenplc = _plcCollection[id];
+                currenplc.Dispose();
+            }
+            _plcCollection[id] = plc;
+            return true;
+        }
+
+        public Task<bool> CreateRobotAsync(Guid id, PlcInfo plcInfo)
+        {
+            IPlc plc;
+            if (plcInfo.CommunicationType == Enums.CommunicationType.OPC_UA_Client)
+            {
+                plc = new OPCuaClientPLC(plcInfo);
+            }
+            else if (plcInfo.CommunicationType == Enums.CommunicationType.Mitsubishi_MC)
+            {
+                plc = new MitsubishiMcPLC(plcInfo);
+            }
+            else
+            {
+                return Task.FromResult(false);
+            }
+
+            if (_plcCollection.ContainsKey(id))
+            {
+                var currenplc = _plcCollection[id];
+                currenplc.Dispose();
+            }
+            _plcCollection[id] = plc;
+            return Task.FromResult(true);
+        }
+
+        public IPlc GetPlc(Guid id)
+        {
+            if (!_plcCollection.ContainsKey(id))
+            {
+                return null;
+            }
+            return _plcCollection[id];
+        }
+
+        public Task<IPlc> GetPlcAsync(Guid id)
+        {
+            if (!_plcCollection.ContainsKey(id))
+            {
+                return null;
+            }
+            return Task.FromResult(_plcCollection[id]);
+        }
+
+        public void UnRegisterPlc(Guid id)
+        {
+            if (_plcCollection.ContainsKey(id))
+            {
+                var plc = _plcCollection[id];
+                plc.Dispose();
+            }
+        }
+
+        public Task UnRegisterPlcAsync(Guid id)
+        {
+            if (_plcCollection.ContainsKey(id))
+            {
+                var plc = _plcCollection[id];
+                plc.Dispose();
+            }
+            return Task.CompletedTask;
+        }
+    }
+}

Some files were not shown because too many files changed in this diff