Bladeren bron

添加项目文件。

孝锋 徐 11 maanden geleden
commit
8432bfd06f
100 gewijzigde bestanden met toevoegingen van 23803 en 0 verwijderingen
  1. 63 0
      .gitattributes
  2. 369 0
      .gitignore
  3. 84 0
      README.md
  4. 4 0
      ResXManager.config.xml
  5. 863 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. 309 0
      Team.FFFeederService/FeederService.cs
  15. 44 0
      Team.FFFeederService/Interfaces/IFeeder.cs
  16. 162 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. 167 0
      Team.FFFeederService/Models/SingleActionParam.cs
  27. 156 0
      Team.FFFeederService/Models/SingleSequenceAction.cs
  28. 109 0
      Team.FFFeederService/Models/SingleSequenceActionGroup.cs
  29. 140 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. 1694 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. 320 0
      TeamAAS-VM/App.config
  41. 49 0
      TeamAAS-VM/App.xaml
  42. 288 0
      TeamAAS-VM/App.xaml.cs
  43. 15 0
      TeamAAS-VM/Attributes/LocalizationAttribute.cs
  44. 82 0
      TeamAAS-VM/Behaviors/CheckBoxUserSelectionBehavior.cs
  45. 92 0
      TeamAAS-VM/Behaviors/ComboBoxSelectionBehavior.cs
  46. 84 0
      TeamAAS-VM/Behaviors/DatePickerUserSelectionBehavior.cs
  47. 74 0
      TeamAAS-VM/Behaviors/ListBoxUserSelectionBehavior.cs
  48. 178 0
      TeamAAS-VM/Behaviors/NumericUpDownUserInputBehavior.cs
  49. 80 0
      TeamAAS-VM/Behaviors/RadioButtonUserSelectionBehavior.cs
  50. 86 0
      TeamAAS-VM/Behaviors/SliderUserInteractionBehavior.cs
  51. 214 0
      TeamAAS-VM/Behaviors/TextBoxUserInputBehavior.cs
  52. 125 0
      TeamAAS-VM/Controls/AddPalletView.xaml
  53. 314 0
      TeamAAS-VM/Controls/AddPalletView.xaml.cs
  54. 60 0
      TeamAAS-VM/Controls/AddProduct.xaml
  55. 130 0
      TeamAAS-VM/Controls/AddProduct.xaml.cs
  56. 170 0
      TeamAAS-VM/Controls/AflexControl.xaml
  57. 186 0
      TeamAAS-VM/Controls/AflexControl.xaml.cs
  58. 162 0
      TeamAAS-VM/Controls/FeederOutput.xaml
  59. 376 0
      TeamAAS-VM/Controls/FeederOutput.xaml.cs
  60. 1384 0
      TeamAAS-VM/Controls/FeederSequence.xaml
  61. 697 0
      TeamAAS-VM/Controls/FeederSequence.xaml.cs
  62. 148 0
      TeamAAS-VM/Controls/FeederSystemParam.xaml
  63. 318 0
      TeamAAS-VM/Controls/FeederSystemParam.xaml.cs
  64. 74 0
      TeamAAS-VM/Controls/ParameterEdit.xaml
  65. 148 0
      TeamAAS-VM/Controls/ParameterEdit.xaml.cs
  66. 36 0
      TeamAAS-VM/Controls/PictureDisplayControl.xaml
  67. 154 0
      TeamAAS-VM/Controls/PictureDisplayControl.xaml.cs
  68. 230 0
      TeamAAS-VM/Controls/RobotManual.xaml
  69. 469 0
      TeamAAS-VM/Controls/RobotManual.xaml.cs
  70. 224 0
      TeamAAS-VM/Controls/ScriptEditControl.xaml
  71. 619 0
      TeamAAS-VM/Controls/ScriptEditControl.xaml.cs
  72. 69 0
      TeamAAS-VM/Controls/ShowMessage.xaml
  73. 131 0
      TeamAAS-VM/Controls/ShowMessage.xaml.cs
  74. 66 0
      TeamAAS-VM/Controls/UProgressBar.xaml
  75. 239 0
      TeamAAS-VM/Controls/UProgressBar.xaml.cs
  76. 276 0
      TeamAAS-VM/Controls/VibrationControl.xaml
  77. 195 0
      TeamAAS-VM/Controls/VibrationControl.xaml.cs
  78. 806 0
      TeamAAS-VM/Controls/VibrationPara.xaml
  79. 896 0
      TeamAAS-VM/Controls/VibrationPara.xaml.cs
  80. 24 0
      TeamAAS-VM/Controls/WaitingControl.xaml
  81. 28 0
      TeamAAS-VM/Controls/WaitingControl.xaml.cs
  82. 30 0
      TeamAAS-VM/Controls/WaitingPage.xaml
  83. 28 0
      TeamAAS-VM/Controls/WaitingPage.xaml.cs
  84. 67 0
      TeamAAS-VM/Controls/myNumericUpDowm.xaml
  85. 159 0
      TeamAAS-VM/Controls/myNumericUpDowm.xaml.cs
  86. 403 0
      TeamAAS-VM/Core/BgCommunicate.cs
  87. 329 0
      TeamAAS-VM/Core/BgModbusTcpCommunicate.cs
  88. 100 0
      TeamAAS-VM/Core/BraceFoldingStrategy.cs
  89. 1026 0
      TeamAAS-VM/Core/Cameras/AHuaCamera.cs
  90. 1049 0
      TeamAAS-VM/Core/Cameras/BaslerCamera.cs
  91. 659 0
      TeamAAS-VM/Core/Cameras/CognexCamera.cs
  92. 1012 0
      TeamAAS-VM/Core/Cameras/GalaxyCamera.cs
  93. 634 0
      TeamAAS-VM/Core/Cameras/MvCamera.cs
  94. 79 0
      TeamAAS-VM/Core/Common.cs
  95. 196 0
      TeamAAS-VM/Core/CoordinateTransformer.cs
  96. 108 0
      TeamAAS-VM/Core/DetectionResult.cs
  97. 125 0
      TeamAAS-VM/Core/FileHelper.cs
  98. 65 0
      TeamAAS-VM/Core/FilePath.cs
  99. 311 0
      TeamAAS-VM/Core/GalaxyMethod/CDecide.cs
  100. 82 0
      TeamAAS-VM/Core/GalaxyMethod/CWin32Bitmaps.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

+ 84 - 0
README.md

@@ -0,0 +1,84 @@
+# TeamAAS-VM
+
+这是 TeamAAS-VM (视觉定位与 Feeder/机器人控制) 的 WPF 桌面应用仓库(分支:VP)。
+
+该仓库为生产线视觉引导、Feeder 驱动与机器人配合提供软件端实现,包含图形界面、配置管理、远程命令服务与硬件抽象层。
+
+---
+
+## 项目结构(摘要)
+- `TeamAAS-VM/` —— 主 WPF 应用(项目名:`TeamAAS-VP`)
+- `Team.FFFeederService/` —— Feeder 相关硬件抽象与驱动
+- `docs/` —— 项目文档(已包含 `RemoteCommandSpecification.md`)
+
+主要关注点:视觉 (Cognex VisionPro)、Feeder、机器人、PLC、后台通讯 (BgCommunicate)、以及远程命令接口。
+
+---
+
+## 先决条件(开发/运行环境)
+- Windows 10/11
+- Visual Studio 2026(支持 .NET Framework 4.8)
+- .NET Framework 4.8 开发工具
+- Cognex VisionPro SDK(运行时与许可)
+- Feeder / Robot / PLC 等硬件的驱动与许可(视部署环境)
+- 推荐:以管理员身份运行以便访问串口、设备与注册表
+
+在 CI/自动构建环境中,请确保安装了所有本地依赖并且有必要的 license 文件(VisionPro 等)。
+
+---
+
+## 构建(本地)
+1. 使用 Visual Studio 打开 `TeamAAS-VM.sln`(或打开 `TeamAAS-VM/TeamAAS-VP.csproj`)。
+2. 恢复 NuGet 包。
+3. 选择 `Release|x86` 或 `Debug|Any CPU`(依据目标平台)。
+4. 构建解决方案并在输出中检查错误。
+
+注意:部分组件(如 VisionPro)为本地 SDK,若本机未安装会导致设计时/运行时错误。
+
+---
+
+## 运行
+1. 在 Visual Studio 中设置 `TeamAAS-VP` 为启动项目。
+2. 运行 (F5) 或发布可执行程序到目标机并运行。
+3. 首次运行可能需要填写设备配置,或在 `App` 启动时加载本地配置文件夹(路径由 `FilePath` 常量定义)。
+
+---
+
+## 远程命令协议(快速)
+项目内提供了基于逗号分隔文本格式的远程命令(由 `RemoteCommandService.ExecuteAsync` 处理)。
+- 命令示例:`LoadProduct,ProductName`、`GetPalletPoint,1,2,5`、以及触发视觉流程的流程名命令如 `PickCam1,GetPos`。
+- 命令规范文档已生成:`docs/RemoteCommandSpecification.md`,请参阅该文档以获取完整格式、参数和返回示例。
+
+---
+
+## 日志与调试
+- 日志使用项目内的 `LogHelper`(log4net 配置在 `App.config`)。
+- 出现崩溃或本地 native 异常(例如 CRT R6025),建议:
+  - 在 Visual Studio 中启用混合调试(Native + Managed),重现退出过程并查看 native 堆栈。
+  - 检查 `Management.DisposeResources()` 是否在退出时被调用并能正确关闭串口/相机/Timers/线程/后台任务。
+  - 检查设备驱动是否在 Dispose 前完成断开,避免关闭后仍有回调触发本地虚函数。
+
+---
+
+## 常见问题
+- 运行时报错 `R6025 (pure virtual function call)`:通常是 native 组件在对象已销毁后仍调用虚函数。按上面的日志与调试方法排查并确保退出时释放所有硬件资源与停止后台线程/定时器。
+- 设计器中 XAML 报错(找不到类型):请先进行完整解决方案构建,确保所有控件/自定义类型已编译并位于正确的命名空间。
+
+---
+
+## 贡献指南
+- 新功能请先在 issue 中描述设计与目标。
+- 使用 feature 分支,发起 pull request 前请确保:
+  - 本地能通过构建;
+  - 必要时添加单元测试;
+  - 更新文档(`docs/` 下或 README)。
+
+---
+
+## 联系人 / 维护
+- 仓库维护者:见仓库 remote 与项目负责人信息(Git 远程地址)。
+- 若遇到与硬件或许可相关的问题,请与对应硬件供应商或内部维护人员联系。
+
+---
+
+README 旨在作为入门与运维参考。如需我把 README 翻译成英文版或生成更详细的部署手册(例如在不同环境下的配置步骤),请告诉我具体格式与范围,我可继续完善.

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

+ 863 - 0
Team.FFFeederService/AfagFeeder.cs

