feat: 增加海康相机视频采集与 SOP 配方编辑器

This commit is contained in:
sophelper 2026-11-05 21:37:09 +08:00
parent 5fb36a7569
commit d079c59b4f
16 changed files with 2369 additions and 27 deletions

4
.gitignore vendored
View File

@ -386,3 +386,7 @@ FodyWeavers.xsd
/docs
/AGENTS.md
*.onnx
# 海康 MVS 托管 SDK 随项目提供;原生运行时由现场安装。
!/libs/
!/libs/MvCameraControl.Net.dll

View File

@ -1,6 +1,6 @@
# SopHelper — 单 USB 相机 SOP 辅助
# SopHelper — 单相机 SOP 辅助
工位上接一个 UVC 相机,程序按 YAML 配方定义的步骤顺序判定操作员动作:逐步打勾、
工位上接一个 UVC 或海康工业相机,程序按 YAML 配方定义的步骤顺序判定操作员动作:逐步打勾、
超时报违规、留日志和快照。只做一件事,不做大而全。
引擎逻辑移植自 [VisionInspectionSystem](https://github.com/TheDoorIsUnlocked/VisionInspectionSystem)(MIT)。
@ -9,7 +9,7 @@
```
SopHelper.Engine net8.0 纯类库,零 UI 依赖(可单测、可被别的项目引用)
Camera/ UVC 采集:MSMF 优先,DSHOW 回退,单相机
Camera/ UVC(MSMF / DSHOW)及海康 MVS(GigE / USB)连续采集,单相机
Inference/ YOLOv8 ONNX(自带 letterbox + DFL 解码 + NMS)
MediaPipe 手部两阶段(palm 192 → 方形裁剪 → landmark 224)
Pipeline/ 采集 → 推理 → 结果帧,支持抽帧
@ -19,7 +19,7 @@ SopHelper.App net8.0-windows,Prism.DryIoc
纯 WPF 样式,无 HandyControl / SkiaSharp.Views.WPF
```
依赖只有 Prism.DryIoc、OpenCvSharp4、Microsoft.ML.OnnxRuntime、YamlDotNet —— 没有
依赖包括 Prism.DryIoc、OpenCvSharp4、Microsoft.ML.OnnxRuntime、YamlDotNet 和海康 MVS SDK —— 没有
GPL/AGPL 组件(YOLO 那段是自己写的,就是为了不引 GPL-3.0 的 YoloDotNet)。
## 跑起来
@ -41,6 +41,23 @@ dotnet build SopHelper.slnx
没有模型也能起:缺哪个就在日志里报哪条警告,只有手部类和计时类条件能工作。
### 海康相机取视频
参考 `plcsharp` 的 `MvCameraControl` 接法,支持海康机器人 GigE / USB 工业相机。
`libs/MvCameraControl.Net.dll` 随项目提供,构建和发布会自动复制;现场需安装
**MVS 4.5 或以上的 x64 运行时**(与 SDK 兼容),使用 x64 进程运行。
原生运行时通常位于 `C:\Program Files (x86)\Common Files\MVS\Runtime\Win64_x64`。
1. 先在 MVS 中确认能发现相机并正常取图,然后关闭 MVS 对该设备的连接。
2. GigE 相机与网卡配置在可互通的网段;USB 相机安装 MVS USB 驱动。
3. SOP 页点击「刷新」,选择 `海康 型号 / 序列号`,选择配方后点击「开始/停止」。
视频进入现有预览、ROI、推理和 SOP 判定流程。
4. 停止后可切换相机,再次开始会重新连接;运行及连接过程中禁止切换设备。
采集会设置连续模式并关闭触发;GigE 尝试优化包大小。输出统一为 BGR 三通道,
灰度、Bayer、RGB、YUV 等格式转换后再交给管线。SDK 缓冲在复制后立即归还。
未安装 MVS 时日志提示原因,UVC 仍可使用。此功能针对工业相机,不包含安防摄像头 RTSP。
## 配方
`configs/sop/*.yaml`,写好的例子见 `configs/sop/demo.yaml`。
@ -63,6 +80,21 @@ dotnet build SopHelper.slnx
违规:`timeout` / `wrong_order`(只看紧邻下一步)/ `object_removed`,同类 3 秒冷却。
### 配方编辑器
SOP 页配方行的「编辑 / 新建」。表单式,四个 tab:步骤 / 区域 / 全局设置 / 检测模型,
字段与 YAML 一一对应;method、区域名、hand、动作、违规类型都是下拉选——就是为了不让
"照抄别人的 YAML 拼错一个字母"这种事发生(下拉候选就是 `ConditionMethod` 那几项)。
区域改键名会同步更新所有引用它的步骤;删区域会清掉引用。
两条要注意的:
- **保存是重写整个文件,注释会丢**(YamlDotNet 不保留注释)。`demo.yaml` 顶上那些说明
注释,编辑器保存一次就没了——那些话是给编辑器的字段说的,不是给自己的。
- **运行中不能编辑**,和「应用」一致,得先停止。保存成功后界面会重扫 `configs/sop`、
选中刚存的配方并立即重新应用,区域覆盖层跟着更新。新建时文件名可填,之后不可改
(SOP 页是按文件名选配方的)。
## 判定语义(踩过的坑)
- **稳定帧门控**:按 `(步骤Id, 条件序号)` 累计连续命中帧数,达标才放行,未命中立即清零。

Binary file not shown.

View File

@ -9,6 +9,7 @@ using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Models;
using SopHelper.VVMs.RecipeEditor;
using SopHelper.VVMs.SopPage;
using SopHelper.VVMs.MainWindow;
@ -46,12 +47,15 @@ public partial class App
// 引擎层三件套。它们在 SopHelper.Engine 程序集里,上面的 [Model] 反射扫描只覆盖本程序集,
// 所以必须显式注册,否则 SOP 页 ViewModel 的构造注入解析不出来。
_ = containerRegistry.RegisterSingleton<ICameraService, UvcCameraService>();
_ = containerRegistry.RegisterSingleton<ICameraService, CameraService>();
_ = containerRegistry.RegisterSingleton<DetectionPipeline>();
_ = containerRegistry.RegisterSingleton<SopEngine>();
// ViewModel 工厂默认走容器解析,带构造注入的 ViewModel 必须先注册
_ = containerRegistry.Register<SopPageViewModel>();
// 配方编辑器弹窗(SOP 页「编辑」「新建」按钮弹出)
containerRegistry.RegisterDialog<RecipeEditor, RecipeEditorViewModel>("RecipeEditorDialog");
}
/// <summary>

