移除配方全局设置并独立保存运行参数

This commit is contained in:
tfarcraw 2026-11-19 18:09:24 +08:00
parent 9206306ed0
commit 674e16e884
20 changed files with 229 additions and 197 deletions

View File

@ -19,13 +19,15 @@ pwsh -File tools/Start-HandAiD3.ps1
## 操作流程
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和自动曝光使用下拉菜单选择,关闭自动曝光后可填写以毫秒为单位的手动曝光时间(留空保留当前时间);海康相机可设置曝光时间。USB 采集统一使用 OpenCV:Windows 自动使用设备可用的兼容接口(DirectShow/MSMF),枚举结果记录内部接口标记,保证连接时沿用同一设备索引体系;Linux 使用 V4L2,无需选择采集方式。曝光控制分别适配 Windows 的对数档位及 V4L2 的原始控制值,Windows 会匹配最接近的曝光档位;设备不支持或控制失败时静默跳过。已移除 Windows 专属驱动属性页,旧设置中的采集方式及补偿字段会被忽略。设置按设备保存在 workspace/camera-device-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。抽帧、完成后自动复位和复位延时保存在独立的 `workspace/runtime-settings.json`,下次开始运行时生效,切换配方不会覆盖。
2. 配方编辑器包含“步骤、SOP流程视频、Agent助手”三页。区域导航和参数位于步骤页播放器下方,暂停视频后可直接拖动画框;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和自动曝光使用下拉菜单选择,关闭自动曝光后可填写以毫秒为单位的手动曝光时间(留空保留当前时间);海康相机可设置曝光时间。USB 采集统一使用 OpenCV:Windows 自动使用设备可用的兼容接口(DirectShow/MSMF),枚举结果记录内部接口标记,保证连接时沿用同一设备索引体系;Linux 使用 V4L2,无需选择采集方式。曝光控制分别适配 Windows 的对数档位及 V4L2 的原始控制值,Windows 会匹配最接近的曝光档位;设备不支持或控制失败时静默跳过。已移除 Windows 专属驱动属性页,旧设置中的采集方式及补偿字段会被忽略。设置按设备保存在 workspace/camera-device-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。
6. 过程图区显示实际送检的完成帧;日志显示帧号、裁剪范围、模型完成概率和耗时。完成图按步骤设置保存到配方目录。
配方只保存步骤、区域和工艺判据。稳定帧、命中容差由每个步骤设置;步骤超时秒数大于 0 时启用超时告警,0 表示关闭。旧配方加载时会把继承的全局稳定帧、容差和超时关闭状态迁移到步骤,保存时不再写出 `sop.settings`。首次应用或编辑旧配方且尚无独立运行设置时,会迁移其抽帧及复位参数;已有运行设置优先。
主页面只显示运行状态,推理后端诊断记录在运行日志中。SOP 停止采集时保留相机连接;再次开始复用同一设备,USB 参数未改变时不重复设置视频模式。切换相机、设备消失或退出程序时释放连接;采集失败时释放连接以便重试。停止后仍可修改相机配置和编辑配方。
Windows DirectShow 设置分辨率时可能把 MJPG 重置为 YUY2,因此程序在分辨率和帧率设置后再应用视频格式;Linux V4L2 保持先设置格式。2026-11-18 在 USB Camera(0c45:636d)上验证:原顺序在 640×480 和 800×600 下均约 15fps,修复后通过实际 UvcCameraService 采集均约 30fps,格式回读为 MJPG,手动曝光回读 15.625ms。设置接口返回成功和驱动回读 30fps 均不能代替实际采集计数。

View File