@@ -0,0 +1,863 @@
+using aflex_CSharp_Integration_Sample;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+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 int FeederNo { get; set; }
+
+        public string Name { get; set; }
+
+        public bool IsConnected => IsInit;
+
+        public bool IsInit { get; set; }
+
+        /// <summary>
+        /// Feeder连接状态更改事件
+        /// </summary>
+        public event Action<object, bool> FeederConnectionStatusChanged;
+
+        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, int feederNo, string name, string ip, int port)
+        {
+            Id = id;
+            FeederNo = feederNo;
+            Name= name;
+            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)
+                            {
+                                FeederConnectionStatusChanged?.Invoke(this,true);
+                                GeneralRelease();
+                            }
+                            else
+                            {
+                                FeederConnectionStatusChanged?.Invoke(this,false);
+                            }
+                            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)
+                            {
+                                FeederConnectionStatusChanged?.Invoke(this,true);
+                                GeneralRelease();
+                            }
+                            else
+                            {
+                                FeederConnectionStatusChanged?.Invoke(this,false);
+                            }
+                            IsInit = true;
+                        }
+                    }
+                }
+                catch (Exception)
+                {
+                    IsInit = false;
+                    while (!IsInit)
+                    {
+                        try
+                        {
+                            bool flog = objaflex.Connect(IPValue, PortValue);
+                            if (flog)
+                            {
+                                FeederConnectionStatusChanged?.Invoke(this,true);
+                                GeneralRelease();
+                            }
+                            else
+                            {
+                                FeederConnectionStatusChanged?.Invoke(this,false);
+                            }
+                            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 = 0;
+                    break;
+                case FeederModel.FF240:
+                    feedermodel = 0;
+                    break;
+                case FeederModel.FF380:
+                    feedermodel = 1;
+                    break;
+                case FeederModel.FF530:
+                    feedermodel = 2;
+                    break;
+                case FeederModel.Unknown:
+                    feedermodel = 0;
+                    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();
+        }
+    }
+}

+ 309 - 0
Team.FFFeederService/FeederService.cs

@@ -0,0 +1,309 @@
+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;
+        private readonly object _sync = new object();
+
+        public FeederService()
+        {
+            _feederCollection = new Dictionary<Guid, IVoiceCoilMotorFeeder>();
+        }
+
+        public bool CreateFeeder(Guid id, int feederNo, string name, string ip, int port, FeederBrand feederBrand)
+        {
+            IVoiceCoilMotorFeeder feeder;
+            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);
+                feeder = new TeamFeeder(id, feederNo, name, tcpClient);
+            }
+            else
+            {
+                feeder = new AfagFeeder(id, feederNo, name, ip, port);
+            }
+
+            feeder.Id = id;
+
+            lock (_sync)
+            {
+                if (_feederCollection.ContainsKey(id))
+                {
+                    try
+                    {
+                        // 移除旧事件并释放
+                        var old = _feederCollection[id];
+                        old.Dispose();
+                    }
+                    catch
+                    {
+                        // 忽略个别释放异常
+                    }
+
+                    _feederCollection[id] = feeder;
+                }
+                else
+                {
+                    _feederCollection.Add(id, feeder);
+                }
+            }
+
+            return true;
+        }
+
+        public Task<bool> CreateFeederAsync(Guid id, int feederNo, string name, string ip, int port, FeederBrand feederBrand)
+        {
+            return Task.Run(() => CreateFeeder(id, feederNo, name, ip, port, feederBrand));
+        }
+
+        /// <summary>
+        /// Feeder断开连接时
+        /// </summary>
+        private void FeederService_FeederDisconnectedEvent(Guid feederId, ITcpClient client, ClosedEventArgs e)
+        {
+            // 可在这里转发或记录断开事件
+        }
+
+        /// <summary>
+        /// Feeder连接上时
+        /// </summary>
+        private void FeederService_FeederConnectedEvent(Guid feederId, ITcpClient client, ConnectedEventArgs e)
+        {
+            // 可在这里转发或记录连接事件
+        }
+
+        public IVoiceCoilMotorFeeder GetFeeder(Guid id)
+        {
+            lock (_sync)
+            {
+                if (_feederCollection.TryGetValue(id, out var feeder)) return feeder;
+            }
+            return null;
+        }
+
+        public Task<IVoiceCoilMotorFeeder> GetFeederAsync(Guid id)
+        {
+            return Task.Run(() => { return GetFeeder(id); });
+        }
+
+        public IVoiceCoilMotorFeeder GetFeederByIndex(int feederNo)
+        {
+            lock (_sync)
+            {
+                foreach (var kvp in _feederCollection)
+                {
+                    var f = kvp.Value;
+                    if (f == null) continue;
+                    try
+                    {
+                        if (f.FeederNo == feederNo) return f;
+                    }
+                    catch
+                    {
+                        // 忽略访问异常
+                    }
+                }
+            }
+            return null;
+        }
+
+        public Task<IVoiceCoilMotorFeeder> GetFeederByIndexAsync(int feederNo)
+        {
+            return Task.Run(() => { return GetFeederByIndex(feederNo); });
+        }
+
+        public Task UnRegisterFeederAsync(Guid id)
+        {
+            return Task.Run(() => UnRegisterFeeder(id));
+        }
+
+        public void UnRegisterFeeder(Guid id)
+        {
+            IVoiceCoilMotorFeeder feeder = null;
+            lock (_sync)
+            {
+                if (_feederCollection.TryGetValue(id, out feeder))
+                {
+                    _feederCollection.Remove(id);
+                }
+            }
+
+            if (feeder != null)
+            {
+
+                try
+                {
+                    feeder.Dispose();
+                }
+                catch
+                {
+                    // 忽略释放异常
+                }
+            }
+        }
+
+        public Task UnRegisterFeederByIndexAsync(int feederNo)
+        {
+            return Task.Run(() => UnRegisterFeederByIndex(feederNo));
+        }
+
+        public void UnRegisterFeederByIndex(int feederNo)
+        {
+            Guid foundId = Guid.Empty;
+            lock (_sync)
+            {
+                foreach (var kvp in _feederCollection)
+                {
+                    try
+                    {
+                        if (kvp.Value != null && kvp.Value.FeederNo == feederNo)
+                        {
+                            foundId = kvp.Key;
+                            break;
+                        }
+                    }
+                    catch { }
+                }
+            }
+
+            if (foundId != Guid.Empty)
+            {
+                UnRegisterFeeder(foundId);
+            }
+        }
+
+        public IReadOnlyCollection<IVoiceCoilMotorFeeder> GetAllFeeders()
+        {
+            lock (_sync)
+            {
+                return _feederCollection.Values.ToList().AsReadOnly();
+            }
+        }
+
+        public Task<IReadOnlyCollection<IVoiceCoilMotorFeeder>> GetAllFeedersAsync()
+        {
+            return Task.Run(() => { return GetAllFeeders(); });
+        }
+
+        public bool TryGetFeeder(Guid id, out IVoiceCoilMotorFeeder feeder)
+        {
+            lock (_sync)
+            {
+                return _feederCollection.TryGetValue(id, out feeder);
+            }
+        }
+
+        public Task<(bool found, IVoiceCoilMotorFeeder feeder)> TryGetFeederAsync(Guid id)
+        {
+            return Task.Run(() =>
+            {
+                IVoiceCoilMotorFeeder feeder;
+                bool found;
+                lock (_sync)
+                {
+                    found = _feederCollection.TryGetValue(id, out feeder);
+                }
+                return (found, feeder);
+            });
+        }
+
+        public bool ContainsFeeder(Guid id)
+        {
+            lock (_sync)
+            {
+                return _feederCollection.ContainsKey(id);
+            }
+        }
+
+        public Task<bool> ContainsFeederAsync(Guid id)
+        {
+            return Task.Run(() => { return ContainsFeeder(id); });
+        }
+
+        public bool RemoveFeeder(Guid id)
+        {
+            IVoiceCoilMotorFeeder feeder = null;
+            lock (_sync)
+            {
+                if (_feederCollection.TryGetValue(id, out feeder))
+                {
+                    _feederCollection.Remove(id);
+                }
+            }
+
+            if (feeder != null)
+            {
+
+                try
+                {
+                    feeder.Dispose();
+                }
+                catch
+                {
+                    // 忽略释放异常
+                }
+                return true;
+            }
+            return false;
+        }
+
+        public Task<bool> RemoveFeederAsync(Guid id)
+        {
+            return Task.Run(() => { return RemoveFeeder(id); });
+        }
+
+        public void RemoveAllFeeders()
+        {
+            List<IVoiceCoilMotorFeeder> feeders;
+            lock (_sync)
+            {
+                feeders = _feederCollection.Values.ToList();
+                _feederCollection.Clear();
+            }
+
+            foreach (var f in feeders)
+            {
+
+                try
+                {
+                    f.Dispose();
+                }
+                catch { }
+            }
+        }
+
+        /// <summary>
+        /// 更新Feeder编号
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="newFeederNo"></param>
+        public void UpdateFeederNo(Guid id, int newFeederNo)
+        {
+            lock (_sync)
+            {
+                if (_feederCollection.TryGetValue(id, out var feeder))
+                {
+                    feeder.FeederNo = newFeederNo;
+                }
+            }
+
+        }
+    }
+}

+ 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; }
+        int FeederNo { get; set; }
+        string Name { 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<object,bool> FeederConnectionStatusChanged;
+    }
+}

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