View File

@ -132,6 +132,136 @@
</Setter>
</Style>
<!-- TextBox:同 ComboBox,WPF 默认模板是白底。配方编辑器满屏都是输入框,
不重写就是深底白框一片花。 -->
<Style TargetType="TextBox">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="CaretBrush" Value="{StaticResource Accent}" />
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Height" Value="26" />
<Setter Property="FontFamily" Value="Microsoft YaHei" />
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="SelectionBrush" Value="{StaticResource Accent}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4">
<ScrollViewer x:Name="PART_ContentHost" Margin="6,0" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="BorderBrush" Value="{StaticResource Accent}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- CheckBox:默认模板浅色主题底,同理重写 -->
<Style TargetType="CheckBox">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="FontFamily" Value="Microsoft YaHei" />
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="CheckBox">
<StackPanel Orientation="Horizontal">
<Border x:Name="box" Width="16" Height="16" CornerRadius="3"
Background="{StaticResource Panel}"
BorderBrush="{StaticResource Line}" BorderThickness="1"
VerticalAlignment="Center">
<Path x:Name="tick" Width="10" Height="10" Stretch="Fill"
Fill="{StaticResource Accent}" Visibility="Collapsed"
Data="M 0 4 L 3 8 L 10 0 L 12 2 L 4 11 L 1 7 Z" />
</Border>
<ContentPresenter Margin="6,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="tick" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="box" Property="BorderBrush" Value="{StaticResource Accent}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- TabControl:默认模板是浅色主题底(同 ComboBox 那个坑),配方编辑器要用它分区。 -->
<Style TargetType="TabControl">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TabPanel Grid.Row="0" IsItemsHost="True" Margin="0,0,0,6" />
<Border Grid.Row="1" Background="{StaticResource Panel}"
BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6">
<ContentPresenter ContentSource="SelectedContent" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="TabItem">
<Setter Property="Foreground" Value="{StaticResource FgDim}" />
<Setter Property="FontFamily" Value="Microsoft YaHei" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<Border x:Name="bd" Background="Transparent" BorderBrush="{StaticResource Line}"
BorderThickness="1" CornerRadius="5" Padding="{TemplateBinding Padding}" Margin="0,0,6,0">
<ContentPresenter ContentSource="Header" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bd" Property="Background" Value="#3300B8D4" />
<Setter TargetName="bd" Property="BorderBrush" Value="{StaticResource Accent}" />
<Setter Property="Foreground" Value="{StaticResource Fg}" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="BorderBrush" Value="{StaticResource Accent}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- 表单里的字段标签列 -->
<Style x:Key="Field" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
<Setter Property="Width" Value="74" />
<Setter Property="Foreground" Value="{StaticResource FgDim}" />
</Style>
<!-- 左侧导航 -->
<Style TargetType="ListBox">
<Setter Property="Background" Value="Transparent" />

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,530 @@
<UserControl x:Class="SopHelper.VVMs.RecipeEditor.RecipeEditor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor"
prism:ViewModelLocator.AutoWireViewModel="True"
Width="1020" Height="720" Background="{StaticResource Bg}">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<!-- 一行字段:标签 + 控件 -->
<Style x:Key="Row" TargetType="Grid">
<Setter Property="Margin" Value="0,0,0,6" />
</Style>
<!-- 列表里的删除按钮 -->
<Style x:Key="Mini" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Padding" Value="8,3" />
<Setter Property="FontSize" Value="12" />
</Style>
<DataTemplate DataType="{x:Type ed:TextItem}">
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Column="1" Margin="6,0,0,0" Style="{StaticResource Mini}"
Content="删" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type ed:ViolationRuleNode}">
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ComboBox ItemsSource="{Binding DataContext.Recipe.ViolationTypes, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Type}" />
<TextBox Grid.Column="1" Margin="6,0,0,0" Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Column="2" Margin="6,0,0,0" Text="{Binding Severity}" />
<Button Grid.Column="3" Margin="6,0,0,0" Style="{StaticResource Mini}"
Content="删" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
<!-- 步骤列表项 -->
<DataTemplate x:Key="StepRow" DataType="{x:Type ed:StepNode}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock>
<Run Text="{Binding Id}" Foreground="{StaticResource Accent}" /><Run Text=" " /><Run Text="{Binding Name}" />
</TextBlock>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button Content="↑" Style="{StaticResource Mini}" Margin="2,0,0,0"
Command="{Binding DataContext.Recipe.MoveStepUpCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" />
<Button Content="↓" Style="{StaticResource Mini}" Margin="2,0,0,0"
Command="{Binding DataContext.Recipe.MoveStepDownCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" />
<Button Content="×" Style="{StaticResource Mini}" Margin="2,0,0,0" Foreground="{StaticResource Ng}"
Command="{Binding DataContext.Recipe.RemoveStepCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</DataTemplate>
<!-- 区域列表项 -->
<DataTemplate x:Key="RegionRow" DataType="{x:Type ed:RegionNode}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Rectangle Width="10" Height="10" Fill="{Binding Brush}" VerticalAlignment="Center" />
<TextBlock Margin="6,0,0,0">
<Run Text="{Binding Key}" Foreground="{StaticResource Accent}" /><Run Text=" " /><Run Text="{Binding Name}" />
</TextBlock>
</StackPanel>
<Button Grid.Column="1" Content="×" Style="{StaticResource Mini}" Foreground="{StaticResource Ng}"
Command="{Binding DataContext.Recipe.RemoveRegionCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
<!-- 列表用普通条目模板(全局 ListBox 样式是给导航用的,这里要单列可选项) -->
<Style x:Key="Pick" TargetType="ListBox">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
</Style>
<Style x:Key="PickItem" TargetType="ListBoxItem">
<Setter Property="Padding" Value="8,6" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="bd" Background="Transparent" Padding="{TemplateBinding Padding}" CornerRadius="4">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="Background" Value="#22FFFFFF" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bd" Property="Background" Value="#3300B8D4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- ============ 头部:文件 + 配方名 ============ -->
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,10">
<TextBlock Text="{Binding Title}" Style="{StaticResource Title}" />
<TextBlock Text="文件名" Style="{StaticResource Field}" Margin="24,0,8,0" />
<TextBox Width="150" IsEnabled="{Binding Recipe.CanEditFileName}"
ToolTip="只有新建时能改——SOP 页是按文件名选配方的"
Text="{Binding Recipe.FileName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="配方名" Style="{StaticResource Field}" Margin="16,0,8,0" />
<TextBox Width="170" Text="{Binding Recipe.Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="版本" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Width="60" Text="{Binding Recipe.Version, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
<TabControl Grid.Row="1">
<!-- ==================== 步骤 ==================== -->
<TabItem Header="步骤">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="270" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<DockPanel>
<Button DockPanel.Dock="Bottom" Content="加步骤" Margin="0,8,0,0" Padding="0,6"
Command="{Binding Recipe.AddStepCommand}" />
<ListBox Style="{StaticResource Pick}" ItemContainerStyle="{StaticResource PickItem}"
ItemTemplate="{StaticResource StepRow}"
ItemsSource="{Binding Recipe.Steps}"
SelectedItem="{Binding Recipe.SelectedStep}" />
</DockPanel>
<ScrollViewer Grid.Column="1" Margin="12,0,0,0" VerticalScrollBarVisibility="Auto"
DataContext="{Binding Recipe.SelectedStep}">
<StackPanel>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="步骤号" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Id}" />
<TextBlock Grid.Column="2" Text="超时秒" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Timeout}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="步骤名" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Grid.Column="2" Text="节拍毫秒" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding StandardDurationMs}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="说明" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<!-- 判定条件 -->
<TextBlock Text="判定条件" Style="{StaticResource Title}" FontSize="13" Margin="0,10,0,6" />
<StackPanel>
<TextBlock Text="本步无判定条件(只能靠超时推进)" />
<Grid Style="{StaticResource Row}" Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="方法" Style="{StaticResource Field}" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.Methods, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.Method}" />
<TextBlock Grid.Column="2" Text="目标类别" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Detection.TargetObject, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="主区域" Style="{StaticResource Field}" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.Region}" />
<TextBlock Grid.Column="2" Text="起点区域" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<ComboBox Grid.Column="3" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.FromRegion}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="终点区域" Style="{StaticResource Field}" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.ToRegion}" />
<TextBlock Grid.Column="2" Text="手" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<ComboBox Grid.Column="3" ItemsSource="{Binding DataContext.Recipe.Hands, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.Hand}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="动作" Style="{StaticResource Field}" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.Actions, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.Action}" />
<TextBlock Grid.Column="2" Text="容差像素" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Detection.Tolerance}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="置信度" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Detection.MinConfidence}" />
<TextBlock Grid.Column="2" Text="稳定帧" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Detection.StableFrames}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="计时毫秒" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Detection.DurationMs}" HorizontalAlignment="Left" Width="120" />
</Grid>
<TextBlock Text="time_elapsed / hand_move / hand_action 豁免稳定帧门控(自带时序或瞬时语义)"
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
</StackPanel>
<!-- 必在物料 / 完成时必须存在 -->
<TextBlock Style="{StaticResource Title}" FontSize="13" Margin="0,10,0,6"
Text="{Binding MustKeep.Title}" />
<ItemsControl ItemsSource="{Binding MustKeep.Items}" />
<TextBlock Style="{StaticResource Title}" FontSize="13" Margin="0,10,0,6"
Text="{Binding RequiredObjects.Title}" />
<ItemsControl ItemsSource="{Binding RequiredObjects.Items}" />
<TextBlock Style="{StaticResource Title}" FontSize="13" Margin="0,10,0,6"
Text="{Binding ViolationRules.Title}" />
<ItemsControl ItemsSource="{Binding ViolationRules.Items}" />
</StackPanel>
</ScrollViewer>
</Grid>
</TabItem>
<!-- ==================== 区域 ==================== -->
<TabItem Header="区域">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="270" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<DockPanel>
<Button DockPanel.Dock="Bottom" Content="加区域" Margin="0,8,0,0" Padding="0,6"
Command="{Binding Recipe.AddRegionCommand}" />
<ListBox Style="{StaticResource Pick}" ItemContainerStyle="{StaticResource PickItem}"
ItemTemplate="{StaticResource RegionRow}"
ItemsSource="{Binding Recipe.Regions}"
SelectedItem="{Binding Recipe.SelectedRegion}" />
</DockPanel>
<StackPanel Grid.Column="1" Margin="12,0,0,0" DataContext="{Binding Recipe.SelectedRegion}">
<TextBlock Text="绝对像素坐标(相机原始分辨率),必须在现场画面上标定,别照抄别人的配方"
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,10" />
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="键名" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Key, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Grid.Column="2" Text="显示名" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="X1 / Y1" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding X1}" />
<TextBlock Grid.Column="2" Text="Y1" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Y1}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="X2 / Y2" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding X2}" />
<TextBlock Grid.Column="2" Text="Y2" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Y2}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="颜色" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Color, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" />
<Rectangle Grid.Column="1" Width="18" Height="18" Fill="{Binding Brush}"
HorizontalAlignment="Right" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="说明" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<TextBlock Text="改键名会同步更新所有步骤里对它的引用" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,8,0,0" />
</StackPanel>
</Grid>
</TabItem>
<!-- ==================== 全局设置 ==================== -->
<TabItem Header="全局设置">
<StackPanel Margin="10" DataContext="{Binding Recipe.Settings}">
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="置信度" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding ConfidenceThreshold}" HorizontalAlignment="Left" Width="120" />
<TextBlock Grid.Column="2" Text="稳定帧" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding StableFrames}" HorizontalAlignment="Left" Width="120" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="命中容差" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding PositionTolerance}" HorizontalAlignment="Left" Width="120" />
<TextBlock Grid.Column="2" Text="抽帧" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding FrameStride}" HorizontalAlignment="Left" Width="120" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="复位延时" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding ResetDelaySec}" HorizontalAlignment="Left" Width="120" />
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<CheckBox Content="超时违规" IsChecked="{Binding EnableTimeoutDetection}" Margin="0,0,20,0" />
<CheckBox Content="错序违规" IsChecked="{Binding EnableSkipDetection}" Margin="0,0,20,0" />
<CheckBox Content="完成后自动复位" IsChecked="{Binding AutoResetOnComplete}" />
</StackPanel>
</StackPanel>
</TabItem>
<!-- ==================== 检测模型 ==================== -->
<TabItem Header="检测模型">
<StackPanel Margin="10" DataContext="{Binding Recipe}">
<CheckBox Content="使用检测模型(object_* 与 hand_near_object / person_present 依赖它)"
IsChecked="{Binding HasModel}" Margin="0,0,0,10" />
<StackPanel Visibility="{Binding HasModel, Converter={StaticResource BoolToVis}}" DataContext="{Binding Model}">
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="模型路径" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Path, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="输入尺寸" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding InputSize}" HorizontalAlignment="Left" Width="120" />
</Grid>
<TextBlock Style="{StaticResource Title}" FontSize="13" Margin="0,10,0,6" Text="{Binding Title}" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,6">
<Button Content="加类别" Style="{StaticResource Mini}" Command="{Binding AddCommand}" />
</StackPanel>
<ItemsControl ItemsSource="{Binding Items}" />
</StackPanel>
<TextBlock Margin="0,10,0,0" Foreground="{StaticResource FgDim}"
Text="路径相对程序目录;当前用的 yolo11n 是 AGPL-3.0 血统,量产前换掉(见 README)" />
</StackPanel>
</TabItem>
</TabControl>
<!-- ============ 底部:校验提醒 + 保存 ============ -->
<Grid Grid.Row="2" Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="校验提醒(不阻止保存;现场常见先存草稿再补区域)" Foreground="{StaticResource FgDim}" FontSize="12" />
<ItemsControl ItemsSource="{Binding Warnings}" MaxHeight="66">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Foreground="{StaticResource Ng}" FontSize="12" Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Bottom">
<Button Content="取消" Command="{Binding CloseCommand}" Margin="0,0,8,0" />
<Button Content="保存" Command="{Binding SaveCommand}"
Background="{StaticResource Panel}" BorderBrush="{StaticResource Accent}" />
</StackPanel>
</Grid>
</Grid>
</UserControl>