@ -0,0 +1,52 @@
using System.IO;
using System.Text.Json;
using SopHelper.Engine.Sop;
using SopHelper.Presentation;
namespace SopHelper.Models;
public sealed class RuntimeOptions
{
public int FrameStride { get; set; } = 1;
public bool AutoResetOnComplete { get; set; } = true;
public int ResetDelaySec { get; set; } = 1;
public void Apply(SopConfig config)
{
config.Sop.Settings.FrameStride = Math.Max(1, FrameStride);
config.Sop.Settings.AutoResetOnComplete = AutoResetOnComplete;
config.Sop.Settings.ResetDelaySec = Math.Max(1, ResetDelaySec);
}
}
/// <summary>执行方式独立保存,切换或导出配方不会覆盖运行设置。</summary>
public sealed class RuntimeSettingsStore(string root)
{
public static RuntimeSettingsStore Current => new(DesktopPlatform.WorkspaceRoot);
public string FilePath => Path.Combine(root, "workspace", "runtime-settings.json");
public RuntimeOptions? Read() => File.Exists(FilePath)
? JsonSerializer.Deserialize<RuntimeOptions>(File.ReadAllText(FilePath))
?? throw new InvalidDataException("运行设置内容为空") : null;
public RuntimeOptions LoadOrMigrate(SopConfig? legacy = null)
{
if (Read() is { } saved) return saved;
var options = legacy?.Sop.HasLegacySettings == true ? new RuntimeOptions
{
FrameStride = Math.Max(1, legacy.Sop.Settings.FrameStride),
AutoResetOnComplete = legacy.Sop.Settings.AutoResetOnComplete,
ResetDelaySec = Math.Max(1, legacy.Sop.Settings.ResetDelaySec),
} : new RuntimeOptions();
Save(options);
return options;
}
public void Save(RuntimeOptions options)
{
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
var temporary = FilePath + ".tmp";
try
{
File.WriteAllText(temporary, JsonSerializer.Serialize(options, new JsonSerializerOptions { WriteIndented = true }));
File.Move(temporary, FilePath, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
}

View File

@ -48,6 +48,7 @@ public sealed class SopVideoFlowTest : IDisposable
if (config.Sop.Steps.Count == 0) throw new InvalidOperationException("请先添加流程步骤,再测试流程");
// 深拷贝,测试轮次不修改编辑中的配方,也不自动开始下一轮。
var snapshot = SopConfigLoader.Parse(SopConfigLoader.ToYaml(config));
(SopHelper.Models.RuntimeSettingsStore.Current.Read() ?? new()).Apply(snapshot);
snapshot.Sop.Settings.AutoResetOnComplete = false;
snapshot.Sop.Model = null;
_stride = Math.Max(1, snapshot.Sop.Settings.FrameStride);

View File

@ -215,7 +215,6 @@ public class RecipeNode : EditorNode
}
/// <summary>全局设置(sop.settings)</summary>
public RecipeSettingsNode Settings { get; } = new();
/// <summary>区域(sop.regions,键 = 配方里引用的区域名)</summary>
public ObservableCollection<RegionNode> Regions { get; } = [];
@ -390,6 +389,7 @@ public class RecipeNode : EditorNode
/// </summary>
public static RecipeNode From(SopConfig config, string fileName, bool isNew)
{
SopConfigLoader.MigrateStepSettings(config);
var node = new RecipeNode
{
IsNew = isNew,
@ -398,7 +398,6 @@ public class RecipeNode : EditorNode
Description = config.Sop.Description,
};
node.Settings.CopyFrom(config.Sop.Settings);
foreach (var name in SopHelper.Engine.Training.PartCatalog.Read(config, null))
node.Parts.Items.Add(new TextItem { Text = name, RemoveCommand = node.Parts.RemoveCommand });
@ -471,7 +470,6 @@ public class RecipeNode : EditorNode
config.Sop.Description = Description;
config.Sop.Parts = Parts.Items.Select(p => p.Text).ToList();
Settings.CopyTo(config.Sop.Settings);
foreach (var region in Regions.Where(r => !string.IsNullOrWhiteSpace(r.Key)))
{
@ -524,92 +522,6 @@ public class RecipeNode : EditorNode
}
}
/// <summary>
/// sop.settings
/// </summary>
public class RecipeSettingsNode : EditorNode
{
private float _confidenceThreshold = 0.6f;
private int _stableFrames = 5;
private float _positionTolerance = 20f;
private bool _enableTimeoutDetection = true;
private bool _autoResetOnComplete = true;
private int _resetDelaySec = 1;
private int _frameStride = 1;
/// <summary>全局置信度阈值</summary>
public float ConfidenceThreshold
{
get { return _confidenceThreshold; }
set { SetProperty(ref _confidenceThreshold, value); }
}
/// <summary>默认稳定帧数(条件未写 stable_frames 时用它)</summary>
public int StableFrames
{
get { return _stableFrames; }
set { SetProperty(ref _stableFrames, value); }
}
/// <summary>区域命中容差(像素)</summary>
public float PositionTolerance
{
get { return _positionTolerance; }
set { SetProperty(ref _positionTolerance, value); }
}
/// <summary>启用超时违规</summary>
public bool EnableTimeoutDetection
{
get { return _enableTimeoutDetection; }
set { SetProperty(ref _enableTimeoutDetection, value); }
}
/// <summary>整轮完成后自动复位</summary>
public bool AutoResetOnComplete
{
get { return _autoResetOnComplete; }
set { SetProperty(ref _autoResetOnComplete, value); }
}
/// <summary>复位前停留秒数</summary>
public int ResetDelaySec
{
get { return _resetDelaySec; }
set { SetProperty(ref _resetDelaySec, value); }
}
/// <summary>抽帧间隔(1=每帧都判)</summary>
public int FrameStride
{
get { return _frameStride; }
set { SetProperty(ref _frameStride, value); }
}
/// <summary>读入</summary>
public void CopyFrom(SopSettings from)
{
ConfidenceThreshold = from.ConfidenceThreshold;
StableFrames = from.StableFrames;
PositionTolerance = from.PositionTolerance;
EnableTimeoutDetection = from.EnableTimeoutDetection;
AutoResetOnComplete = from.AutoResetOnComplete;
ResetDelaySec = from.ResetDelaySec;
FrameStride = from.FrameStride;
}
/// <summary>写出</summary>
public void CopyTo(SopSettings to)
{
to.ConfidenceThreshold = ConfidenceThreshold;
to.StableFrames = StableFrames;
to.PositionTolerance = PositionTolerance;
to.EnableTimeoutDetection = EnableTimeoutDetection;
to.AutoResetOnComplete = AutoResetOnComplete;
to.ResetDelaySec = ResetDelaySec;
to.FrameStride = FrameStride;
}
}
/// <summary>
/// sop.model
/// </summary>

View File

@ -393,48 +393,6 @@
</Grid>
</Grid>
</TabItem>
<TabItem Header="全局设置">
<StackPanel Margin="10" DataContext="{Binding Recipe.Settings}">
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="置信度" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding ConfidenceThreshold, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
<TextBlock Grid.Column="2" Text="稳定帧" Margin="16,0,8,0" Classes="Field" />
<TextBox Grid.Column="3" Text="{Binding StableFrames, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="命中容差" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding PositionTolerance, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
<TextBlock Grid.Column="2" Text="抽帧" Margin="16,0,8,0" Classes="Field" />
<TextBox Grid.Column="3" Text="{Binding FrameStride, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="复位延时" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding ResetDelaySec, Mode=TwoWay}" 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 AutoResetOnComplete}" />
</StackPanel>
</StackPanel>
</TabItem>
<TabItem Header="SOP流程视频">
<Grid Margin="10" RowDefinitions="Auto,*">
<Grid Grid.Row="1" DataContext="{Binding SopRecording}" IsVisible="{Binding DataContext.HasSopRecording, RelativeSource={RelativeSource AncestorType=UserControl}}" RowDefinitions="Auto,*,Auto,Auto,Auto">

View File

@ -147,6 +147,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
else if (_cameraInfo is null) PreviewStatus = "请在 SOP 页先选择相机,或打开图片;选中区域后在图上拖动画框";
var config = parameters.GetValue<SopConfig>("config") ?? new SopConfig();
if (!_isNew && config.Sop.HasLegacySettings)
SopHelper.Models.RuntimeSettingsStore.Current.LoadOrMigrate(config);
// 新建时文件名还没定,用配方名兜底;已存在的文件名不可改(SOP 页按文件名选配方)
var fileName = string.IsNullOrEmpty(_path) ? config.Sop.Name : Path.GetFileNameWithoutExtension(_path);

View File

@ -51,13 +51,19 @@
<Slider IsEnabled="{Binding CanSelectCamera}" Grid.Column="1" Minimum="1" Maximum="10" TickFrequency="1" IsSnapToTickEnabled="True" Value="{Binding FrameStride}" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="{Binding FrameStride}" HorizontalAlignment="Right" Foreground="{StaticResource FgDim}" />
</Grid>
<CheckBox x:Name="AutoResetCheckBox" Content="完成后自动复位" IsChecked="{Binding AutoResetOnComplete}" IsEnabled="{Binding CanSelectCamera}" Margin="0,10,0,0" />
<Grid ColumnDefinitions="Auto,*" Margin="0,8,0,0">
<TextBlock Text="复位延时(秒)" VerticalAlignment="Center" Margin="0,0,12,0" />
<NumericUpDown x:Name="ResetDelayInput" Grid.Column="1" Value="{Binding ResetDelaySec}" Minimum="1" Maximum="3600" Increment="1"
IsEnabled="{Binding CanSelectCamera}" HorizontalAlignment="Left" Width="120" />
</Grid>
</StackPanel>
</Border>
<Border Classes="panel">
<StackPanel Spacing="8">
<TextBlock Text="当前已应用配方" Classes="Title" />
<TextBlock Text="{Binding ActiveRecipe}" TextWrapping="Wrap" />
<TextBlock Text="选择配方后点击“应用”;抽帧参数在下次开始运行时生效。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
<TextBlock Text="选择配方后点击“应用”。运行参数自动保存,在下次开始运行时生效,切换配方不会覆盖。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
</StackPanel>
</Border>
<TextBlock Text="{Binding StatusText}" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />

View File

@ -92,7 +92,8 @@ public class SopPageViewModel : ViewModelBase
private double _frameWidth;
private double _frameHeight;
private double _confidence = 0.6;
private int _frameStride = 2;
private readonly SopHelper.Models.RuntimeSettingsStore _runtimeStore = SopHelper.Models.RuntimeSettingsStore.Current;
private SopHelper.Models.RuntimeOptions _runtimeOptions = new();
/// <summary>
/// SOP 主页视图模型
@ -106,6 +107,7 @@ public class SopPageViewModel : ViewModelBase
_pipeline.ShouldDetectHands = () => _engine.RequiresHandDetection;
_dialogs = dialogs;
_dispatcher = Dispatcher.CurrentDispatcher;
_runtimeOptions = _runtimeStore.Read() ?? new();
_camera.ConnectionChanged += on => _dispatcher.BeginInvoke(() =>
{
@ -312,8 +314,23 @@ public class SopPageViewModel : ViewModelBase
/// <summary>抽帧间隔</summary>
public int FrameStride
{
get { return _frameStride; }
set { SetProperty(ref _frameStride, value); }
get => _runtimeOptions.FrameStride;
set { if (!CanSelectCamera || value == FrameStride) return; _runtimeOptions.FrameStride = Math.Clamp(value, 1, 10); SaveRuntimeOptions(); }
}
public bool AutoResetOnComplete
{
get => _runtimeOptions.AutoResetOnComplete;
set { if (!CanSelectCamera || value == AutoResetOnComplete) return; _runtimeOptions.AutoResetOnComplete = value; SaveRuntimeOptions(); }
}
public int ResetDelaySec
{
get => _runtimeOptions.ResetDelaySec;
set { if (!CanSelectCamera || value == ResetDelaySec) return; _runtimeOptions.ResetDelaySec = Math.Max(1, value); SaveRuntimeOptions(); }
}
private void SaveRuntimeOptions()
{
_runtimeStore.Save(_runtimeOptions);
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
}
/// <summary>打开所选相机的独立配置窗口</summary>
@ -769,7 +786,8 @@ public class SopPageViewModel : ViewModelBase
}
// 抽帧从界面参数覆盖配方默认值
_engine.Config.Sop.Settings.FrameStride = Math.Max(1, FrameStride);
_runtimeOptions.Apply(_engine.Config);
_pipeline.SetFrameStride(FrameStride);
if (!await _pipeline.StartAsync())
{
@ -797,6 +815,9 @@ public class SopPageViewModel : ViewModelBase
}
var config = SopConfigLoader.Load(path);
_runtimeOptions = _runtimeStore.LoadOrMigrate(config);
_runtimeOptions.Apply(config);
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
config.Sop.Model = null;
_engine.Load(config);

View File

@ -118,6 +118,8 @@ public class DetectionPipeline : IDisposable
/// <summary>
/// 启动(相机需已连接)
/// </summary>
public void SetFrameStride(int stride) => _options.FrameStride = Math.Max(1, stride);
public async Task<bool> StartAsync()
{
ObjectDisposedException.ThrowIf(_disposed, this);

View File

@ -25,7 +25,6 @@ public class ConditionResult
/// </summary>
public class ConditionEvaluator
{
private readonly SopSettings _settings;
private readonly Dictionary<string, DetRect> _regions;
/// <summary>稳定帧计数:key = "步骤Id:条件序号"</summary>
@ -44,7 +43,6 @@ public class ConditionEvaluator
/// </summary>
public ConditionEvaluator(SopSettings settings, Dictionary<string, DetRect> regions)
{
_settings = settings;
_regions = regions;
}
@ -83,7 +81,7 @@ public class ConditionEvaluator
var result = ApplyStableGate(step.Id, probeSeed, condition, raw);
result.RawMatched = rawMatched;
result.RequiredFrames = condition.Method.ToLowerInvariant() is ConditionMethod.HandMove or ConditionMethod.TimeElapsed ? 0
: Math.Max(1, condition.StableFrames > 0 ? condition.StableFrames : _settings.StableFrames);
: Math.Max(1, condition.StableFrames);
result.StableFrames = _stablePassCounts.GetValueOrDefault($"{step.Id}:{probeSeed}", rawMatched ? 1 : 0);
TrackVisits(step, condition, frame);
@ -96,7 +94,7 @@ public class ConditionEvaluator
/// </summary>
private ConditionResult EvaluateCondition(StepDef step, StepCondition condition, FrameResult frame)
{
var tolerance = condition.Tolerance > 0 ? condition.Tolerance : _settings.PositionTolerance;
var tolerance = Math.Max(0, condition.Tolerance);
switch (condition.Method.ToLowerInvariant())
{
@ -192,7 +190,7 @@ public class ConditionEvaluator
if (exempt) return raw;
var required = condition.StableFrames > 0 ? condition.StableFrames : _settings.StableFrames;
var required = Math.Max(1, condition.StableFrames);
if (required <= 1) return raw;
var key = $"{stepId}:{probeSeed}";
@ -222,7 +220,7 @@ public class ConditionEvaluator
/// </summary>
private void TrackVisits(StepDef step, StepCondition condition, FrameResult frame)
{
var tolerance = condition.Tolerance > 0 ? condition.Tolerance : _settings.PositionTolerance;
var tolerance = Math.Max(0, condition.Tolerance);
// 手访问过哪些区域
foreach (var hand in frame.Hands)

View File

@ -33,8 +33,15 @@ public class SopBody
[YamlMember(DefaultValuesHandling = DefaultValuesHandling.OmitNull)]
public List<string>? Parts { get; set; }
/// <summary>全局设置</summary>
public SopSettings Settings { get; set; } = new();
/// <summary>引擎运行参数及旧配方迁移值;保存配方时不写出。</summary>
private SopSettings _settings = new();
public SopSettings Settings
{
get => _settings;
set { _settings = value ?? new(); HasLegacySettings = true; }
}
[YamlIgnore]
public bool HasLegacySettings { get; set; }
/// <summary>区域定义(键 = 配方里引用的区域名)</summary>
public Dictionary<string, RegionDef> Regions { get; set; } = new(StringComparer.OrdinalIgnoreCase);
@ -47,13 +54,10 @@ public class SopBody
}
/// <summary>
/// sop.settings
/// 引擎运行参数;旧配方 settings 只读兼容。
/// </summary>
public class SopSettings
{
/// <summary>全局置信度阈值</summary>
public float ConfidenceThreshold { get; set; } = 0.6f;
/// <summary>默认稳定帧数(条件未写 stable_frames 时用它)</summary>
public int StableFrames { get; set; } = 5;

View File

@ -37,6 +37,7 @@ public static partial class SopConfigLoader
var config = deserializer.Deserialize<SopConfig>(yaml) ?? new SopConfig();
MigrateStepSettings(config);
Validate(config);
return config;
@ -48,13 +49,17 @@ public static partial class SopConfigLoader
/// </summary>
public static string ToYaml(SopConfig config)
{
// 在副本上迁移;导出不能改变正在编辑或运行的对象。
var saved = System.Text.Json.JsonSerializer.Deserialize<SopConfig>(System.Text.Json.JsonSerializer.Serialize(config))!;
MigrateStepSettings(saved, config.Sop.HasLegacySettings);
var serializer = new SerializerBuilder()
.WithAttributeOverride<SopBody>(body => body.Settings, new YamlIgnoreAttribute())
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.WithNewLine("\n")
.WithQuotingNecessaryStrings()
.Build();
var yaml = serializer.Serialize(config);
var yaml = serializer.Serialize(saved);
// 没配模型时别留一个空的 model: 节点——它会被读成"有 model 但 path 为空",
// 校验里那几条"需要模型"的提醒就哑了(本可空手告诉你的手已经空了)。
@ -64,6 +69,22 @@ public static partial class SopConfigLoader
return yaml.TrimEnd('\n') + "\n";
}
public static void MigrateStepSettings(SopConfig config, bool? useLegacy = null)
{
var settings = config.Sop.Settings;
var legacy = useLegacy ?? config.Sop.HasLegacySettings;
foreach (var step in config.Sop.Steps)
{
if (step.Detection is { } condition)
{
if (condition.StableFrames <= 0) condition.StableFrames = legacy ? Math.Max(1, settings.StableFrames) : 5;
if (condition.Tolerance <= 0) condition.Tolerance = legacy ? Math.Max(0, settings.PositionTolerance) : 0;
}
if (!settings.EnableTimeoutDetection) step.Timeout = 0;
}
settings.EnableTimeoutDetection = true;
}
/// <summary>
/// 写回文件,并顺手校验一遍(校验提醒随返回值给出,编辑器要显示)。
/// </summary>

View File

@ -188,7 +188,7 @@ public partial class SopEngine
};
if (hand is null) return false;
var (x, y) = hand.Center;
return region.Contains(x, y, condition.Tolerance > 0 ? condition.Tolerance : _config.Sop.Settings.PositionTolerance);
return region.Contains(x, y, Math.Max(0, condition.Tolerance));
}
private void CaptureFollowingStep(FrameResult frame, Func<byte[]>? captureJpeg, Func<RegionDef?, byte[]>? captureDecisionImage)

View File

@ -125,6 +125,7 @@ public partial class SopEngine
public void Load(SopConfig config)
{
Stop();
SopConfigLoader.MigrateStepSettings(config);
_config = config;
Statistics = GetStatistics(config.Sop.Name);

View File

@ -14,6 +14,8 @@ public static class SopStepTransfer
{
Check(current);
var document = new SopConfig();
document.Sop.Settings = Copy(current.Sop.Settings);
document.Sop.HasLegacySettings = current.Sop.HasLegacySettings;
document.Sop.Name = current.Sop.Name;
document.Sop.Description = "步骤导出:导入时仅读取步骤、关联区域和零件名称";
document.Sop.Steps = current.Sop.Steps.Select(Copy).ToList();
@ -44,6 +46,7 @@ public static class SopStepTransfer
else document = ParseYaml(text);
if (document is null) throw new FormatException("文件中没有步骤配置");
Check(document);
SopConfigLoader.MigrateStepSettings(document);
return document;
}

View File

@ -1,5 +1,3 @@
using SopHelper.Engine.Common;
namespace SopHelper.Engine.Sop;
/// <summary>
@ -24,7 +22,7 @@ public class ViolationEvent
}
/// <summary>
/// 违规判定:超时 / 必留物被拿走。
/// 步骤超时违规判定。
/// 每类违规带冷却,避免逐帧刷屏(参考项目用 3s,这里保持一致)。
/// </summary>
public class ViolationDetector
@ -32,18 +30,13 @@ public class ViolationDetector
/// <summary>同类违规最小间隔</summary>
private static readonly TimeSpan Cooldown = TimeSpan.FromSeconds(3);
private readonly SopSettings _settings;
private readonly Dictionary<string, DateTime> _lastFired = [];
/// <summary>每个必留物体最近一次被检出的时刻(判"被拿走"用)</summary>
private readonly Dictionary<string, DateTime> _lastSeenObject = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 违规判定
/// </summary>
public ViolationDetector(SopSettings settings)
{
_settings = settings;
}
/// <summary>
@ -52,7 +45,6 @@ public class ViolationDetector
public void Reset()
{
_lastFired.Clear();
_lastSeenObject.Clear();
}
/// <summary>
@ -60,7 +52,6 @@ public class ViolationDetector
/// </summary>
public ViolationEvent? CheckTimeout(StepDef step, DateTime stepEnteredAt)
{
if (!_settings.EnableTimeoutDetection) return null;
if (step.Timeout <= 0) return null;
var elapsed = DateTime.Now - stepEnteredAt;
@ -71,41 +62,6 @@ public class ViolationDetector
return Fire(rule, step.Id, $"步骤 {step.Id}「{step.Name}」超时 {elapsed.TotalSeconds:F0}s(限 {step.Timeout}s)");
}
/// <summary>
/// 必留物被拿走:本步期间 must_keep 的物体连续若干帧消失
/// </summary>
public ViolationEvent? CheckMustKeep(StepDef step, FrameResult frame)
{
if (step.MustKeep.Count == 0) return null;
foreach (var label in step.MustKeep)
{
var hit = frame.Detections.Any(d => d.Label.Equals(label, StringComparison.OrdinalIgnoreCase)
&& d.Confidence >= _settings.ConfidenceThreshold);
if (hit)
{
_lastSeenObject[label] = DateTime.Now;
continue;
}
// 从没见过的必留物不报"被拿走"(配方类别名与模型不一致是常态)
if (!_lastSeenObject.TryGetValue(label, out var lastSeen)) continue;
if ((DateTime.Now - lastSeen).TotalSeconds < 2) continue;
var rule = FindRule(step, "object_removed");
var violation = Fire(rule, step.Id, $"步骤 {step.Id}「{step.Name}」期间 {label} 被拿走");
if (violation is not null) return violation;
// 报过之后重新计时,避免物体一直不在就每帧报
_lastSeenObject[label] = DateTime.Now;
}
return null;
}
private static ViolationRule? FindRule(StepDef step, string type)
{
return step.ViolationRules.FirstOrDefault(r => r.Type.Equals(type, StringComparison.OrdinalIgnoreCase));

View File

@ -86,6 +86,36 @@ internal static class Smoke
var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null;
await Task.Delay(150);
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
if(Environment.GetCommandLineArgs().Contains("--runtime-settings-only"))
{
var model=app.Container.Resolve<SopPageViewModel>();
var view=new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model);
var dialog=new Window{Content=view,Width=900,Height=720};dialog.Show();await Task.Delay(100);
try
{
view.GetVisualDescendants().OfType<Slider>().Single().Value=3;
view.FindControl<CheckBox>("AutoResetCheckBox")!.IsChecked=false;
view.FindControl<NumericUpDown>("ResetDelayInput")!.Value=4;
await Task.Delay(50);
var saved=RuntimeSettingsStore.Current.Read()!;
Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4
&&saved.FrameStride==3&&!saved.AutoResetOnComplete&&saved.ResetDelaySec==4,"运行设置控件绑定并自动保存三个运行参数");
model.ApplyRecipeCommand.Execute();
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
Check(engine.Config.Sop.Settings.FrameStride==3&&!engine.Config.Sop.Settings.AutoResetOnComplete&&engine.Config.Sop.Settings.ResetDelaySec==4,
"应用配方不会覆盖运行设置,并传给引擎");
model.IsRunning=true;await Task.Delay(30);
Check(!view.FindControl<CheckBox>("AutoResetCheckBox")!.IsEnabled&&!view.FindControl<NumericUpDown>("ResetDelayInput")!.IsEnabled,"运行中禁止修改自动复位和延时");
model.AutoResetOnComplete=true;model.FrameStride=8;model.ResetDelaySec=20;
Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4,"运行中参数赋值也不会覆盖已保存设置");
model.IsRunning=false;
using var rendered=new RenderTargetBitmap(new PixelSize(900,720));rendered.Render(dialog);
var screenshots=Path.Combine(Directory.GetCurrentDirectory(),"..","scratch","screenshots");Directory.CreateDirectory(screenshots);
rendered.Save(Path.Combine(screenshots,"runtime-settings.png"));
}
finally{model.IsRunning=false;dialog.Close();}
_exit=0;return;
}
if(_agentSettingsFile is not null)
{
var model=new RecipeEditorViewModel();
@ -861,6 +891,11 @@ internal static class Smoke
try
{
Check(settingsView.GetVisualDescendants().OfType<ComboBox>().Count()==2&&settingsView.GetVisualDescendants().OfType<Slider>().Count()==1,"Runtime settings retain camera, recipe and stride while removing YOLO threshold");
Check(settingsView.GetVisualDescendants().OfType<CheckBox>().Any(c=>c.Content?.ToString()=="完成后自动复位")
&& settingsView.GetVisualDescendants().OfType<NumericUpDown>().Any(),"运行设置包含自动复位和复位延时");
sop.FrameStride=3;sop.AutoResetOnComplete=false;sop.ResetDelaySec=4;
var runtime=RuntimeSettingsStore.Current.Read()!;
Check(runtime.FrameStride==3&&!runtime.AutoResetOnComplete&&runtime.ResetDelaySec==4,"运行设置修改后独立持久化");
Save(settingsWindow,"runtime-settings-no-yolo");
}
finally{settingsWindow.Close();}

View File

@ -34,6 +34,7 @@ internal static class Program
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
CheckAiFlow();
CheckSequenceEditor();
CheckRuntimeSettings(root);
StepTransferChecks.Run(root);
AgentDraftVerificationChecks.Run(root);
StandardVideoImportChecks.Run(root);
@ -66,6 +67,21 @@ internal static class Program
Console.WriteLine("PASS: 编辑器过程时序模式及观察参数往返保留");
}
private static void CheckRuntimeSettings(string root)
{
var store = new SopHelper.Models.RuntimeSettingsStore(Path.Combine(root, "runtime-migration"));
var legacy = SopConfigLoader.Parse("sop: {settings: {frame_stride: 3, auto_reset_on_complete: false, reset_delay_sec: 4}}");
var options = store.LoadOrMigrate(legacy);
Check(options.FrameStride == 3 && !options.AutoResetOnComplete && options.ResetDelaySec == 4, "首次使用旧配方时迁移运行设置");
options.FrameStride = 2; options.AutoResetOnComplete = true; options.ResetDelaySec = 6;
store.Save(options);
var other = SopConfigLoader.Parse("sop: {settings: {frame_stride: 9, auto_reset_on_complete: false, reset_delay_sec: 30}}");
var loaded = new SopHelper.Models.RuntimeSettingsStore(Path.Combine(root, "runtime-migration")).LoadOrMigrate(other);
loaded.Apply(other);
Check(other.Sop.Settings.FrameStride == 2 && other.Sop.Settings.AutoResetOnComplete && other.Sop.Settings.ResetDelaySec == 6,
"重启及切换配方沿用独立运行设置,不被旧配方覆盖");
}
private static void CheckAiFlow()
{
var config = SopConfigLoader.Parse("""
@ -167,6 +183,7 @@ internal static class Program
var parameters = view.FindControl<ScrollViewer>("StepParameters")!;
Check(!view.GetVisualDescendants().OfType<TabItem>().Any(t => t.Header?.ToString() == "区域"),
"Region editing is integrated into the step tab");
Check(!view.GetVisualDescendants().OfType<TabItem>().Any(t => t.Header?.ToString() == "全局设置"), "配方编辑不再包含全局设置页");
var regionNavigation = view.FindControl<ListBox>("StepRegionNavigation")!;
var regionParameters = view.FindControl<ScrollViewer>("RegionParameters")!;
Check(regionNavigation.TranslatePoint(default, window)!.Value.Y >= stepVideo.TranslatePoint(default, window)!.Value.Y + stepVideo.Bounds.Height

View File

@ -5,6 +5,7 @@ using SopHelper.Engine.Common;
using SopHelper.Engine.Sop;
if (args.Contains("--dlite-audit")) { await DliteAudit.RunAsync(args); return; }
SettingsMigrationChecks.Run();
static void Check(bool value, string message) { if (!value) throw new Exception(message); }
Check(typeof(SopEngine).Assembly.GetType("SopHelper.Engine.Inference.YoloDetector") is null, "运行程序集必须移除 YOLO 检测器");

View File

@ -0,0 +1,40 @@
using SopHelper.Engine.Sop;
internal static class SettingsMigrationChecks
{
public static void Run()
{
var config = SopConfigLoader.Parse("""
sop:
name: 旧设置迁移
settings: { stable_frames: 9, position_tolerance: 35, enable_timeout_detection: false, frame_stride: 3, auto_reset_on_complete: false, reset_delay_sec: 4, confidence_threshold: 0.8 }
steps:
- id: 1
timeout: 10
detection: { method: hand_in_region, stable_frames: 0, tolerance: 0 }
- id: 2
timeout: 20
detection: { method: hand_in_region, stable_frames: 2, tolerance: 3 }
""");
Check(config.Sop.HasLegacySettings && config.Sop.Steps[0].Detection is { StableFrames: 9, Tolerance: 35 }, "旧配方继承的稳定帧和容差迁移到步骤");
Check(config.Sop.Steps[1].Detection is { StableFrames: 2, Tolerance: 3 } && config.Sop.Steps.All(s => s.Timeout == 0), "显式步骤参数优先,关闭的超时告警迁移为步骤超时0");
var yaml = SopConfigLoader.ToYaml(config);
var restored = SopConfigLoader.Parse(yaml);
Check(!yaml.Contains("settings:") && !yaml.Contains("has_legacy_settings") && !restored.Sop.HasLegacySettings
&& restored.Sop.Steps[0].Detection is { StableFrames: 9, Tolerance: 35 }, "保存后的配方不含全局或运行设置且保留步骤行为");
Check(config.Sop.Settings.FrameStride == 3 && !config.Sop.Settings.AutoResetOnComplete && config.Sop.Settings.ResetDelaySec == 4,
"配方导出不修改内存中待迁移的旧运行参数");
restored.Sop.Steps[0].Timeout = 2;
var detector = new ViolationDetector(restored.Sop.Settings);
Check(detector.CheckTimeout(restored.Sop.Steps[0], DateTime.Now.AddSeconds(-3)) is not null, "步骤正数超时直接启用违规告警");
restored.Sop.Steps[0].Timeout = 0;
Check(new ViolationDetector(restored.Sop.Settings).CheckTimeout(restored.Sop.Steps[0], DateTime.Now.AddHours(-1)) is null, "步骤超时0关闭违规告警");
var zero = SopConfigLoader.Parse("sop: {steps: [{id: 1, detection: {method: hand_in_region, tolerance: 0, stable_frames: 1}}]}");
Check(SopConfigLoader.Parse(SopConfigLoader.ToYaml(zero)).Sop.Steps[0].Detection!.Tolerance == 0, "新配方的零像素容差不再继承隐藏的全局容差");
}
private static void Check(bool condition, string message)
{
if (!condition) throw new Exception(message);
Console.WriteLine("PASS: " + message);
}
}