@@ -0,0 +1,162 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Team.FFFeederService.Interfaces
+{
+    /// <summary>
+    /// Feeder 管理服务接口。
+    /// 提供创建、查询、注销、移除和枚举 Feeder 的同步和异步操作。
+    /// 所有方法在实现中应保证线程安全并正确释放资源。
+    /// </summary>
+    public interface IFeederService
+    {
+        /// <summary>
+        /// 异步创建并注册一个新的 Feeder 实例。
+        /// </summary>
+        /// <param name="id">Feeder 的唯一标识符 (GUID)。</param>
+        /// <param name="feederNo">Feeder 的编号索引(用于位置/槽位标识)。</param>
+        /// <param name="name">Feeder 的显示名称。</param>
+        /// <param name="ip">Feeder 的网络 IP 地址或主机名。</param>
+        /// <param name="port">Feeder 的网络端口号。</param>
+        /// <param name="feederBrand">Feeder 的品牌枚举,用于创建特定实现。</param>
+        /// <returns>返回一个任务,任务结果为是否成功创建并注册 Feeder。</returns>
+        Task<bool> CreateFeederAsync(Guid id,int feederNo, string name, string ip, int port, FeederBrand feederBrand);
+
+        /// <summary>
+        /// 同步创建并注册一个新的 Feeder 实例。
+        /// </summary>
+        /// <param name="id">Feeder 的唯一标识符 (GUID)。</param>
+        /// <param name="feederNo">Feeder 的编号索引(用于位置/槽位标识)。</param>
+        /// <param name="name">Feeder 的显示名称。</param>
+        /// <param name="ip">Feeder 的网络 IP 地址或主机名。</param>
+        /// <param name="port">Feeder 的网络端口号。</param>
+        /// <param name="feederBrand">Feeder 的品牌枚举,用于创建特定实现。</param>
+        /// <returns>是否成功创建并注册 Feeder。</returns>
+        bool CreateFeeder(Guid id, int feederNo, string name, string ip, int port, FeederBrand feederBrand);
+
+        /// <summary>
+        /// 获取已注册的 Feeder(通过 id)。若未找到,可抛出或返回 null(由实现决定)。
+        /// </summary>
+        /// <param name="id">要获取的 Feeder 的唯一标识符。</param>
+        /// <returns>对应的 <see cref="IVoiceCoilMotorFeeder"/> 实例。</returns>
+        IVoiceCoilMotorFeeder GetFeeder(Guid id);
+
+        /// <summary>
+        /// 异步获取已注册的 Feeder(通过 id)。
+        /// </summary>
+        /// <param name="id">要获取的 Feeder 的唯一标识符。</param>
+        /// <returns>一个任务,任务结果为对应的 <see cref="IVoiceCoilMotorFeeder"/> 实例。</returns>
+        Task<IVoiceCoilMotorFeeder> GetFeederAsync(Guid id);
+
+        /// <summary>
+        /// 通过 Feeder 编号(index)获取 Feeder。
+        /// </summary>
+        /// <param name="feederNo">Feeder 的编号索引。</param>
+        /// <returns>对应的 <see cref="IVoiceCoilMotorFeeder"/> 实例,若不存在返回 null(由实现决定)。</returns>
+        IVoiceCoilMotorFeeder GetFeederByIndex(int feederNo);
+
+        /// <summary>
+        /// 异步通过 Feeder 编号(index)获取 Feeder。
+        /// </summary>
+        /// <param name="feederNo">Feeder 的编号索引。</param>
+        /// <returns>一个任务,任务结果为对应的 <see cref="IVoiceCoilMotorFeeder"/> 实例。</returns>
+        Task<IVoiceCoilMotorFeeder> GetFeederByIndexAsync(int feederNo);
+
+        /// <summary>
+        /// 注销并移除 Feeder(通过 id)。调用后应释放与该 Feeder 相关的所有资源并从管理集合中移除。
+        /// </summary>
+        /// <param name="id">要注销的 Feeder 的唯一标识符。</param>
+        Task UnRegisterFeederAsync(Guid id);
+
+        /// <summary>
+        /// 同步注销并移除 Feeder(通过 id)。调用后应释放与该 Feeder 相关的所有资源并从管理集合中移除。
+        /// </summary>
+        /// <param name="id">要注销的 Feeder 的唯一标识符。</param>
+        void UnRegisterFeeder(Guid id);
+
+        /// <summary>
+        /// 注销并移除 Feeder(通过 index)。调用后应释放与该 Feeder 相关的所有资源并从管理集合中移除。
+        /// </summary>
+        /// <param name="feederNo">要注销的 Feeder 的编号索引。</param>
+        Task UnRegisterFeederByIndexAsync(int feederNo);
+
+        /// <summary>
+        /// 同步注销并移除 Feeder(通过 index)。
+        /// </summary>
+        /// <param name="feederNo">要注销的 Feeder 的编号索引。</param>
+        void UnRegisterFeederByIndex(int feederNo);
+
+        /// <summary>
+        /// 获取所有已注册的 Feeder 的只读集合快照。
+        /// 返回的集合不应允许外部修改管理内部状态。
+        /// </summary>
+        /// <returns>只读集合,包含当前所有已注册的 Feeder 实例。</returns>
+        IReadOnlyCollection<IVoiceCoilMotorFeeder> GetAllFeeders();
+
+        /// <summary>
+        /// 异步获取所有已注册的 Feeder 的只读集合快照。
+        /// </summary>
+        /// <returns>一个任务,任务结果为只读集合,包含当前所有已注册的 Feeder 实例。</returns>
+        Task<IReadOnlyCollection<IVoiceCoilMotorFeeder>> GetAllFeedersAsync();
+
+        /// <summary>
+        /// 尝试通过 id 获取 Feeder,避免抛出异常的安全访问方式。
+        /// </summary>
+        /// <param name="id">要查找的 Feeder 的唯一标识符。</param>
+        /// <param name="feeder">如果找到则输出对应的 Feeder 实例;否则为 null。</param>
+        /// <returns>如果找到则返回 true,否则返回 false。</returns>
+        bool TryGetFeeder(Guid id, out IVoiceCoilMotorFeeder feeder);
+
+        /// <summary>
+        /// 异步尝试通过 id 获取 Feeder,返回一个包含查找结果的元组。
+        /// </summary>
+        /// <param name="id">要查找的 Feeder 的唯一标识符。</param>
+        /// <returns>一个任务,任务结果为 (found, feeder),found 表示是否找到,feeder 为对应实例或 null。</returns>
+        Task<(bool found, IVoiceCoilMotorFeeder feeder)> TryGetFeederAsync(Guid id);
+
+        /// <summary>
+        /// 检查 Feeder 是否存在(通过 id)。
+        /// </summary>
+        /// <param name="id">要检查的 Feeder 的唯一标识符。</param>
+        /// <returns>存在则返回 true,否则返回 false。</returns>
+        bool ContainsFeeder(Guid id);
+
+        /// <summary>
+        /// 异步检查 Feeder 是否存在(通过 id)。
+        /// </summary>
+        /// <param name="id">要检查的 Feeder 的唯一标识符。</param>
+        /// <returns>一个任务,任务结果为是否存在。</returns>
+        Task<bool> ContainsFeederAsync(Guid id);
+
+        /// <summary>
+        /// 移除 Feeder(通过 id)并释放资源,返回是否成功移除。
+        /// 如果 Feeder 不存在则返回 false。
+        /// </summary>
+        /// <param name="id">要移除的 Feeder 的唯一标识符。</param>
+        /// <returns>是否成功移除并释放资源。</returns>
+        bool RemoveFeeder(Guid id);
+
+        /// <summary>
+        /// 异步移除 Feeder(通过 id)并释放资源,返回是否成功移除。
+        /// </summary>
+        /// <param name="id">要移除的 Feeder 的唯一标识符。</param>
+        /// <returns>一个任务,任务结果为是否成功移除并释放资源。</returns>
+        Task<bool> RemoveFeederAsync(Guid id);
+
+        /// <summary>
+        /// 移除并释放所有已注册的 Feeder。调用后管理集合应为空。
+        /// 实现应确保对每个 Feeder 的资源正确释放且保持原子性或可恢复性。
+        /// </summary>
+        void RemoveAllFeeders();
+
+        /// <summary>
+        /// 更新Feeder编号
+        /// </summary>
+        /// <param name="id"></param>
+        /// <param name="newFeederNo"></param>
+        void UpdateFeederNo(Guid id, int newFeederNo);
+    }
+}

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

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

@@ -0,0 +1,167 @@
+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); }
+        }
+
+        public SingleActionParam Copy()
+        {
+            return new SingleActionParam()
+            {
+                Motor1 = new VoiceMotorParam()
+                {
+                    Amplitude = this.Motor1.Amplitude,
+                    Frequency = this.Motor1.Frequency,
+                    Phase = this.Motor1.Phase,
+                    WaveShape = this.Motor1.WaveShape
+                },
+                Motor2 = new VoiceMotorParam()
+                {
+                    Amplitude = this.Motor2.Amplitude,
+                    Frequency = this.Motor2.Frequency,
+                    Phase = this.Motor2.Phase,
+                    WaveShape = this.Motor2.WaveShape
+                },
+                Motor3 = new VoiceMotorParam()
+                {
+                    Amplitude = this.Motor3.Amplitude,
+                    Frequency = this.Motor3.Frequency,
+                    Phase = this.Motor3.Phase,
+                    WaveShape = this.Motor3.WaveShape
+                },
+                Motor4 = new VoiceMotorParam()
+                {
+                    Amplitude = this.Motor4.Amplitude,
+                    Frequency = this.Motor4.Frequency,
+                    Phase = this.Motor4.Phase,
+                    WaveShape = this.Motor4.WaveShape
+                },
+                DurationValue=this.DurationValue
+            };
+        }
+
+        #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
+    }
+}

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

@@ -0,0 +1,140 @@
+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 new VoiceMotorParam()
+            {
+                Amplitude=this.Amplitude,
+                Frequency=this.Frequency,
+                Phase=this.Phase,
+                WaveShape=this.WaveShape
+            };
+        }
+    }
+}

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

+ 1694 - 0
Team.FFFeederService/TeamFeeder.cs

@@ -0,0 +1,1694 @@
+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; }
+
+        public int FeederNo { get; set; }
+
+        public string Name { 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<object, bool> FeederConnectionStatusChanged;
+        #endregion
+
+        public TeamFeeder(Guid id, int feederNo, string name, TcpClient tcpClient)
+        {
+            Id = id;
+            FeederNo = feederNo;
+            Name = name;
+            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)
+        {
+            FeederConnectionStatusChanged?.Invoke(this,true);
+            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)
+        {
+            FeederConnectionStatusChanged?.Invoke(this,false);
+            //Console.WriteLine($"{client.IP}断开连接!");
+            return EasyTask.CompletedTask;
+        }
+
+        /// <summary>
+        /// 获取Feeder型号
+        /// </summary>
+        /// <returns></returns>
+        public FeederModel GetFeederModel()
+        {
+            try
+            {
+                string res = GetSingleParamValue(30).Replace("{", "").Replace("}", "").Split(':')[1];
+                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, fedType, 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

+ 320 - 0
TeamAAS-VM/App.config

@@ -0,0 +1,320 @@
+<?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>
+    <!--CT日志类-->
+    <logger name="logCT">
+      <level value="ALL" />
+      <appender-ref ref="CTAppender" />
+    </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>
+    <!--CT日志附加介质-->
+    <appender name="CTAppender" type="log4net.Appender.RollingFileAppender">
+      <param name="File" value="..\\Log\\LogCT\\" />
+      <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>
+  </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>

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

@@ -0,0 +1,288 @@
+using Prism.Ioc;
+using Prism.Modularity;
+using Prism.Services.Dialogs;
+using Prism.Unity;
+using SqlSugar;
+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.FFFeederService;
+using Team.FFFeederService.Interfaces;
+using Team.Utility;
+using TeamAAS_VP;
+using TeamAAS_VP.Controls;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Properties;
+using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.Services;
+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 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<IConfigService, ConfigService>();
+            containerRegistry.RegisterSingleton<ICalibrationService, CalibrationService>();
+            containerRegistry.RegisterSingleton<ICameraService, CameraService>();
+            containerRegistry.RegisterSingleton<IRobotService, RobotService>();
+            containerRegistry.RegisterSingleton<IPlcService, PlcService>();
+            containerRegistry.RegisterSingleton<IFeederService, FeederService>();
+            containerRegistry.RegisterSingleton<IProductService, ProductService>();
+            containerRegistry.RegisterSingleton<IRemoteCommandService, RemoteCommandService>();
+            containerRegistry.RegisterSingleton<Management>();
+
+            // Register system database service and initializer
+            containerRegistry.RegisterSingleton<ISystemDatabaseService, TeamAAS_VP.Data.SystemDatabaseService>();
+            containerRegistry.RegisterSingleton<IDatabaseInitializer, TeamAAS_VP.Data.DatabaseInitializer>();
+
+            containerRegistry.RegisterSingleton<ShowVisionRenderViewModel>();
+            containerRegistry.RegisterSingleton<InchingControlViewModel>();
+            //containerRegistry.RegisterSingleton<ScriptHomeViewModel>();
+            containerRegistry.RegisterSingleton<DebugViewModel>();
+            containerRegistry.RegisterSingleton<FeederClearViewModel>();
+            containerRegistry.RegisterSingleton<AfagFeederManual>();
+            containerRegistry.RegisterSingleton<HomeViewModel>();
+            //产品
+            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>();
+            //**************************************************************************************
+
+            // 注册 SQLSugar 客户端(单例模式)
+            containerRegistry.RegisterSingleton<ISqlSugarClient>(s =>
+            {
+                // 规范化数据库路径(使用绝对路径和平台分隔符)
+                string relative = Path.Combine("..", "Database File", "System.db");
+                string fullDbPath = Path.GetFullPath(relative); // 变为绝对路径
+                Directory.CreateDirectory(Path.GetDirectoryName(fullDbPath)); // 确保目录存在
+                string connectionString = $"Data Source={fullDbPath};Version=3;";
+                //Scoped用SqlSugarClient 
+                SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
+                {
+                    DbType = SqlSugar.DbType.Sqlite,
+                    ConnectionString = connectionString,
+                    IsAutoCloseConnection = false,
+                    InitKeyType = InitKeyType.Attribute // 初始化主键和自增列信息的方式
+                },
+               db =>
+               {
+                   db.Aop.OnLogExecuting = (sql, pars) =>
+                   {
+
+                   };
+               });
+                return sqlSugar;
+            });
+        }
+
+        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())
+                    {
+                        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);
+
+        }
+
+        protected override void OnInitialized()
+        {
+            base.OnInitialized();
+        }
+    }
+}

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

+ 82 - 0
TeamAAS-VM/Behaviors/CheckBoxUserSelectionBehavior.cs

@@ -0,0 +1,82 @@
+using Microsoft.Xaml.Behaviors;
+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.Input;
+
+namespace TeamAAS_VP.Behaviors
+{
+    public class CheckBoxUserSelectionBehavior : Behavior<CheckBox>
+    {
+        public static readonly DependencyProperty UserSelectionCommandProperty =
+            DependencyProperty.Register(
+                nameof(UserSelectionCommand),
+                typeof(ICommand),
+                typeof(CheckBoxUserSelectionBehavior));
+
+        public ICommand UserSelectionCommand
+        {
+            get => (ICommand)GetValue(UserSelectionCommandProperty);
+            set => SetValue(UserSelectionCommandProperty, value);
+        }
+
+        public static readonly DependencyProperty CommandParameterProperty =
+            DependencyProperty.Register(
+                nameof(CommandParameter),
+                typeof(object),
+                typeof(CheckBoxUserSelectionBehavior));
+
+        public object CommandParameter
+        {
+            get => GetValue(CommandParameterProperty);
+            set => SetValue(CommandParameterProperty, value);
+        }
+
+        private bool _isUserInteraction = false;
+
+        protected override void OnAttached()
+        {
+            base.OnAttached();
+            AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
+            AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
+            AssociatedObject.Checked += OnCheckedChanged;
+            AssociatedObject.Unchecked += OnCheckedChanged;
+        }
+
+        protected override void OnDetaching()
+        {
+            base.OnDetaching();
+            AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
+            AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown;
+            AssociatedObject.Checked -= OnCheckedChanged;
+            AssociatedObject.Unchecked -= OnCheckedChanged;
+        }
+
+        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
+        {
+            _isUserInteraction = true;
+        }
+
+        private void OnPreviewKeyDown(object sender, KeyEventArgs e)
+        {
+            if (e.Key == Key.Space)
+            {
+                _isUserInteraction = true;
+            }
+        }
+
+        private void OnCheckedChanged(object sender, RoutedEventArgs e)
+        {
+            if (_isUserInteraction && UserSelectionCommand?.CanExecute(CommandParameter) == true)
+            {
+                var parameter = new Tuple<object, bool>(CommandParameter, AssociatedObject.IsChecked == true);
+                UserSelectionCommand.Execute(parameter);
+            }
+            _isUserInteraction = false;
+        }
+    }
+}

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

+ 84 - 0
TeamAAS-VM/Behaviors/DatePickerUserSelectionBehavior.cs

@@ -0,0 +1,84 @@
+using Microsoft.Xaml.Behaviors;
+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.Input;
+
+namespace TeamAAS_VP.Behaviors
+{
+    public class DatePickerUserSelectionBehavior : Behavior<DatePicker>
+    {
+        public static readonly DependencyProperty UserSelectionCommandProperty =
+            DependencyProperty.Register(
+                nameof(UserSelectionCommand),
+                typeof(ICommand),
+                typeof(DatePickerUserSelectionBehavior));
+
+        public ICommand UserSelectionCommand
+        {
+            get => (ICommand)GetValue(UserSelectionCommandProperty);
+            set => SetValue(UserSelectionCommandProperty, value);
+        }
+
+        public static readonly DependencyProperty CommandParameterProperty =
+            DependencyProperty.Register(
+                nameof(CommandParameter),
+                typeof(object),
+                typeof(DatePickerUserSelectionBehavior));
+
+        public object CommandParameter
+        {
+            get => GetValue(CommandParameterProperty);
+            set => SetValue(CommandParameterProperty, value);
+        }
+
+        private bool _isUserInteraction = false;
+        private DateTime? _previousDate;
+
+        protected override void OnAttached()
+        {
+            base.OnAttached();
+            AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
+            AssociatedObject.CalendarOpened += OnCalendarOpened;
+            AssociatedObject.SelectedDateChanged += OnSelectedDateChanged;
+        }
+
+        protected override void OnDetaching()
+        {
+            base.OnDetaching();
+            AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
+            AssociatedObject.CalendarOpened -= OnCalendarOpened;
+            AssociatedObject.SelectedDateChanged -= OnSelectedDateChanged;
+        }
+
+        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
+        {
+            _isUserInteraction = true;
+            _previousDate = AssociatedObject.SelectedDate;
+        }
+
+        private void OnCalendarOpened(object sender, RoutedEventArgs e)
+        {
+            _isUserInteraction = true;
+            _previousDate = AssociatedObject.SelectedDate;
+        }
+
+        private void OnSelectedDateChanged(object sender, SelectionChangedEventArgs e)
+        {
+            if (_isUserInteraction && UserSelectionCommand?.CanExecute(CommandParameter) == true)
+            {
+                var parameter = new Tuple<object, DateTime?, DateTime?>(
+                    CommandParameter,
+                    _previousDate,
+                    AssociatedObject.SelectedDate);
+
+                UserSelectionCommand.Execute(parameter);
+            }
+            _isUserInteraction = false;
+        }
+    }
+}

+ 74 - 0
TeamAAS-VM/Behaviors/ListBoxUserSelectionBehavior.cs

@@ -0,0 +1,74 @@
+using Microsoft.Xaml.Behaviors;
+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.Input;
+
+namespace TeamAAS_VP.Behaviors
+{
+    public class ListBoxUserSelectionBehavior : Behavior<ListBox>
+    {
+        public static readonly DependencyProperty UserSelectionCommandProperty =
+            DependencyProperty.Register(
+                nameof(UserSelectionCommand),
+                typeof(ICommand),
+                typeof(ListBoxUserSelectionBehavior));
+
+        public ICommand UserSelectionCommand
+        {
+            get => (ICommand)GetValue(UserSelectionCommandProperty);
+            set => SetValue(UserSelectionCommandProperty, value);
+        }
+
+        public static readonly DependencyProperty CommandParameterProperty =
+            DependencyProperty.Register(
+                nameof(CommandParameter),
+                typeof(object),
+                typeof(ListBoxUserSelectionBehavior));
+
+        public object CommandParameter
+        {
+            get => GetValue(CommandParameterProperty);
+            set => SetValue(CommandParameterProperty, value);
+        }
+
+        protected override void OnAttached()
+        {
+            base.OnAttached();
+            AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
+            AssociatedObject.SelectionChanged += OnSelectionChanged;
+        }
+
+        protected override void OnDetaching()
+        {
+            base.OnDetaching();
+            AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
+            AssociatedObject.SelectionChanged -= OnSelectionChanged;
+        }
+
+        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
+        {
+            AssociatedObject.Tag = true; // 标记为用户交互
+        }
+
+        private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+        {
+            if (AssociatedObject.Tag is bool isUserInteraction && isUserInteraction)
+            {
+                if (UserSelectionCommand?.CanExecute(CommandParameter) == true)
+                {
+                    var parameter = new Tuple<object, object>(
+                        CommandParameter,
+                        AssociatedObject.SelectedItem);
+
+                    UserSelectionCommand.Execute(parameter);
+                }
+                AssociatedObject.Tag = false; // 重置标记
+            }
+        }
+    }
+}

+ 178 - 0
TeamAAS-VM/Behaviors/NumericUpDownUserInputBehavior.cs

@@ -0,0 +1,178 @@
+using Microsoft.Xaml.Behaviors;
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+
+namespace TeamAAS_VP.Behaviors
+{
+    /// <summary>
+    /// 为 `MahApps.Metro.Controls.NumericUpDown` 提供用户输入检测行为。
+    /// 当控件值由用户交互(鼠标、键盘或文本输入)更改时,触发绑定的命令并传递 (CommandParameter, previousValue, currentValue)。
+    /// </summary>
+    public class NumericUpDownUserInputBehavior : Behavior<MahApps.Metro.Controls.NumericUpDown>
+    {
+        /// <summary>
+        /// 依赖属性:用户输入触发时要执行的命令。
+        /// 命令接收一个 Tuple&lt;object, double?, double?&gt; 参数,分别是 (CommandParameter, previousValue, currentValue)。
+        /// </summary>
+        public static readonly DependencyProperty UserInputCommandProperty =
+            DependencyProperty.Register(
+                nameof(UserInputCommand),
+                typeof(ICommand),
+                typeof(NumericUpDownUserInputBehavior));
+
+        /// <summary>
+        /// 要在用户输入时执行的命令。
+        /// </summary>
+        public ICommand UserInputCommand
+        {
+            get => (ICommand)GetValue(UserInputCommandProperty);
+            set => SetValue(UserInputCommandProperty, value);
+        }
+
+        /// <summary>
+        /// 依赖属性:传递给命令的参数(作为命令的第一个项,最终传递给命令的是 Tuple&lt;object, double?, double?&gt;)。
+        /// </summary>
+        public static readonly DependencyProperty CommandParameterProperty =
+            DependencyProperty.Register(
+                nameof(CommandParameter),
+                typeof(object),
+                typeof(NumericUpDownUserInputBehavior));
+
+        /// <summary>
+        /// 命令参数,最终与 previousValue 和 currentValue 一起封装成 Tuple 传递给命令。
+        /// </summary>
+        public object CommandParameter
+        {
+            get => GetValue(CommandParameterProperty);
+            set => SetValue(CommandParameterProperty, value);
+        }
+
+        // 标记当前操作是否为用户交互触发
+        private bool _isUserInteraction = false;
+
+        // 保存上一次值(用于在值变化时向命令提供前后对比)
+        private double? _previousValue;
+
+        /// <summary>
+        /// 行为附加时订阅控件的相关事件用于检测用户交互与值变化。
+        /// </summary>
+        protected override void OnAttached()
+        {
+            base.OnAttached();
+            AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
+            AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
+            AssociatedObject.ValueChanged += OnValueChanged;
+            AssociatedObject.LostFocus += OnLostFocus;
+            AssociatedObject.GotFocus += OnGotFocus;
+        }
+
+        /// <summary>
+        /// 行为分离时取消订阅事件,防止内存泄漏。
+        /// </summary>
+        protected override void OnDetaching()
+        {
+            base.OnDetaching();
+            AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
+            AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown;
+            AssociatedObject.ValueChanged -= OnValueChanged;
+            AssociatedObject.LostFocus -= OnLostFocus;
+            AssociatedObject.GotFocus -= OnGotFocus;
+        }
+
+        /// <summary>
+        /// 当控件获得焦点时,标记为用户交互并记录当前值。
+        /// 这有助于检测通过文本输入直接修改值的场景。
+        /// </summary>
+        private void OnGotFocus(object sender, RoutedEventArgs e)
+        {
+            _isUserInteraction = true;
+            _previousValue = AssociatedObject.Value;
+
+            // 如果需要按当前语言设置文本框语言,可在此处获取应用级服务并设置 PART_TextBox 的 Language。
+            //var management = App.Host.Services.GetRequiredService<Management>();
+            //var partTextBox = AssociatedObject.Template.FindName("PART_TextBox", AssociatedObject) as TextBox;
+            //partTextBox.Language = System.Windows.Markup.XmlLanguage.GetLanguage(management.CurrentLanguage);
+        }
+
+        /// <summary>
+        /// 在鼠标按下时标记为用户交互并记录当前值(例如点击上下箭头)。
+        /// </summary>
+        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
+        {
+            _isUserInteraction = true;
+            _previousValue = AssociatedObject.Value;
+        }
+
+        /// <summary>
+        /// 在键盘按下时检测常见的用户输入按键(上下箭头、数字、退格、删除等),以标记为用户交互并记录当前值。
+        /// </summary>
+        private void OnPreviewKeyDown(object sender, KeyEventArgs e)
+        {
+            // 检测键盘输入(上下箭头、数字键、删除、退格等)
+            if (e.Key == Key.Up || e.Key == Key.Down ||
+                e.Key == Key.Back || e.Key == Key.Delete ||
+                (e.Key >= Key.D0 && e.Key <= Key.D9) ||
+                (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
+            {
+                _isUserInteraction = true;
+                _previousValue = AssociatedObject.Value;
+            }
+        }
+
+        /// <summary>
+        /// 值变化时触发:若是用户交互导致的变化且命令可执行,则构造参数并执行命令。
+        /// 同时更新保存的前一个值以便连续变化时能够正确传递历史值。
+        /// </summary>
+        private void OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double?> e)
+        {
+            if (_isUserInteraction && UserInputCommand?.CanExecute(CommandParameter) == true)
+            {
+                var parameter = new Tuple<object, double?, double?>(
+                    CommandParameter,
+                    _previousValue,
+                    AssociatedObject.Value);
+
+                UserInputCommand.Execute(parameter);
+
+                // 更新前一个值,方便下一次变化比较
+                _previousValue = AssociatedObject.Value;
+            }
+        }
+
+        /// <summary>
+        /// 失去焦点时的处理:
+        /// 1. 处理通过文本框直接输入导致的值变化(可能在 LostFocus 时才完成绑定/解析),执行命令。
+        /// 2. 重置用户交互标记。
+        /// 3. 当文本框为空时,恢复绑定的值(UpdateTarget),避免空文本导致模型被清空。
+        /// </summary>
+        private void OnLostFocus(object sender, RoutedEventArgs e)
+        {
+            // 处理通过文本框直接输入的情况:若是用户交互且值有变化,则执行命令
+            if (_isUserInteraction && _previousValue != AssociatedObject.Value)
+            {
+                if (UserInputCommand?.CanExecute(CommandParameter) == true)
+                {
+                    var parameter = new Tuple<object, double?, double?>(
+                        CommandParameter,
+                        _previousValue,
+                        AssociatedObject.Value);
+
+                    UserInputCommand.Execute(parameter);
+                }
+            }
+
+            // 重置用户交互标记
+            _isUserInteraction = false;
+
+            // 处理空文本框的情况(恢复绑定值),避免用户清空文本导致绑定端值丢失
+            var partTextBox = AssociatedObject.Template.FindName("PART_TextBox", AssociatedObject) as TextBox;
+            if (string.IsNullOrWhiteSpace(partTextBox?.Text))
+            {
+                var bindingExpression = AssociatedObject.GetBindingExpression(MahApps.Metro.Controls.NumericUpDown.ValueProperty);
+                bindingExpression?.UpdateTarget();
+            }
+        }
+    }
+}

+ 80 - 0
TeamAAS-VM/Behaviors/RadioButtonUserSelectionBehavior.cs

@@ -0,0 +1,80 @@
+using Microsoft.Xaml.Behaviors;
+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.Input;
+
+namespace TeamAAS_VP.Behaviors
+{
+    public class RadioButtonUserSelectionBehavior : Behavior<RadioButton>
+    {
+        public static readonly DependencyProperty UserSelectionCommandProperty =
+            DependencyProperty.Register(
+                nameof(UserSelectionCommand),
+                typeof(ICommand),
+                typeof(RadioButtonUserSelectionBehavior));
+
+        public ICommand UserSelectionCommand
+        {
+            get => (ICommand)GetValue(UserSelectionCommandProperty);
+            set => SetValue(UserSelectionCommandProperty, value);
+        }
+
+        public static readonly DependencyProperty CommandParameterProperty =
+            DependencyProperty.Register(
+                nameof(CommandParameter),
+                typeof(object),
+                typeof(RadioButtonUserSelectionBehavior));
+
+        public object CommandParameter
+        {
+            get => GetValue(CommandParameterProperty);
+            set => SetValue(CommandParameterProperty, value);
+        }
+
+        private bool _isUserInteraction = false;
+
+        protected override void OnAttached()
+        {
+            base.OnAttached();
+            AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
+            AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
+            AssociatedObject.Checked += OnChecked;
+        }
+
+        protected override void OnDetaching()
+        {
+            base.OnDetaching();
+            AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
+            AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown;
+            AssociatedObject.Checked -= OnChecked;
+        }
+
+        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
+        {
+            _isUserInteraction = true;
+        }
+
+        private void OnPreviewKeyDown(object sender, KeyEventArgs e)
+        {
+            if (e.Key == Key.Space)
+            {
+                _isUserInteraction = true;
+            }
+        }
+
+        private void OnChecked(object sender, RoutedEventArgs e)
+        {
+            if (_isUserInteraction && UserSelectionCommand?.CanExecute(CommandParameter) == true)
+            {
+                var parameter = new Tuple<object, object>(CommandParameter, AssociatedObject.Content);
+                UserSelectionCommand.Execute(parameter);
+            }
+            _isUserInteraction = false;
+        }
+    }
+}

+ 86 - 0
TeamAAS-VM/Behaviors/SliderUserInteractionBehavior.cs

@@ -0,0 +1,86 @@
+using Microsoft.Xaml.Behaviors;
+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.Input;
+
+namespace TeamAAS_VP.Behaviors
+{
+    public class SliderUserInteractionBehavior : Behavior<Slider>
+    {
+        public static readonly DependencyProperty UserInteractionCommandProperty =
+            DependencyProperty.Register(
+                nameof(UserInteractionCommand),
+                typeof(ICommand),
+                typeof(SliderUserInteractionBehavior));
+
+        public ICommand UserInteractionCommand
+        {
+            get => (ICommand)GetValue(UserInteractionCommandProperty);
+            set => SetValue(UserInteractionCommandProperty, value);
+        }
+
+        public static readonly DependencyProperty CommandParameterProperty =
+            DependencyProperty.Register(
+                nameof(CommandParameter),
+                typeof(object),
+                typeof(SliderUserInteractionBehavior));
+
+        public object CommandParameter
+        {
+            get => GetValue(CommandParameterProperty);
+            set => SetValue(CommandParameterProperty, value);
+        }
+
+        private bool _isUserDragging = false;
+        private double _previousValue;
+
+        protected override void OnAttached()
+        {
+            base.OnAttached();
+            AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
+            AssociatedObject.PreviewMouseUp += OnPreviewMouseUp;
+            AssociatedObject.ValueChanged += OnValueChanged;
+        }
+
+        protected override void OnDetaching()
+        {
+            base.OnDetaching();
+            AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
+            AssociatedObject.PreviewMouseUp -= OnPreviewMouseUp;
+            AssociatedObject.ValueChanged -= OnValueChanged;
+        }
+
+        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
+        {
+            _isUserDragging = true;
+            _previousValue = AssociatedObject.Value;
+        }
+
+        private void OnPreviewMouseUp(object sender, MouseButtonEventArgs e)
+        {
+            if (_isUserDragging)
+            {
+                _isUserDragging = false;
+            }
+        }
+
+        private void OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
+        {
+            if (_isUserDragging && UserInteractionCommand?.CanExecute(CommandParameter) == true)
+            {
+                var parameter = new Tuple<object, double, double>(
+                    CommandParameter,
+                    _previousValue,
+                    AssociatedObject.Value);
+
+                UserInteractionCommand.Execute(parameter);
+                _previousValue = AssociatedObject.Value;
+            }
+        }
+    }
+}

+ 214 - 0
TeamAAS-VM/Behaviors/TextBoxUserInputBehavior.cs

@@ -0,0 +1,214 @@
+using Microsoft.Xaml.Behaviors;
+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.Input;
+
+namespace TeamAAS_VP.Behaviors
+{
+    /// <summary>
+    /// Behavior:在 TextBox 上检测“用户输入”并通过绑定的命令回调旧/新文本值。
+    /// 仅在检测到明确的用户交互(键入、删除、粘贴、输入法确认等)时触发命令,避免程序性修改触发。
+    /// </summary>
+    public class TextBoxUserInputBehavior : Behavior<TextBox>
+    {
+        #region 依赖属性
+
+        /// <summary>
+        /// 绑定的命令,当检测到用户输入且命令可执行时调用。
+        /// 命令接收类型为 <see cref="TextChangedEventArgs"/>(自定义)。
+        /// </summary>
+        public static readonly DependencyProperty UserInputCommandProperty =
+            DependencyProperty.Register(
+                nameof(UserInputCommand),
+                typeof(ICommand),
+                typeof(TextBoxUserInputBehavior));
+
+        /// <summary>
+        /// 要执行的命令(由视图模型绑定)。
+        /// </summary>
+        public ICommand UserInputCommand
+        {
+            get => (ICommand)GetValue(UserInputCommandProperty);
+            set => SetValue(UserInputCommandProperty, value);
+        }
+
+        /// <summary>
+        /// 可选的外部命令参数,将透传到自定义事件参数中。
+        /// </summary>
+        public static readonly DependencyProperty CommandParameterProperty =
+            DependencyProperty.Register(
+                nameof(CommandParameter),
+                typeof(object),
+                typeof(TextBoxUserInputBehavior));
+
+        /// <summary>
+        /// 绑定的命令参数(用于在触发命令时携带额外上下文)。
+        /// </summary>
+        public object CommandParameter
+        {
+            get => GetValue(CommandParameterProperty);
+            set => SetValue(CommandParameterProperty, value);
+        }
+
+        #endregion
+
+        #region 私有字段
+
+        // 是否由用户触发的输入(用于在 TextChanged 中判断)
+        private bool _isUserInput = false;
+
+        // 记录变更前的文本值,用于在触发时传递旧值
+        private string _previousText;
+
+        #endregion
+
+        #region 附加/分离
+
+        /// <summary>
+        /// Behavior 附加到 TextBox 时订阅必要的事件。
+        /// 订阅 PreviewTextInput、PreviewKeyDown、TextChanged、LostFocus 以检测不同的用户交互场景。
+        /// </summary>
+        protected override void OnAttached()
+        {
+            base.OnAttached();
+            AssociatedObject.PreviewTextInput += OnPreviewTextInput;
+            AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
+            AssociatedObject.TextChanged += OnTextChanged;
+            AssociatedObject.LostFocus += OnLostFocus;
+        }
+
+        /// <summary>
+        /// Behavior 分离时取消订阅事件,防止内存泄漏。
+        /// </summary>
+        protected override void OnDetaching()
+        {
+            base.OnDetaching();
+            AssociatedObject.PreviewTextInput -= OnPreviewTextInput;
+            AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown;
+            AssociatedObject.TextChanged -= OnTextChanged;
+            AssociatedObject.LostFocus -= OnLostFocus;
+        }
+
+        #endregion
+
+        #region 事件处理
+
+        /// <summary>
+        /// 处理预输入文本事件(用户通过键盘输入字符)。
+        /// 标记为用户输入并保存变更前的文本。
+        /// </summary>
+        private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
+        {
+            // 用户正在键入文本,记录标志并缓存旧值
+            _isUserInput = true;
+            _previousText = AssociatedObject.Text;
+        }
+
+        /// <summary>
+        /// 处理按键事件(用于检测删除、退格、空格及粘贴快捷键 Ctrl+V)。
+        /// 对这些键也将视为用户输入。
+        /// </summary>
+        private void OnPreviewKeyDown(object sender, KeyEventArgs e)
+        {
+            // 检测删除、退格、空格等按键,这些也属于用户输入操作
+            if (e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Space)
+            {
+                _isUserInput = true;
+                _previousText = AssociatedObject.Text;
+            }
+
+            // 处理粘贴操作 (Ctrl+V),将其视为用户输入
+            if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
+            {
+                _isUserInput = true;
+                _previousText = AssociatedObject.Text;
+            }
+        }
+
+        /// <summary>
+        /// TextChanged 事件处理器:当文本发生变化且标记为用户输入时,构造参数并执行绑定命令。
+        /// 之后清除用户输入标记以避免重复触发。
+        /// </summary>
+        private void OnTextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
+        {
+            if (_isUserInput)
+            {
+                // 清除标记,避免多次触发
+                _isUserInput = false;
+
+                // 如果命令可执行,构造包含旧值/新值的参数并执行
+                if (UserInputCommand?.CanExecute(CommandParameter) == true)
+                {
+                    var parameter = new TextChangedEventArgs(
+                        CommandParameter,
+                        _previousText,
+                        AssociatedObject.Text);
+
+                    UserInputCommand.Execute(parameter);
+                }
+            }
+        }
+
+        /// <summary>
+        /// LostFocus 事件处理器:处理通过输入法(IME)输入时,确认输入后触发命令。
+        /// 当用户在输入法中输入完成并失去焦点时也应视为用户输入。
+        /// </summary>
+        private void OnLostFocus(object sender, RoutedEventArgs e)
+        {
+            // 如果之前有标记为用户输入(例如输入法未触发 TextChanged),在失焦时触发一次
+            if (_isUserInput)
+            {
+                _isUserInput = false;
+
+                if (UserInputCommand?.CanExecute(CommandParameter) == true)
+                {
+                    var parameter = new TextChangedEventArgs(
+                        CommandParameter,
+                        _previousText,
+                        AssociatedObject.Text);
+
+                    UserInputCommand.Execute(parameter);
+                }
+            }
+        }
+
+        #endregion
+    }
+
+    /// <summary>
+    /// 自定义事件参数:用于封装命令参数、文本变更的旧值与新值。
+    /// 该类是不可变的,仅用于传递数据到命令执行逻辑中。
+    /// </summary>
+    public class TextChangedEventArgs
+    {
+        /// <summary>
+        /// 外部传入的命令参数(如果有)。
+        /// </summary>
+        public object CommandParameter { get; }
+
+        /// <summary>
+        /// 变更前的文本值。
+        /// </summary>
+        public string OldValue { get; }
+
+        /// <summary>
+        /// 变更后的文本值。
+        /// </summary>
+        public string NewValue { get; }
+
+        /// <summary>
+        /// 构造函数:创建包含命令上下文和文本新旧值的参数对象。
+        /// </summary>
+        public TextChangedEventArgs(object commandParameter, string oldValue, string newValue)
+        {
+            CommandParameter = commandParameter;
+            OldValue = oldValue;
+            NewValue = newValue;
+        }
+    }
+}

+ 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="14"
+                 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 _IsVisibility3_2; }
+            set { SetProperty(ref _IsVisibility3_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 _PlatShakeTimeout; }
+            set { SetProperty(ref _PlatShakeTimeout, 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>

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

@@ -0,0 +1,148 @@
+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;
+using TeamAAS_VP.Models.Product;
+
+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>

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

@@ -0,0 +1,469 @@
+using Prism.Commands;
+using Prism.Ioc;
+using Prism.Unity;
+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;
+using TeamAAS_VP.Core;
+using TeamAAS_VP.Core.Robots;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Events;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Resources.Languages;
+using TeamAAS_VP.Services;
+using TeamAAS_VP.ViewModels;
+using TeamAAS_VP.Views;
+
+namespace TeamAAS_VP.Controls
+{
+    /// <summary>
+    /// RobotManual.xaml 的交互逻辑
+    /// </summary>
+    public partial class RobotManual : UserControl,INotifyPropertyChanged
+    {
+        IConfigService _configService;
+
+        public RobotManual()
+        {
+            _configService=((PrismApplication)(App.Current)).Container.Resolve<IConfigService>();
+            InitializeComponent();
+            DataContext = this;
+            this.Loaded += RobotManual_Loaded;
+        }
+
+        private void RobotManual_Loaded(object sender, RoutedEventArgs e)
+        {
+            _configService = ((PrismApplication)(App.Current)).Container.Resolve<IConfigService>();
+        }
+
+        #region 属性
+        private IRobot _Robot;
+
+        public IRobot Robot
+        {
+            get { return _Robot; }
+            set { SetProperty(ref _Robot,value);
+                try
+                {
+                    if (value!=null)
+                    {
+                        this.Distance = _configService.GetRobotStepDistance(value.Id);
+                    }
+                    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;
+                    }
+                    _configService.UpdateRobotStepDistance(Robot.Id, value);
+                }
+                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 new 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
+    }
+}

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

@@ -0,0 +1,66 @@
+<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"
+             mc:Ignorable="d"
+             Background="Transparent"
+             VerticalAlignment="Center"
+             HorizontalAlignment="Stretch"
+             FontFamily="{DynamicResource DefaultFont}"
+             d:Width="1920"
+             d:Height="1080">
+    <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"
+            HorizontalAlignment="Stretch"
+            Background="{DynamicResource MaterialDesign.Brush.Primary.Light}"
+            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
+    }
+}

+ 24 - 0
TeamAAS-VM/Controls/WaitingControl.xaml

@@ -0,0 +1,24 @@
+<UserControl x:Class="TeamAAS_VP.Controls.WaitingControl"
+             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" />
+        </StackPanel>
+    </Grid>
+</UserControl>

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

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

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

@@ -0,0 +1,1026 @@
+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 int Index { get; set; }
+        public string ManufacturerName { get; private set; }
+        public bool IsFindByIp { get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public string CameraIp { 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, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
+        {
+            ID = id;
+            Name = serialNumber;
+            Index = index;
+            CameraIp = cameraip;
+            SerialNumber = serialNumber;
+            IsFindByIp = isFindByIp;
+            mvCameraAcq = new MVSDK_Net.MyCamera();
+            var list = GetDevices();
+            foreach (var device in list)
+            {
+                if (device.CameraType== CameraType.GIGE)
+                {
+                    if (IsFindByIp)
+                    {
+                        if (device.CameraIp == CameraIp)
+                        {
+                            IsHaveCamera = true;
+                            ManufacturerName = device.ManufacturerName;
+                            ModelName = device.Model;
+                            SerialNumber = device.SerialNumber;
+                            CameraType = device.CameraType;
+                            int res = mvCameraAcq.IMV_CreateHandle(IMVDefine.IMV_ECreateHandleMode.modeByCameraKey, 0, serialNumber);
+                            if (res == IMVDefine.IMV_OK)
+                            {
+
+                            }
+                            break;
+                        }
+                    }
+                    else
+                    {
+                        if (device.SerialNumber == serialNumber)
+                        {
+                            IsHaveCamera = true;
+                            ManufacturerName = device.ManufacturerName;
+                            ModelName = device.Model;
+                            SerialNumber = device.SerialNumber;
+                            CameraType = device.CameraType;
+                            CameraIp= device.CameraIp;
+                            int res = mvCameraAcq.IMV_CreateHandle(IMVDefine.IMV_ECreateHandleMode.modeByCameraKey, 0, serialNumber);
+                            if (res == IMVDefine.IMV_OK)
+                            {
+
+                            }
+                            break;
+                        }
+                    }
+                }
+                else
+                {
+                    if (device.SerialNumber == serialNumber)
+                    {
+                        IsHaveCamera = true;
+                        ManufacturerName = device.ManufacturerName;
+                        ModelName = device.Model;
+                        SerialNumber = device.SerialNumber;
+                        CameraType = device.CameraType;
+                        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)
+                    {
+                        IMVDefine.IMV_GigEDeviceInfo gigEDeviceInfo =
+                        (IMVDefine.IMV_GigEDeviceInfo)
+                            ByteToStruct(deviceInfo.deviceSpecificInfo.gigeDeviceInfo,
+                                typeof(IMVDefine.IMV_GigEDeviceInfo));
+
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = deviceInfo.cameraName,
+                            CameraBrand = CameraBrand.IRayple,
+                            CameraType = CameraType.GIGE,
+                            ManufacturerName = deviceInfo.manufactureInfo,
+                            Model = deviceInfo.modelName,
+                            SerialNumber = deviceInfo.serialNumber,
+                            CameraIp = gigEDeviceInfo.ipAddress,
+                            IsFindByIp=true,
+                        });
+                    }
+                    else if (deviceInfo.nCameraType == IMV_ECameraType.typeU3vCamera)
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = deviceInfo.cameraName,
+                            CameraBrand = CameraBrand.IRayple,
+                            CameraType = CameraType.USB,
+                            ManufacturerName = deviceInfo.cameraName,
+                            Model = deviceInfo.modelName,
+                            SerialNumber = deviceInfo.serialNumber,
+                            CameraIp = "",
+                        });
+                    }
+                    else if (deviceInfo.nCameraType == IMV_ECameraType.typeCLCamera)
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = deviceInfo.cameraName,
+                            CameraBrand = CameraBrand.IRayple,
+                            CameraType = CameraType.Link,
+                            ManufacturerName = deviceInfo.cameraName,
+                            Model = deviceInfo.modelName,
+                            SerialNumber = deviceInfo.serialNumber,
+                            CameraIp = "",
+                        });
+                    }
+                    else
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = deviceInfo.cameraName,
+                            CameraBrand = CameraBrand.IRayple,
+                            CameraType = CameraType.Unknown,
+                            ManufacturerName = deviceInfo.cameraName,
+                            Model = deviceInfo.modelName,
+                            SerialNumber = deviceInfo.serialNumber,
+                            CameraIp = "",
+                        });
+                    }
+                }
+            }
+            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.CameraType == CameraType.GIGE)
+                {
+                    if (IsFindByIp)
+                    {
+                        if (device.CameraIp == CameraIp)
+                        {
+                            IsHaveCamera = true;
+                            ManufacturerName = device.ManufacturerName;
+                            ModelName = device.Model;
+                            SerialNumber = device.SerialNumber;
+                            CameraType = device.CameraType;
+                            int res = mvCameraAcq.IMV_CreateHandle(IMVDefine.IMV_ECreateHandleMode.modeByCameraKey, 0, SerialNumber);
+                            if (res == IMVDefine.IMV_OK)
+                            {
+
+                            }
+                            break;
+                        }
+                    }
+                    else
+                    {
+                        if (device.SerialNumber == SerialNumber)
+                        {
+                            IsHaveCamera = true;
+                            ManufacturerName = device.ManufacturerName;
+                            ModelName = device.Model;
+                            SerialNumber = device.SerialNumber;
+                            CameraType = device.CameraType;
+                            CameraIp = device.CameraIp;
+                            int res = mvCameraAcq.IMV_CreateHandle(IMVDefine.IMV_ECreateHandleMode.modeByCameraKey, 0, SerialNumber);
+                            if (res == IMVDefine.IMV_OK)
+                            {
+
+                            }
+                            break;
+                        }
+                    }
+                }
+                else
+                {
+                    if (device.SerialNumber == SerialNumber)
+                    {
+                        IsHaveCamera = true;
+                        ManufacturerName = device.ManufacturerName;
+                        ModelName = device.Model;
+                        SerialNumber = device.SerialNumber;
+                        CameraType = device.CameraType;
+                        int res = mvCameraAcq.IMV_CreateHandle(IMVDefine.IMV_ECreateHandleMode.modeByCameraKey, 0, SerialNumber);
+                        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>
+        /// <returns></returns>
+        public Task<bool> OpenDeviceAsync()
+        {
+            return Task.Run(() =>
+            {
+                return OpenDevice();
+            });
+        }
+
+        /// <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)
+            {
+                return null;
+            }
+        }
+
+        public static object ByteToStruct(Byte[] bytes, Type type)
+        {
+            int size = Marshal.SizeOf(type);
+            if (size > bytes.Length)
+            {
+                return null;
+            }
+
+            // 分配结构体内存空间
+            IntPtr structPtr = Marshal.AllocHGlobal(size);
+
+            // 将byte数组拷贝到分配好的内存空间
+            Marshal.Copy(bytes, 0, structPtr, size);
+
+            // 将内存空间转换为目标结构体
+            object obj = Marshal.PtrToStructure(structPtr, type);
+
+            // 释放内存空间
+            Marshal.FreeHGlobal(structPtr);
+
+            return obj;
+        }
+        #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
+    }
+}

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

@@ -0,0 +1,1049 @@
+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 int Index { get; set; }
+        public string ManufacturerName { get; private set; }
+        public bool IsFindByIp { get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public string CameraIp { 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, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
+        {
+            ID = id;
+            Name = serialNumber;
+            Index = index;
+            CameraIp = cameraip;
+            SerialNumber = serialNumber;
+            IsFindByIp = isFindByIp;
+            List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
+            foreach (ICameraInfo cameraInfo in allCameraInfos)
+            {
+                if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
+                {
+                    if (IsFindByIp)
+                    {
+                        if (cameraInfo[CameraInfoKey.DeviceIpAddress] == CameraIp)
+                        {
+                            CameraInfo = cameraInfo;
+                            m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
+                            ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
+                            ModelName = cameraInfo[CameraInfoKey.ModelName];
+                            SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
+                            CameraType = CameraType.GIGE;
+                            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;
+                        }
+                    }
+                    else
+                    {
+                        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];
+                            CameraType = CameraType.GIGE;
+                            CameraIp= cameraInfo[CameraInfoKey.DeviceIpAddress];
+                            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;
+                        }
+                    }
+                }
+                else
+                {
+                    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];
+                        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;
+        }
+
+        #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();
+                int i = 0;
+                foreach (ICameraInfo cameraInfo in allCameraInfos)
+                {
+                    if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = cameraInfo[CameraInfoKey.FullName],
+                            CameraBrand = CameraBrand.Basler_Pylon,
+                            CameraType = CameraType.GIGE,
+                            ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
+                            Model = cameraInfo[CameraInfoKey.ModelName],
+                            SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
+                            CameraIp = cameraInfo[CameraInfoKey.DeviceIpAddress],
+                            IsFindByIp = true,
+                        });
+                    }
+                    else if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("usb"))
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = cameraInfo[CameraInfoKey.FullName],
+                            CameraBrand = CameraBrand.Basler_Pylon,
+                            CameraType = CameraType.USB,
+                            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()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = cameraInfo[CameraInfoKey.FullName],
+                            CameraBrand = CameraBrand.Basler_Pylon,
+                            CameraType = CameraType.Link,
+                            ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
+                            Model = cameraInfo[CameraInfoKey.ModelName],
+                            SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
+                            CameraIp = "",
+                        });
+                    }
+                    else
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = cameraInfo[CameraInfoKey.FullName],
+                            CameraBrand = CameraBrand.Basler_Pylon,
+                            CameraType = CameraType.Unknown,
+                            ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
+                            Model = cameraInfo[CameraInfoKey.ModelName],
+                            SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
+                            CameraIp = "",
+                        });
+                    }
+                    i++;
+                }
+            }
+            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.DeviceType].ToLower().Contains("gige"))
+                    {
+                        if (IsFindByIp)
+                        {
+                            if (cameraInfo[CameraInfoKey.DeviceIpAddress] == CameraIp)
+                            {
+                                CameraInfo = cameraInfo;
+                                m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
+                                ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
+                                ModelName = cameraInfo[CameraInfoKey.ModelName];
+                                SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
+                                CameraType = CameraType.GIGE;
+                                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;
+                            }
+                        }
+                        else
+                        {
+                            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];
+                                CameraType = CameraType.GIGE;
+                                CameraIp = cameraInfo[CameraInfoKey.DeviceIpAddress];
+                                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;
+                            }
+                        }
+                    }
+                    else
+                    {
+                        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];
+                            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;
+                        }
+                    }
+                }
+                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;
+        }
+
+        /// <summary>
+        /// 打开相机异步
+        /// </summary>
+        /// <returns></returns>
+        public Task<bool> OpenDeviceAsync()
+        {
+            return Task.Run(() =>
+            {
+                return OpenDevice();
+            });
+        }
+
+        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();
+
+            Image = GrabResult2CogImage(grabResult);
+            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 = "";
+                            Image = GrabResult2CogImage(grabResult);
+                            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>
+        /// 将从相机获取的图像IGrabResult转换为CogImage图像
+        /// <paramref name="grabResult"/> 从相机获取的图像 IGrabResult </param>
+        /// </summary>
+        private ICogImage GrabResult2CogImage(IGrabResult grabResult)
+        {
+            if (grabResult == null) return null;
+
+            byte[] pixelData = grabResult.PixelData as byte[];
+
+            GCHandle pixelHandle = default;
+            bool pixelPinned = false;
+
+            GCHandle dstHandle = default;
+            bool dstPinned = false;
+
+            ICogImage result = null;
+
+            try
+            {
+                // 尽量 pin 原始像素数据(如果存在)
+                if (pixelData != null && pixelData.Length > 0)
+                {
+                    pixelHandle = GCHandle.Alloc(pixelData, GCHandleType.Pinned);
+                    pixelPinned = true;
+                }
+
+                IntPtr pixelPointer = pixelPinned ? pixelHandle.AddrOfPinnedObject() : IntPtr.Zero;
+
+                // 彩色图像处理
+                if (IsColorPixelFormat(grabResult.PixelTypeValue))
+                {
+                    // 使用 using 确保 Bitmap 及时释放
+                    using (Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb))
+                    {
+                        BitmapData bmpData = null;
+                        try
+                        {
+                            bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
+                            // 使用成员 converter 将 grabResult 转换到 bitmap 的缓冲区
+                            converter.OutputPixelFormat = PixelType.BGRA8packed;
+                            IntPtr ptrBmp = bmpData.Scan0;
+                            converter.Convert(ptrBmp, Math.Abs(bmpData.Stride) * bitmap.Height, grabResult);
+                        }
+                        finally
+                        {
+                            if (bmpData != null)
+                            {
+                                try { bitmap.UnlockBits(bmpData); } catch { }
+                            }
+                        }
+
+                        // 构造 Cognex 图像并返回副本(ScaleImage 通常返回独立图像)
+                        CogImage24PlanarColor colorImage = null;
+                        try
+                        {
+                            colorImage = new CogImage24PlanarColor(bitmap);
+                            result = colorImage.ScaleImage(bitmap.Width, bitmap.Height);
+                        }
+                        finally
+                        {
+                            // colorImage 若实现了 IDisposable 则释放(安全检查)
+                            (colorImage as IDisposable)?.Dispose();
+                        }
+                    }
+
+                    return result;
+                }
+                // 单通道(Mono)图像处理
+                else if (IsMonoPixelFormat(grabResult.PixelTypeValue))
+                {
+                    Basler.Pylon.PixelType enDstPixelType = Basler.Pylon.PixelType.Mono8;
+                    uint nSaveImageNeedSize = (uint)grabResult.Width * (uint)grabResult.Height;
+                    IntPtr pTemp = IntPtr.Zero;
+
+                    if (grabResult.PixelTypeValue == Basler.Pylon.PixelType.Mono8)
+                    {
+                        // 直接使用已 pin 的原始数据指针
+                        if (!pixelPinned)
+                        {
+                            // 如果原始不是 byte[],尝试从 grabResult 获取 PixelData(若支持)
+                            byte[] alt = grabResult.PixelData as byte[];
+                            if (alt != null)
+                            {
+                                pixelHandle = GCHandle.Alloc(alt, GCHandleType.Pinned);
+                                pixelPinned = true;
+                                pixelPointer = pixelHandle.AddrOfPinnedObject();
+                            }
+                        }
+                        pTemp = pixelPointer;
+                    }
+                    else
+                    {
+                        // 为转换后的 Mono8 数据分配临时缓冲并 pin
+                        byte[] dstBuffer = new byte[nSaveImageNeedSize];
+                        dstHandle = GCHandle.Alloc(dstBuffer, GCHandleType.Pinned);
+                        dstPinned = true;
+                        pTemp = dstHandle.AddrOfPinnedObject();
+
+                        // 使用局部的 PixelDataConverter 转换为 Mono8
+                        var pixelConverter = new Basler.Pylon.PixelDataConverter();
+                        pixelConverter.OutputPixelFormat = Basler.Pylon.PixelType.Mono8;
+                        pixelConverter.Convert(pTemp, nSaveImageNeedSize, grabResult);
+                    }
+
+                    if (pTemp == IntPtr.Zero)
+                    {
+                        return null;
+                    }
+
+                    // ConvertToICogImage 内部会做 ScaleImage,通常会产生独立拷贝
+                    result = ConvertToICogImage((uint)grabResult.Height, (uint)grabResult.Width, pTemp, enDstPixelType);
+
+                    return result;
+                }
+
+                return null;
+            }
+            finally
+            {
+                // 释放所有固定句柄,确保及时释放 pin 状态
+                try
+                {
+                    if (dstPinned)
+                    {
+                        dstHandle.Free();
+                        dstPinned = false;
+                    }
+                }
+                catch { }
+
+                try
+                {
+                    if (pixelPinned)
+                    {
+                        pixelHandle.Free();
+                        pixelPinned = false;
+                    }
+                }
+                catch { }
+            }
+        }
+
+        #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
+    }
+}

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

@@ -0,0 +1,659 @@
+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 int Index { get; set; }
+        public string ManufacturerName { get; private set; }
+        public bool IsFindByIp { get; private set; }
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public string CameraIp { 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, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
+        {
+            ID = id;
+            Name = serialNumber;
+            Index = index;
+            CameraIp = cameraip;
+            SerialNumber = serialNumber;
+            IsFindByIp = isFindByIp;
+            //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())//识别已安装的帧抓取器的类//帧抓取器:相机
+            {
+                int i = 0;
+                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;
+                        }
+                    }
+                    if (type== CameraType.GIGE)
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = item.Name,
+                            CameraBrand = CameraBrand.Cognex,
+                            CameraType = type,
+                            ManufacturerName = manufacturerName,
+                            Model = model,
+                            SerialNumber = item.SerialNumber,
+                            CameraIp = item.OwnedGigEAccess.CurrentIPAddress,
+                            IsFindByIp=true,
+                        });
+                    }
+                    else
+                    {
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = "",
+                            CameraBrand = CameraBrand.Cognex,
+                            CameraType = type,
+                            ManufacturerName = manufacturerName,
+                            Model = model,
+                            SerialNumber = item.SerialNumber,
+                            CameraIp = item.Name,
+                        });
+                    }
+                    i++;
+                }
+            }
+            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)
+                    {
+                        string[] bf1 = item.Name.Split(':');
+                        CameraType type = CameraType.GIGE;
+                        if (bf1.Length == 3)
+                        {
+                            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;
+                            }
+                        }
+                        if (type== CameraType.GIGE)
+                        {
+                            if (IsFindByIp)
+                            {
+                                if (CameraIp== item.OwnedGigEAccess.CurrentIPAddress)
+                                {
+                                    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 manufacturerName = item.Name;
+                                    string model = item.Name;
+                                    manufacturerName = bf1[1].Trim();
+                                    model = bf1[2].Trim();
+                                    ManufacturerName = manufacturerName;
+                                    ModelName = model;
+                                    CameraIp = item.OwnedGigEAccess.CurrentIPAddress;
+                                    IsHaveCamera = true;
+                                    break;
+                                }
+                            }
+                            else
+                            {
+                                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 manufacturerName = item.Name;
+                                    string model = item.Name;
+                                    manufacturerName = bf1[1].Trim();
+                                    model = bf1[2].Trim();
+                                    ManufacturerName = manufacturerName;
+                                    ModelName = model;
+                                    CameraIp = item.OwnedGigEAccess.CurrentIPAddress;
+                                    IsHaveCamera = true;
+                                    break;
+                                }
+                            }
+                        }
+                        else
+                        {
+                            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 manufacturerName = item.Name;
+                                string model = item.Name;
+                                manufacturerName = bf1[1].Trim();
+                                model = bf1[2].Trim();
+                                ManufacturerName = manufacturerName;
+                                ModelName = model;
+                                IsHaveCamera = true;
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (!IsHaveCamera)
+                {
+                    return false;
+                }
+            }
+            if (!IsConnected)
+            {
+                CameraConnectChangedEvent?.Invoke(ID, true);
+            }
+
+            IsConnected = true;
+            return IsConnected;
+        }
+
+        /// <summary>
+        /// 打开相机异步
+        /// </summary>
+        /// <returns></returns>
+        public Task<bool> OpenDeviceAsync()
+        {
+            return Task.Run(() =>
+            {
+                return OpenDevice();
+            });
+        }
+
+        /// <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
+    }
+}

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