View File

@ -0,0 +1,15 @@
namespace SopHelper.VVMs.RecipeEditor;
/// <summary>
/// 配方编辑器(弹窗)。ViewModel 按命名约定自动绑定,见 App.ConfigureViewModelLocator。
/// </summary>
public partial class RecipeEditor : System.Windows.Controls.UserControl
{
/// <summary>
/// 配方编辑器
/// </summary>
public RecipeEditor()
{
InitializeComponent();
}
}

View File

@ -0,0 +1,134 @@
using System.Collections.ObjectModel;
using System.IO;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using SopHelper.Engine.Sop;
namespace SopHelper.VVMs.RecipeEditor;
/// <summary>
/// 配方编辑器(SOP 页「编辑」按钮弹出)。表单在 EditorNodes 那一侧,
/// 保存时整体映射回 SopConfig 交给 SopConfigLoader 写 YAML。
/// 类名必须是"视图全名 + ViewModel",Prism 的 ViewModelLocator 按这个约定绑定(见 App)。
/// </summary>
public class RecipeEditorViewModel : BindableBase, IDialogAware
{
private RecipeNode _recipe = new();
private string _path = "";
private bool _isNew;
/// <summary>当前编辑的配方目录(configs/sop)</summary>
private string _directory = "";
/// <inheritdoc />
public string Title => _isNew ? "新建配方" : $"编辑配方 - {FileNameText}";
/// <inheritdoc />
public DialogCloseListener RequestClose { get; } = new();
/// <summary>标题栏显示的文件名</summary>
public string FileNameText => string.IsNullOrEmpty(_path) ? $"{_recipe.FileName}.yaml(新建)" : Path.GetFileName(_path);
/// <summary>编辑中的配方</summary>
public RecipeNode Recipe
{
get { return _recipe; }
private set
{
if (!SetProperty(ref _recipe, value)) return;
RaisePropertyChanged(nameof(FileNameText));
RaisePropertyChanged(nameof(Title));
}
}
/// <summary>保存前的校验提醒(不阻止保存——现场常见"先存草稿再补区域")</summary>
public ObservableCollection<string> Warnings { get; } = [];
/// <summary>保存</summary>
public DelegateCommand SaveCommand { get; private set; } = null!;
/// <summary>放弃修改关闭</summary>
public DelegateCommand CloseCommand { get; private set; } = null!;
/// <summary>
/// 配方编辑器
/// </summary>
public RecipeEditorViewModel()
{
SaveCommand = new DelegateCommand(Save);
CloseCommand = new DelegateCommand(() => RequestClose.Invoke(ButtonResult.Cancel));
}
/// <inheritdoc />
public void OnDialogOpened(IDialogParameters parameters)
{
_directory = parameters.GetValue<string>("directory") ?? "";
_path = parameters.GetValue<string>("path") ?? "";
_isNew = parameters.GetValue<bool>("new");
var config = parameters.GetValue<SopConfig>("config") ?? new SopConfig();
// 新建时文件名还没定,用配方名兜底;已存在的文件名不可改(SOP 页按文件名选配方)
var fileName = string.IsNullOrEmpty(_path) ? config.Sop.Name : Path.GetFileNameWithoutExtension(_path);
Recipe = RecipeNode.From(config, fileName, _isNew);
Recipe.Changed += RefreshWarnings;
RefreshWarnings();
}
/// <inheritdoc />
public bool CanCloseDialog() => true;
/// <inheritdoc />
public void OnDialogClosed()
{
}
private void Save()
{
if (string.IsNullOrWhiteSpace(Recipe.Name))
{
Warnings.Add("配方名(sop.name)不能为空");
return;
}
var fileName = string.IsNullOrWhiteSpace(Recipe.FileName) ? Recipe.Name : Recipe.FileName;
// 只取文件名部分,别让人在这儿塞路径
fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
_path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName + ".yaml") : _path;
try
{
// Save 内部落盘后会回读校验,返回值就是磁盘上那份
var saved = SopConfigLoader.Save(Recipe.ToConfig(), _path);
Warnings.Clear();
foreach (var warning in saved.Warnings) Warnings.Add(warning);
RequestClose.Invoke(new DialogParameters { { "path", Path.GetFileName(_path) } }, ButtonResult.OK);
}
catch (Exception ex)
{
// 写盘失败(文件被占用/只读)留给用户看,别让整个编辑器跟着炸
Warnings.Clear();
Warnings.Add("保存失败:" + ex.Message);
}
}
/// <summary>
/// 用当前编辑结果跑一遍加载器校验(就是"这一步永远不推进"那类问题)
/// </summary>
private void RefreshWarnings()
{
Warnings.Clear();
var config = Recipe.ToConfig();
SopConfigLoader.Validate(config);
foreach (var warning in config.Warnings) Warnings.Add(warning);
}
}

