From 674e16e8841e328782b7d14a0176768dc620ce12 Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Thu, 19 Nov 2026 18:09:24 +0800
Subject: [PATCH] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E9=85=8D=E6=96=B9=E5=85=A8?=
=?UTF-8?q?=E5=B1=80=E8=AE=BE=E7=BD=AE=E5=B9=B6=E7=8B=AC=E7=AB=8B=E4=BF=9D?=
=?UTF-8?q?=E5=AD=98=E8=BF=90=E8=A1=8C=E5=8F=82=E6=95=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 6 +-
.../Models/RuntimeSettingsStore.cs | 52 +++++++++++
.../Training/SopVideoFlowTest.cs | 1 +
.../VVMs/RecipeEditor/EditorNodes.cs | 90 +------------------
.../VVMs/RecipeEditor/RecipeEditor.axaml | 42 ---------
.../RecipeEditor/RecipeEditorViewModel.cs | 2 +
.../RuntimeSettings/RuntimeSettings.axaml | 8 +-
.../VVMs/SopPage/SopPageViewModel.cs | 29 +++++-
.../Pipeline/DetectionPipeline.cs | 2 +
.../Sop/ConditionEvaluator.cs | 10 +--
.../Sop/SopConfig.cs | 16 ++--
.../Sop/SopConfigLoader.cs | 23 ++++-
.../Sop/SopEngine.BufferedEvidence.cs | 2 +-
.../Sop/SopEngine.cs | 1 +
.../Sop/SopStepTransfer.cs | 3 +
.../Sop/ViolationDetector.cs | 46 +---------
tests/Avalonia.Smoke/Program.cs | 35 ++++++++
tests/VideoFlowTest.Smoke/Program.cs | 17 ++++
tests/VisionDecision.Smoke/Program.cs | 1 +
.../SettingsMigrationChecks.cs | 40 +++++++++
20 files changed, 229 insertions(+), 197 deletions(-)
create mode 100644 src/SopHelper.Avalonia/Models/RuntimeSettingsStore.cs
create mode 100644 tests/VisionDecision.Smoke/SettingsMigrationChecks.cs
diff --git a/README.md b/README.md
index cc94dfa..5462272 100644
--- a/README.md
+++ b/README.md
@@ -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 均不能代替实际采集计数。
diff --git a/src/SopHelper.Avalonia/Models/RuntimeSettingsStore.cs b/src/SopHelper.Avalonia/Models/RuntimeSettingsStore.cs
new file mode 100644
index 0000000..dac9287
--- /dev/null
+++ b/src/SopHelper.Avalonia/Models/RuntimeSettingsStore.cs
@@ -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);
+ }
+}
+
+/// 执行方式独立保存,切换或导出配方不会覆盖运行设置。
+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(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); }
+ }
+}
diff --git a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs
index cdfa118..ec0cd09 100644
--- a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs
+++ b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs
@@ -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);
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
index 4a2a474..4c08be1 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
@@ -215,7 +215,6 @@ public class RecipeNode : EditorNode
}
/// 全局设置(sop.settings)
- public RecipeSettingsNode Settings { get; } = new();
/// 区域(sop.regions,键 = 配方里引用的区域名)
public ObservableCollection Regions { get; } = [];
@@ -390,6 +389,7 @@ public class RecipeNode : EditorNode
///
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
}
}
-///
-/// sop.settings
-///
-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;
- /// 全局置信度阈值
- public float ConfidenceThreshold
- {
- get { return _confidenceThreshold; }
- set { SetProperty(ref _confidenceThreshold, value); }
- }
-
- /// 默认稳定帧数(条件未写 stable_frames 时用它)
- public int StableFrames
- {
- get { return _stableFrames; }
- set { SetProperty(ref _stableFrames, value); }
- }
-
- /// 区域命中容差(像素)
- public float PositionTolerance
- {
- get { return _positionTolerance; }
- set { SetProperty(ref _positionTolerance, value); }
- }
-
- /// 启用超时违规
- public bool EnableTimeoutDetection
- {
- get { return _enableTimeoutDetection; }
- set { SetProperty(ref _enableTimeoutDetection, value); }
- }
-
- /// 整轮完成后自动复位
- public bool AutoResetOnComplete
- {
- get { return _autoResetOnComplete; }
- set { SetProperty(ref _autoResetOnComplete, value); }
- }
-
- /// 复位前停留秒数
- public int ResetDelaySec
- {
- get { return _resetDelaySec; }
- set { SetProperty(ref _resetDelaySec, value); }
- }
-
- /// 抽帧间隔(1=每帧都判)
- public int FrameStride
- {
- get { return _frameStride; }
- set { SetProperty(ref _frameStride, value); }
- }
-
- /// 读入
- 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;
- }
-
- /// 写出
- 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;
- }
-}
-
///
/// sop.model
///
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
index 9f62fbf..5bc4316 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
@@ -393,48 +393,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
index 73eb993..fb34e15 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
@@ -147,6 +147,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
else if (_cameraInfo is null) PreviewStatus = "请在 SOP 页先选择相机,或打开图片;选中区域后在图上拖动画框";
var config = parameters.GetValue("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);
diff --git a/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml b/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml
index 1b68c41..013cdc7 100644
--- a/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml
+++ b/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml
@@ -51,13 +51,19 @@
+
+
+
+
+
-
+
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index 220ef52..6f44f6d 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -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();
///
/// 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
/// 抽帧间隔
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));
}
/// 打开所选相机的独立配置窗口
@@ -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);
diff --git a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
index 428ca15..be0e4bc 100644
--- a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
@@ -118,6 +118,8 @@ public class DetectionPipeline : IDisposable
///
/// 启动(相机需已连接)
///
+ public void SetFrameStride(int stride) => _options.FrameStride = Math.Max(1, stride);
+
public async Task StartAsync()
{
ObjectDisposedException.ThrowIf(_disposed, this);
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs b/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs
index cf79d00..d79756c 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs
@@ -25,7 +25,6 @@ public class ConditionResult
///
public class ConditionEvaluator
{
- private readonly SopSettings _settings;
private readonly Dictionary _regions;
/// 稳定帧计数:key = "步骤Id:条件序号"
@@ -44,7 +43,6 @@ public class ConditionEvaluator
///
public ConditionEvaluator(SopSettings settings, Dictionary 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
///
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
///
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)
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
index 6b55d23..5c74fd8 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
@@ -33,8 +33,15 @@ public class SopBody
[YamlMember(DefaultValuesHandling = DefaultValuesHandling.OmitNull)]
public List? Parts { get; set; }
- /// 全局设置
- public SopSettings Settings { get; set; } = new();
+ /// 引擎运行参数及旧配方迁移值;保存配方时不写出。
+ private SopSettings _settings = new();
+ public SopSettings Settings
+ {
+ get => _settings;
+ set { _settings = value ?? new(); HasLegacySettings = true; }
+ }
+ [YamlIgnore]
+ public bool HasLegacySettings { get; set; }
/// 区域定义(键 = 配方里引用的区域名)
public Dictionary Regions { get; set; } = new(StringComparer.OrdinalIgnoreCase);
@@ -47,13 +54,10 @@ public class SopBody
}
///
-/// sop.settings
+/// 引擎运行参数;旧配方 settings 只读兼容。
///
public class SopSettings
{
- /// 全局置信度阈值
- public float ConfidenceThreshold { get; set; } = 0.6f;
-
/// 默认稳定帧数(条件未写 stable_frames 时用它)
public int StableFrames { get; set; } = 5;
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
index 91af5b4..45eb564 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
@@ -37,6 +37,7 @@ public static partial class SopConfigLoader
var config = deserializer.Deserialize(yaml) ?? new SopConfig();
+ MigrateStepSettings(config);
Validate(config);
return config;
@@ -48,13 +49,17 @@ public static partial class SopConfigLoader
///
public static string ToYaml(SopConfig config)
{
+ // 在副本上迁移;导出不能改变正在编辑或运行的对象。
+ var saved = System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.Serialize(config))!;
+ MigrateStepSettings(saved, config.Sop.HasLegacySettings);
var serializer = new SerializerBuilder()
+ .WithAttributeOverride(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;
+ }
+
///
/// 写回文件,并顺手校验一遍(校验提醒随返回值给出,编辑器要显示)。
///
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.BufferedEvidence.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.BufferedEvidence.cs
index 0a02f19..961f61d 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.BufferedEvidence.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.BufferedEvidence.cs
@@ -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? captureJpeg, Func? captureDecisionImage)
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
index 62c1f3f..3c806a1 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
@@ -125,6 +125,7 @@ public partial class SopEngine
public void Load(SopConfig config)
{
Stop();
+ SopConfigLoader.MigrateStepSettings(config);
_config = config;
Statistics = GetStatistics(config.Sop.Name);
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopStepTransfer.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopStepTransfer.cs
index eb69f35..24321a4 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopStepTransfer.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopStepTransfer.cs
@@ -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;
}
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/ViolationDetector.cs b/src/SopHelper.CrossPlatform.Engine/Sop/ViolationDetector.cs
index cf59154..a9aa431 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/ViolationDetector.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/ViolationDetector.cs
@@ -1,5 +1,3 @@
-using SopHelper.Engine.Common;
-
namespace SopHelper.Engine.Sop;
///
@@ -24,7 +22,7 @@ public class ViolationEvent
}
///
-/// 违规判定:超时 / 必留物被拿走。
+/// 步骤超时违规判定。
/// 每类违规带冷却,避免逐帧刷屏(参考项目用 3s,这里保持一致)。
///
public class ViolationDetector
@@ -32,18 +30,13 @@ public class ViolationDetector
/// 同类违规最小间隔
private static readonly TimeSpan Cooldown = TimeSpan.FromSeconds(3);
- private readonly SopSettings _settings;
private readonly Dictionary _lastFired = [];
- /// 每个必留物体最近一次被检出的时刻(判"被拿走"用)
- private readonly Dictionary _lastSeenObject = new(StringComparer.OrdinalIgnoreCase);
-
///
/// 违规判定
///
public ViolationDetector(SopSettings settings)
{
- _settings = settings;
}
///
@@ -52,7 +45,6 @@ public class ViolationDetector
public void Reset()
{
_lastFired.Clear();
- _lastSeenObject.Clear();
}
///
@@ -60,7 +52,6 @@ public class ViolationDetector
///
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)");
}
- ///
- /// 必留物被拿走:本步期间 must_keep 的物体连续若干帧消失
- ///
- 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));
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index 6e26eac..d340f35 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -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();
+ 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().Single().Value=3;
+ view.FindControl("AutoResetCheckBox")!.IsChecked=false;
+ view.FindControl("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();
+ 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("AutoResetCheckBox")!.IsEnabled&&!view.FindControl("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().Count()==2&&settingsView.GetVisualDescendants().OfType().Count()==1,"Runtime settings retain camera, recipe and stride while removing YOLO threshold");
+ Check(settingsView.GetVisualDescendants().OfType().Any(c=>c.Content?.ToString()=="完成后自动复位")
+ && settingsView.GetVisualDescendants().OfType().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();}
diff --git a/tests/VideoFlowTest.Smoke/Program.cs b/tests/VideoFlowTest.Smoke/Program.cs
index a567bda..8277c7d 100644
--- a/tests/VideoFlowTest.Smoke/Program.cs
+++ b/tests/VideoFlowTest.Smoke/Program.cs
@@ -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("StepParameters")!;
Check(!view.GetVisualDescendants().OfType().Any(t => t.Header?.ToString() == "区域"),
"Region editing is integrated into the step tab");
+ Check(!view.GetVisualDescendants().OfType().Any(t => t.Header?.ToString() == "全局设置"), "配方编辑不再包含全局设置页");
var regionNavigation = view.FindControl("StepRegionNavigation")!;
var regionParameters = view.FindControl("RegionParameters")!;
Check(regionNavigation.TranslatePoint(default, window)!.Value.Y >= stepVideo.TranslatePoint(default, window)!.Value.Y + stepVideo.Bounds.Height
diff --git a/tests/VisionDecision.Smoke/Program.cs b/tests/VisionDecision.Smoke/Program.cs
index 0b1f539..4f9e3ea 100644
--- a/tests/VisionDecision.Smoke/Program.cs
+++ b/tests/VisionDecision.Smoke/Program.cs
@@ -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 检测器");
diff --git a/tests/VisionDecision.Smoke/SettingsMigrationChecks.cs b/tests/VisionDecision.Smoke/SettingsMigrationChecks.cs
new file mode 100644
index 0000000..0b5d535
--- /dev/null
+++ b/tests/VisionDecision.Smoke/SettingsMigrationChecks.cs
@@ -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);
+ }
+}