@@ -0,0 +1,1012 @@
+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 System.Threading.Tasks;
+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 int Index { get; set; }
+
+        public CameraBrand CameraBrand { get => CameraBrand.Galaxy; }
+        public bool IsFindByIp { get; private set; }
+        public string ManufacturerName { get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public string CameraIp { 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, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
+        {
+            ID = id;
+            Name = serialNumber;
+            Index = index;
+            CameraIp = cameraip;
+            SerialNumber = serialNumber;
+            IsFindByIp = isFindByIp;
+            var list = GetDevices();
+            foreach (var device in list)
+            {
+                if (device.CameraType== CameraType.GIGE)
+                {
+                    if (IsFindByIp)
+                    {
+                        if (device.CameraIp == CameraIp)
+                        {
+                            IsHaveCamera = true;
+                            ManufacturerName = device.ManufacturerName;
+                            ModelName = device.Model;
+                            SerialNumber = device.SerialNumber;
+                            CameraType = CameraType.GIGE;
+                            break;
+                        }
+                    }
+                    else
+                    {
+                        if (device.SerialNumber == serialNumber)
+                        {
+                            IsHaveCamera = true;
+                            ManufacturerName = device.ManufacturerName;
+                            ModelName = device.Model;
+                            SerialNumber = device.SerialNumber;
+                            CameraType = CameraType.GIGE;
+                            break;
+                        }
+                    }
+                }
+                else
+                {
+                    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()
+                    {
+                        CameraNo = i + 1,
+                        CameraName = m_listIGXDeviceInfo[i].GetDisplayName(),
+                        CameraBrand = CameraBrand.Galaxy,
+                        CameraType = CameraType.GIGE,
+                        ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
+                        Model = m_listIGXDeviceInfo[i].GetModelName(),
+                        SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
+                        CameraIp = m_listIGXDeviceInfo[i].GetIP(),
+                        IsFindByIp=true,
+                    });
+                }
+                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()
+                    {
+                        CameraNo = i + 1,
+                        CameraName = m_listIGXDeviceInfo[i].GetDisplayName(),
+                        CameraBrand = CameraBrand.Galaxy,
+                        CameraType = CameraType.USB,
+                        ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
+                        Model = m_listIGXDeviceInfo[i].GetModelName(),
+                        SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
+                        CameraIp = "",
+                    });
+                }
+                else if (deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_UNKNOWN)
+                {
+                    cameras.Add(new Models.CameraInfo()
+                    {
+                        CameraNo = i + 1,
+                        CameraName = m_listIGXDeviceInfo[i].GetDisplayName(),
+                        CameraBrand = CameraBrand.Galaxy,
+                        CameraType = CameraType.Unknown,
+                        ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
+                        Model = m_listIGXDeviceInfo[i].GetModelName(),
+                        SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
+                        CameraIp = "",
+                    });
+                }
+            }
+            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)
+            {
+            }
+
+            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.CameraType == CameraType.GIGE)
+                {
+                    if (IsFindByIp)
+                    {
+                        if (device.CameraIp == CameraIp)
+                        {
+                            IsHaveCamera = true;
+                            ManufacturerName = device.ManufacturerName;
+                            ModelName = device.Model;
+                            SerialNumber = device.SerialNumber;
+                            CameraType = CameraType.GIGE;
+                            break;
+                        }
+                    }
+                    else
+                    {
+                        if (device.SerialNumber == SerialNumber)
+                        {
+                            IsHaveCamera = true;
+                            ManufacturerName = device.ManufacturerName;
+                            ModelName = device.Model;
+                            SerialNumber = device.SerialNumber;
+                            CameraType = CameraType.GIGE;
+                            break;
+                        }
+                    }
+                }
+                else
+                {
+                    if (device.SerialNumber == SerialNumber)
+                    {
+                        IsHaveCamera = true;
+                        ManufacturerName = device.ManufacturerName;
+                        ModelName = device.Model;
+                        SerialNumber = device.SerialNumber;
+                        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)
+                {
+                }
+            }
+
+            if (!IsConnected)
+            {
+                CameraConnectChangedEvent?.Invoke(ID, true);
+            }
+            IsConnected = true;
+            return IsConnected;
+        }
+
+        /// <summary>
+        /// 打开相机异步
+        /// </summary>
+        /// <returns></returns>
+        public Task<bool> OpenDeviceAsync()
+        {
+            return Task.Run(() =>
+            {
+                return OpenDevice();
+            });
+        }
+
+        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)
+            {
+                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
+    }
+}

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

@@ -0,0 +1,634 @@
+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;
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Interfaces;
+using TeamAAS_VP.Models;
+
+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 int Index { get; set; }
+        public string ManufacturerName { get; private set; }
+
+        public bool IsFindByIp {  get; private set; }
+
+        public string ModelName { get; private set; }
+
+        public string SerialNumber { get; private set; }
+
+        public string CameraIp { 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,int index, string name, string serialNumber,string cameraip,bool isFindByIp)
+        {
+            ID = id;
+            Name = serialNumber;
+            Index = index;
+            CameraIp=cameraip;
+            SerialNumber = serialNumber;
+            IsFindByIp= isFindByIp;
+            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));
+                    uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
+                    uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
+                    uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
+                    uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
+                    string ip= string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
+                    
+                    if (IsFindByIp)
+                    {
+                        if (CameraIp == ip)
+                        {
+                            ManufacturerName = stGigEDeviceInfo.chManufacturerName;
+                            ModelName = stGigEDeviceInfo.chModelName;
+                            SerialNumber = stGigEDeviceInfo.chSerialNumber;
+                            CameraType = CameraType.GIGE;
+                            CameraInfo = device;
+                            IsHaveCamera = true;
+                            break;
+                        }
+                    }
+                    else
+                    {
+                        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];
+                        uint nIp1 = ((gigeInfo.nCurrentIp & 0xff000000) >> 24);
+                        uint nIp2 = ((gigeInfo.nCurrentIp & 0x00ff0000) >> 16);
+                        uint nIp3 = ((gigeInfo.nCurrentIp & 0x0000ff00) >> 8);
+                        uint nIp4 = (gigeInfo.nCurrentIp & 0x000000ff);
+                        string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
+                        cameras.Add(new CameraInfo()
+                        {
+                            CameraNo= i + 1,
+                            CameraName = gigeInfo.UserDefinedName,
+                            CameraBrand = CameraBrand.HikRobot_MVS,
+                            CameraType = CameraType.GIGE,
+                            ManufacturerName = gigeInfo.chManufacturerName,
+                            Model = gigeInfo.chModelName,
+                            SerialNumber = gigeInfo.chSerialNumber,
+                            CameraIp = ip,
+                            IsFindByIp=true,
+                        });
+                    }
+                    else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_USB_DEVICE)
+                    {
+                        CUSBCameraInfo usbInfo = (CUSBCameraInfo)m_ltDeviceList[i];
+                        cameras.Add(new Models.CameraInfo()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = usbInfo.UserDefinedName,
+                            CameraBrand = CameraBrand.HikRobot_MVS,
+                            CameraType = CameraType.USB,
+                            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()
+                        {
+                            CameraNo = i + 1,
+                            CameraName = Info.chModelName,
+                            CameraBrand = CameraBrand.HikRobot_MVS,
+                            CameraType = CameraType.USB,
+                            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));
+                        uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
+                        uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
+                        uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
+                        uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
+                        string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
+
+                        if (IsFindByIp)
+                        {
+                            if (CameraIp == ip)
+                            {
+                                ManufacturerName = stGigEDeviceInfo.chManufacturerName;
+                                ModelName = stGigEDeviceInfo.chModelName;
+                                SerialNumber = stGigEDeviceInfo.chSerialNumber;
+                                CameraType = CameraType.GIGE;
+                                CameraInfo = device;
+                                IsHaveCamera = true;
+                                break;
+                            }
+                        }
+                        else
+                        {
+                            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>
+        /// <returns></returns>
+        public Task<bool> OpenDeviceAsync()
+        {
+            return Task.Run(() =>
+            {
+                return OpenDevice();
+            });
+        }
+
+        /// <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;
+        }
+    }
+}

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

@@ -0,0 +1,125 @@
+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>
+        /// <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;
+            }
+        }
+    }
+}

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

@@ -0,0 +1,65 @@
+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 CalibrationPath = "..//Calibration";
+
+        /// <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>
+        /// 视觉处理模板脚本路径
+        /// </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";
+    }
+}

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

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