View File

@ -76,6 +76,8 @@
<TextBlock Text="相机" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center"
ItemsSource="{Binding Cameras}"
IsEnabled="{Binding CanSelectCamera}"
ToolTip="支持 UVC 和海康 GigE/USB 工业相机"
SelectedItem="{Binding SelectedCamera}">
<!-- 实测 DisplayMemberPath 在运行时没生效(显示 ToString()),显式模板最稳 -->
<ComboBox.ItemTemplate>
@ -93,13 +95,19 @@
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="配方" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center"
ItemsSource="{Binding Recipes}"
SelectedItem="{Binding SelectedRecipe}" />
<Button Grid.Column="2" Content="应用" Margin="6,0,0,0" Padding="10,4"
<Button Grid.Column="2" Content="编辑" Margin="6,0,0,0" Padding="10,4"
Command="{Binding EditRecipeCommand}" />
<Button Grid.Column="3" Content="新建" Margin="6,0,0,0" Padding="10,4"
Command="{Binding NewRecipeCommand}" />
<Button Grid.Column="4" Content="应用" Margin="6,0,0,0" Padding="10,4"
Command="{Binding ApplyRecipeCommand}" />
</Grid>

View File

@ -6,6 +6,7 @@ using System.Windows.Media.Imaging;
using System.Windows.Threading;
using OpenCvSharp;
using Prism.Commands;
using Prism.Dialogs;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Common;
@ -22,9 +23,16 @@ public class SopPageViewModel : ViewModelBase
private const int MaxLogLines = 300;
private const int MaxTopViolations = 3;
/// <summary>配方目录(相对程序目录)</summary>
private static string RecipeDirectory => Path.Combine(AppContext.BaseDirectory, "configs", "sop");
/// <summary>配方编辑器弹窗的注册名(见 App.RegisterTypes)</summary>
private const string EditorDialogName = "RecipeEditorDialog";
private readonly ICameraService _camera;
private readonly DetectionPipeline _pipeline;
private readonly SopEngine _engine;
private readonly IDialogService _dialogs;
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _renderTimer;
@ -48,6 +56,7 @@ public class SopPageViewModel : ViewModelBase
private string _inferenceText = "—";
private bool _isRunning;
private bool _isConnected;
private bool _isCameraBusy;
private double _frameWidth;
private double _frameHeight;
private double _confidence = 0.6;
@ -56,14 +65,24 @@ public class SopPageViewModel : ViewModelBase
/// <summary>
/// SOP 主页视图模型
/// </summary>
public SopPageViewModel(ICameraService camera, DetectionPipeline pipeline, SopEngine engine)
public SopPageViewModel(ICameraService camera, DetectionPipeline pipeline, SopEngine engine, IDialogService dialogs)
{
_camera = camera;
_pipeline = pipeline;
_engine = engine;
_dialogs = dialogs;
_dispatcher = Dispatcher.CurrentDispatcher;
_camera.ConnectionChanged += on => _dispatcher.BeginInvoke(() => IsConnected = on);
_camera.ConnectionChanged += on => _dispatcher.BeginInvoke(() =>
{
IsConnected = on;
if (!on && IsRunning)
{
IsRunning = false;
StatusText = "相机已断开";
RaiseCommands();
}
});
_camera.Error += message => _dispatcher.BeginInvoke(() => Log("warn", message));
_pipeline.ResultArrived += result => _dispatcher.BeginInvoke(() => OnResult(result));
@ -83,12 +102,14 @@ public class SopPageViewModel : ViewModelBase
LoadRecipes();
// 命令接线(DelegateCommand 的可用条件都挂在这里)
RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => !IsRunning);
RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
ResetCommand = new DelegateCommand(_engine.Reset, () => IsRunning);
ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => !IsRunning);
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
NewRecipeCommand = new DelegateCommand(NewRecipe, () => !IsRunning);
StatusText = "选择相机和配方,点开始";
}
@ -165,9 +186,17 @@ public class SopPageViewModel : ViewModelBase
public bool IsRunning
{
get { return _isRunning; }
set { SetProperty(ref _isRunning, value); }
set
{
if (!SetProperty(ref _isRunning, value)) return;
RaisePropertyChanged(nameof(CanSelectCamera));
RaiseCommands();
}
}
/// <summary>连接、枚举、采集期间不切换设备。</summary>
public bool CanSelectCamera => !IsRunning && !_isCameraBusy;
/// <summary>相机是否已连接</summary>
public bool IsConnected
{
@ -228,7 +257,23 @@ public class SopPageViewModel : ViewModelBase
/// <summary>快照</summary>
public DelegateCommand SnapshotCommand { get; private set; } = null!;
private bool CanStart() => SelectedCamera is not null || IsRunning;
/// <summary>编辑当前选中的配方(弹窗)</summary>
public DelegateCommand EditRecipeCommand { get; private set; } = null!;
/// <summary>新建配方(弹窗)</summary>
public DelegateCommand NewRecipeCommand { get; private set; } = null!;
private bool CanStart() => !_isCameraBusy && (SelectedCamera is not null || IsRunning);
private void SetCameraBusy(bool busy)
{
_isCameraBusy = busy;
RaisePropertyChanged(nameof(CanSelectCamera));
RaiseCommands();
}
/// <summary>运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用</summary>
private bool CanEditRecipe() => !IsRunning && !string.IsNullOrWhiteSpace(SelectedRecipe);
/// <summary>
/// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
@ -243,6 +288,8 @@ public class SopPageViewModel : ViewModelBase
ResetCommand?.RaiseCanExecuteChanged();
ApplyRecipeCommand?.RaiseCanExecuteChanged();
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
NewRecipeCommand?.RaiseCanExecuteChanged();
}
/// <summary>
@ -304,37 +351,125 @@ public class SopPageViewModel : ViewModelBase
/// </summary>
private void LoadRecipes()
{
var dir = Path.Combine(AppContext.BaseDirectory, "configs", "sop");
if (!Directory.Exists(dir)) return;
if (!Directory.Exists(RecipeDirectory)) return;
foreach (var file in Directory.GetFiles(dir, "*.yaml").OrderBy(f => f))
foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
if (Recipes.Count > 0) SelectedRecipe = Recipes[0];
}
private async Task RefreshCamerasAsync()
/// <summary>
/// 编辑器保存后:重扫目录(新建的文件要能选到),选中刚存的那个,再重新应用一次
/// </summary>
private void RefreshRecipes(string fileName)
{
Cameras.Clear();
Recipes.Clear();
foreach (var info in await _camera.EnumerateAsync())
Cameras.Add(info);
if (Directory.Exists(RecipeDirectory))
foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
if (Cameras.Count == 0)
var pick = Recipes.Contains(fileName) ? fileName : Recipes.FirstOrDefault();
if (pick is not null) SelectedRecipe = pick;
ApplyRecipe();
}
/// <summary>
/// 编辑当前选中的配方
/// </summary>
private void EditRecipe()
{
var path = Path.Combine(RecipeDirectory, SelectedRecipe!);
if (!File.Exists(path))
{
Log("warn", "没有枚举到 UVC 相机");
Log("warn", $"配方不存在:{path}");
return;
}
SelectedCamera = Cameras[0];
Log("info", $"枚举到 {Cameras.Count} 个相机");
// 编辑器读的是这个已解析的 config(含校验提醒),保存时再整体映射回去
OpenEditor(path, false, SopConfigLoader.Load(path));
}
/// <summary>
/// 新建配方(空白配方,文件名在编辑器里填)
/// </summary>
private void NewRecipe()
{
OpenEditor("", true, new SopConfig());
}
/// <summary>
/// 弹出配方编辑器。保存成功回来的是文件名(可能是新建的,所以列表要重扫)。
/// </summary>
private void OpenEditor(string path, bool isNew, SopConfig config)
{
var parameters = new DialogParameters();
parameters.Add("directory", RecipeDirectory);
parameters.Add("path", path);
parameters.Add("new", isNew);
parameters.Add("config", config);
_dialogs.ShowDialog(EditorDialogName, parameters, result =>
{
if (result.Result != ButtonResult.OK) return;
_dispatcher.BeginInvoke(() => RefreshRecipes(result.Parameters.GetValue<string>("path") ?? ""));
});
}
private async Task RefreshCamerasAsync()
{
if (!CanSelectCamera) return;
SetCameraBusy(true);
try
{
var previous = SelectedCamera;
SelectedCamera = null;
Cameras.Clear();
foreach (var info in await _camera.EnumerateAsync())
Cameras.Add(info);
if (Cameras.Count == 0)
{
Log("warn", "没有枚举到相机(支持 UVC、海康 GigE/USB 工业相机)");
return;
}
SelectedCamera = Cameras.FirstOrDefault(c => c.Kind == previous?.Kind &&
(c.Kind == CameraKind.Hikvision ? c.SerialNumber == previous.SerialNumber : c.Index == previous.Index))
?? Cameras[0];
Log("info", $"枚举到 {Cameras.Count} 个相机");
}
catch (Exception ex)
{
Log("warn", $"刷新相机失败:{ex.Message}");
}
finally { SetCameraBusy(false); }
}
private async Task StartStopAsync()
{
if (_isCameraBusy) return;
SetCameraBusy(true);
try { await StartStopCoreAsync(); }
catch (Exception ex)
{
await Task.Run(_camera.Disconnect);
IsRunning = false;
StatusText = "启动失败";
Log("warn", $"相机操作失败:{ex.Message}");
}
finally { SetCameraBusy(false); }
}
private async Task StartStopCoreAsync()
{
if (IsRunning)
{
_pipeline.Stop();
await Task.Run(_pipeline.Stop);
IsRunning = false;
StatusText = "已停止";
return;
@ -362,6 +497,7 @@ public class SopPageViewModel : ViewModelBase
if (!await _pipeline.StartAsync())
{
await Task.Run(_camera.Disconnect);
Log("warn", "采集启动失败");
return;
}
@ -375,7 +511,7 @@ public class SopPageViewModel : ViewModelBase
{
if (string.IsNullOrWhiteSpace(SelectedRecipe)) return;
var path = Path.Combine(AppContext.BaseDirectory, "configs", "sop", SelectedRecipe);
var path = Path.Combine(RecipeDirectory, SelectedRecipe);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");

View File

@ -0,0 +1,50 @@
namespace SopHelper.Engine.Camera;
/// <summary>统一枚举、按设备类型切换采集后端,推理管线始终订阅同一个服务。</summary>
public sealed class CameraService : ICameraService
{
private readonly ICameraService _uvc = new UvcCameraService();
private readonly ICameraService _hik = new HikvisionCameraService();
private ICameraService? _active;
public CameraService()
{
foreach (var service in new[] { _uvc, _hik })
{
service.FrameArrived += frame => FrameArrived?.Invoke(frame);
service.ConnectionChanged += connected => ConnectionChanged?.Invoke(connected);
service.Error += message => Error?.Invoke(message);
}
}
public bool IsConnected => _active?.IsConnected == true;
public bool IsGrabbing => _active?.IsGrabbing == true;
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error;
public async Task<List<CameraInfo>> EnumerateAsync()
{
// 优先展示海康;没有安装 MVS 时仍可使用 UVC。
var cameras = await _hik.EnumerateAsync();
cameras.AddRange(await _uvc.EnumerateAsync());
return cameras;
}
public async Task<bool> ConnectAsync(CameraInfo camera)
{
if (_active is not null) await Task.Run(_active.Disconnect);
_active = camera.Kind == CameraKind.Hikvision ? _hik : _uvc;
return await _active.ConnectAsync(camera);
}
public Task<bool> StartAsync() => _active?.StartAsync() ?? Task.FromResult(false);
public void Stop() => _active?.Stop();
public void Disconnect() => _active?.Disconnect();
public void Dispose()
{
_uvc.Dispose();
_hik.Dispose();
_active = null;
}
}

View File

@ -0,0 +1,242 @@
using MvCameraControl;
using OpenCvSharp;
namespace SopHelper.Engine.Camera;
/// <summary>海康 MVS 连续视频采集(GigE / USB),参考 plcsharp 的 SDK 接入方式。</summary>
public sealed class HikvisionCameraService : ICameraService
{
private readonly object _gate = new();
private IDevice? _device;
private CancellationTokenSource? _cts;
private Task? _grabTask;
private bool _initialized;
private bool _disposed;
private volatile bool _connected;
private volatile bool _grabbing;
private long _frameId;
public bool IsConnected => _connected;
public bool IsGrabbing => _grabbing;
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error;
private void EnsureInitialized()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_initialized) return;
Check(SDKSystem.Initialize(), "初始化 MVS");
_initialized = true;
}
private static List<IDeviceInfo> EnumerateDevices()
{
Check(DeviceEnumerator.EnumDevices(
DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice, out var devices), "枚举海康相机");
return devices;
}
public Task<List<CameraInfo>> EnumerateAsync() => Task.Run(() =>
{
lock (_gate)
{
try
{
EnsureInitialized();
return EnumerateDevices().Select((device, index) => new CameraInfo
{
Kind = CameraKind.Hikvision,
Index = index,
SerialNumber = device.SerialNumber,
Name = $"海康 {device.ModelName} / {device.SerialNumber}" +
(string.IsNullOrWhiteSpace(device.UserDefinedName) ? "" : $"({device.UserDefinedName})"),
}).ToList();
}
catch (Exception ex)
{
Report(ex);
return new List<CameraInfo>();
}
}
});
public Task<bool> ConnectAsync(CameraInfo camera) => Task.Run(() =>
{
lock (_gate)
{
try
{
DisconnectCore();
EnsureInitialized();
if (camera.Kind != CameraKind.Hikvision || string.IsNullOrWhiteSpace(camera.SerialNumber))
throw new InvalidOperationException("请选择有效的海康相机");
var info = EnumerateDevices().FirstOrDefault(d => d.SerialNumber == camera.SerialNumber)
?? throw new InvalidOperationException($"海康相机 {camera.SerialNumber} 已离线,请刷新列表");
_device = DeviceFactory.CreateDevice(info);
Check(_device.Open(), "打开海康相机");
if (_device is IGigEDevice gigE)
{
var result = gigE.GetOptimalPacketSize(out var packetSize);
if (result == MvError.MV_OK)
result = _device.Parameters.SetIntValue("GevSCPSPacketSize", packetSize);
if (result != MvError.MV_OK)
Error?.Invoke($"海康网络包大小优化失败(0x{result:X8}),继续使用默认值");
}
// 视频必须关闭触发,避免相机上一次留下的软触发/硬触发模式导致无图。
Check(_device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous"), "设置连续采集");
Check(_device.Parameters.SetEnumValueByString("TriggerMode", "Off"), "关闭触发模式");
_connected = true;
ConnectionChanged?.Invoke(true);
return true;
}
catch (Exception ex)
{
DisconnectCore();
Report(ex);
return false;
}
}
});
public Task<bool> StartAsync() => Task.Run(() =>
{
lock (_gate)
{
if (_grabbing) return true;
if (!_connected || _device is null || _disposed) return false;
try
{
StopCore();
Check(_device.StreamGrabber.StartGrabbing(), "启动海康取流");
_cts = new CancellationTokenSource();
var token = _cts.Token;
var device = _device;
_grabbing = true;
_grabTask = Task.Run(() => GrabLoop(device, token));
return true;
}
catch (Exception ex)
{
Report(ex);
return false;
}
}
});
private void GrabLoop(IDevice device, CancellationToken token)
{
try
{
while (!token.IsCancellationRequested)
{
var result = device.StreamGrabber.GetImageBuffer(500, out var buffer);
if (result == MvError.MV_E_NODATA) continue; // 有限超时,允许安全停止。
Check(result, "海康取帧");
Mat bgr;
try
{
bgr = CopyBgr(device, buffer.Image);
}
finally
{
// 转换失败也必须归还 SDK 缓冲,防止缓冲池耗尽。
device.StreamGrabber.FreeImageBuffer(buffer);
}
using var frame = new CameraFrame
{
FrameId = Interlocked.Increment(ref _frameId),
Timestamp = DateTime.Now,
Bgr = bgr,
};
if (token.IsCancellationRequested) break;
try { FrameArrived?.Invoke(frame); }
catch (Exception ex) { Error?.Invoke($"海康帧回调异常:{ex.Message}"); }
}
}
catch (Exception ex)
{
if (!token.IsCancellationRequested)
{
_connected = false;
ConnectionChanged?.Invoke(false);
Report(ex);
}
}
finally { _grabbing = false; }
}
private static Mat CopyBgr(IDevice device, IImage image)
{
if (image.PixelType == MvGvspPixelType.PixelType_Gvsp_BGR8_Packed)
{
using var view = Mat.FromPixelData((int)image.Height, (int)image.Width, MatType.CV_8UC3, image.PixelDataPtr);
return view.Clone();
}
if (image.PixelType == MvGvspPixelType.PixelType_Gvsp_Mono8)
{
using var view = Mat.FromPixelData((int)image.Height, (int)image.Width, MatType.CV_8UC1, image.PixelDataPtr);
var bgr = new Mat();
try { Cv2.CvtColor(view, bgr, ColorConversionCodes.GRAY2BGR); return bgr; }
catch { bgr.Dispose(); throw; }
}
// Bayer、RGB、YUV、高位深格式由 SDK 转换,不能当三通道直接读取。
var result = device.PixelTypeConverter.ConvertPixelType(image, out var converted, MvGvspPixelType.PixelType_Gvsp_BGR8_Packed);
using (converted)
{
Check(result, "转换海康像素格式");
if (converted is null) throw new InvalidOperationException("海康像素转换未返回图像");
using var view = Mat.FromPixelData((int)converted.Height, (int)converted.Width, MatType.CV_8UC3, converted.PixelDataPtr);
return view.Clone(); // 深拷贝后才能释放 SDK 图像。
}
}
public void Stop() { lock (_gate) StopCore(); }
private void StopCore()
{
_cts?.Cancel();
// 等采集线程归还最后一个缓冲后,再停止/关闭设备;不在超时后强行释放句柄。
_grabTask?.GetAwaiter().GetResult();
_grabTask = null;
_cts?.Dispose();
_cts = null;
if (_device is not null) _device.StreamGrabber.StopGrabbing();
_grabbing = false;
}
public void Disconnect() { lock (_gate) DisconnectCore(); }
private void DisconnectCore()
{
StopCore();
if (_device is not null)
{
try { _device.Close(); }
finally { _device.Dispose(); _device = null; }
}
var wasConnected = _connected;
_connected = false;
if (wasConnected) ConnectionChanged?.Invoke(false);
}
public void Dispose()
{
lock (_gate)
{
if (_disposed) return;
DisconnectCore();
if (_initialized) SDKSystem.Finalize();
_initialized = false;
_disposed = true;
}
}
private static void Check(int result, string operation)
{
if (result != MvError.MV_OK) throw new InvalidOperationException($"{operation}失败(0x{result:X8})");
}
private void Report(Exception ex) => Error?.Invoke(
$"海康相机:{ex.Message}。请确认已安装 MVS 4.5 或以上的 x64 运行时,设备已连接且未被其他程序占用。");
}

View File

@ -2,11 +2,18 @@ using OpenCvSharp;
namespace SopHelper.Engine.Camera;
public enum CameraKind { Uvc, Hikvision }
/// <summary>
/// 相机信息
/// </summary>
public class CameraInfo
{
public CameraKind Kind { get; set; }
/// <summary>海康设备序列号,重新枚举后仍可稳定定位设备</summary>
public string SerialNumber { get; set; } = "";
/// <summary>索引(UVC 设备号)</summary>
public int Index { get; set; }
@ -38,7 +45,7 @@ public class CameraFrame : IDisposable
}
/// <summary>
/// USB(UVC)相机服务。单相机最小版:一个采集线程 + 帧事件。
/// 单相机采集服务:一个采集线程 + 帧事件,支持 UVC 和海康工业相机。
/// </summary>
public interface ICameraService : IDisposable
{
@ -57,7 +64,7 @@ public interface ICameraService : IDisposable
/// <summary>错误</summary>
event Action<string>? Error;
/// <summary>枚举可用 UVC 相机</summary>
/// <summary>枚举可用相机</summary>
Task<List<CameraInfo>> EnumerateAsync();
/// <summary>连接相机</summary>

View File

@ -1,3 +1,4 @@
using System.Text;
using System.Text.RegularExpressions;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
@ -6,6 +7,7 @@ namespace SopHelper.Engine.Sop;
/// <summary>
/// 配方加载器:YAML → SopConfig,并做可用性校验(校验结果进 Warnings,界面要显示)。
/// 反向的 ToYaml/Save 给配方编辑器用。
/// </summary>
public static partial class SopConfigLoader
{
@ -40,11 +42,44 @@ public static partial class SopConfigLoader
return config;
}
/// <summary>
/// 把配方写回 YAML 文本(编辑器保存用)。注释会丢——YamlDotNet 不保留注释,
/// 所以 demo.yaml 里那些说明性注释只在手写的原始文件里有。
/// </summary>
public static string ToYaml(SopConfig config)
{
var serializer = new SerializerBuilder()
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.WithNewLine("\n")
.WithQuotingNecessaryStrings()
.Build();
var yaml = serializer.Serialize(config);
// 没配模型时别留一个空的 model: 节点——它会被读成"有 model 但 path 为空",
// 校验里那几条"需要模型"的提醒就哑了(本可空手告诉你的手已经空了)。
if (config.Sop.Model is null)
yaml = string.Join("\n", yaml.Split('\n').Where(l => l.TrimEnd() != " model:"));
return yaml.TrimEnd('\n') + "\n";
}
/// <summary>
/// 写回文件,并顺手校验一遍(校验提醒随返回值给出,编辑器要显示)。
/// </summary>
public static SopConfig Save(SopConfig config, string yamlPath)
{
File.WriteAllText(yamlPath, ToYaml(config), new UTF8Encoding(false));
// 落盘后再读一遍:校验的是文件里真正的内容,不是内存里那份
return Load(yamlPath);
}
/// <summary>
/// 校验:配方里写了引擎没实现的方法,一定要在这里报出来,
/// 否则现场表现是"这一步永远不推进",极难定位。
/// </summary>
private static void Validate(SopConfig config)
public static void Validate(SopConfig config)
{
var supported = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{

View File

@ -14,6 +14,10 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="MvCameraControl.Net">
<HintPath>..\..\libs\MvCameraControl.Net.dll</HintPath>
<Private>true</Private>
</Reference>
<PackageReference Include="OpenCvSharp4.Windows" Version="4.10.0.20241108" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.23.0" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />